Android:互联网连接更改监听器

我已经有了这个代码来监听连接变化 –

public class NetworkStateReceiver extends BroadcastReceiver { public void onReceive(Context context, Intent intent) { Log.d("app","Network connectivity change"); if(intent.getExtras() != null) { NetworkInfo ni = (NetworkInfo) intent.getExtras().get(ConnectivityManager.EXTRA_NETWORK_INFO); if(ni != null && ni.getState() == NetworkInfo.State.CONNECTED) { Log.i("app", "Network " + ni.getTypeName() + " connected"); } } if(intent.getExtras().getBoolean(ConnectivityManager.EXTRA_NO_CONNECTIVITY, Boolean.FALSE)) { Log.d("app", "There's no network connectivity"); } } } 

我使用这个代码检查互联网连接 – 互联网检查

但问题是,如果networking突然失去互联网连接而没有任何连接变化,这个代码是没有用的。 有什么办法可以创build广播接收器监听的互联网连接变化? 我有一个Web应用程序,突然的互联网连接更改可能会导致问题。

Solutions Collecting From Web of "Android:互联网连接更改监听器"

尝试这个

  public class NetworkUtil { public static int TYPE_WIFI = 1; public static int TYPE_MOBILE = 2; public static int TYPE_NOT_CONNECTED = 0; public static final int NETWORK_STATUS_NOT_CONNECTED=0,NETWORK_STAUS_WIFI=1,NETWORK_STATUS_MOBILE=2; public static int getConnectivityStatus(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); if (null != activeNetwork) { if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) return TYPE_WIFI; if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) return TYPE_MOBILE; } return TYPE_NOT_CONNECTED; } public static int getConnectivityStatusString(Context context) { int conn = NetworkUtil.getConnectivityStatus(context); int status = 0; if (conn == NetworkUtil.TYPE_WIFI) { status = NETWORK_STAUS_WIFI; } else if (conn == NetworkUtil.TYPE_MOBILE) { status =NETWORK_STATUS_MOBILE; } else if (conn == NetworkUtil.TYPE_NOT_CONNECTED) { status = NETWORK_STATUS_NOT_CONNECTED; } return status; } } 

而对于BroadcastReceiver

 public class NetworkChangeReceiver extends BroadcastReceiver { @Override public void onReceive(final Context context, final Intent intent) { int status = NetworkUtil.getConnectivityStatusString(context); Log.e("Sulod sa network reciever", "Sulod sa network reciever"); if (!"android.net.conn.CONNECTIVITY_CHANGE".equals(intent.getAction())) { if(status==NetworkUtil.NETWORK_STATUS_NOT_CONNECTED){ new ForceExitPause(context).execute(); }else{ new ResumeForceExitPause(context).execute(); } } } } 

不要忘记把它放到你的AndroidManifest.xml中

  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.INTERNET" /> <receiver android:name="NetworkChangeReceiver" android:label="NetworkChangeReceiver" > <intent-filter> <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> <action android:name="android.net.wifi.WIFI_STATE_CHANGED" /> </intent-filter> </receiver> 

希望这会帮助你干杯!