android系统在网络状态发生变化的时候,会发出 android.net.conn.CONNECTIVITY_CHANGE 广播我们只要注册该广播的监听器即可实现网络状态的监听,代码如下:
在xml里配置receiver:
1 <receiver android:name="NetworkStatusReceiver"> 2 <intent-filter> 3 <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> 4 </intent-filter> 5 </receiver>
java代码:
1 public class NetworkStatusReceiver extends BroadcastReceiver { 2 3 @Override 4 public void onReceive(Context context, Intent intent) { 5 ConnectivityManager mgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 6 NetworkInfo[] info = mgr.getAllNetworkInfo(); 7 if (info != null) { 8 for (int i = 0; i < info.length; i++) { 9 if (info[i].getState() == NetworkInfo.State.CONNECTED) { 10 // 启动你的服务 11 break; 12 } 13 } 14 } 15 } 16 }