可以使用广播监听网络的改变
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(); } } } }