Android中监听网络连接问题
可以使用广播监听网络的改变
AndroidManifest.xml
1
2
3
4
5
6
7
8
9 |
<receiver android:name= "com.relonger.oufengliyuan.receiver.ConnectionChangeReceiver" android:label= "NetworkConnection" > <intent-filter> <action android:name= "android.net.conn.CONNECTIVITY_CHANGE" /> <action android:name= "android.net.wifi.WIFI_STATE_CHANGED"
/> <action android:name= "android.net.wifi.STATE_CHANGE"
/> </intent-filter> </receiver> |
1 |
ConnectionChangeReceiver.java |
package com.relonger.oufengliyuan.receiver; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.widget.Toast; //注册一个广播接收者,接收网络连接状态改变广播 public class ConnectionChangeReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { ConnectivityManager connectivityManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetInfo = connectivityManager .getActiveNetworkInfo(); NetworkInfo mobNetInfo = connectivityManager .getNetworkInfo(ConnectivityManager.TYPE_MOBILE); NetworkInfo mWiFiNetworkInfo = connectivityManager .getNetworkInfo(ConnectivityManager.TYPE_WIFI); /* if (!activeNetInfo.isConnected()) { Toast.makeText(context, "Active Network Type : " + activeNetInfo.getTypeName(), Toast.LENGTH_SHORT).show(); } if (!mobNetInfo.isConnected()) { Toast.makeText(context, "Mobile Network Type : " + mobNetInfo.getTypeName(), Toast.LENGTH_SHORT).show(); }*/ if (mWiFiNetworkInfo != null) { if(!mWiFiNetworkInfo.isConnected()){ Toast.makeText(context,"WIFI未连接",Toast.LENGTH_SHORT).show(); } } } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。