我正在使用标准的Android代码来监听网络连接的变化。
但是在我的Moto G(Lollipop)中,每当我从一个网络切换到另一个网络时,我都没有收到网络断开的事件。
如果我从NetworkA切换到NetworkB。我正在为NetworkB获取CONNECTED事件,但没有为NetworkA获取断开连接的事件。
在某些三星设备(MarshMallow)上也会发生这种情况
是否有可靠的方式获得有关网络连接更改的通知?
注册CONNECTIVITY_CHANGE接收器
<receiver
android:name=".MyReceiver"
android:exported="true">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
MyReciver代码
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent intent) {
LOG.i(" Received connectivity change event. ");
ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(
Context.CONNECTIVITY_SERVICE);
final String action = intent.getAction();
String networkType = intent.getParcelableExtra(
ConnectivityManager.EXTRA_NETWORK_TYPE);
final NetworkInfo otherNetworkInfo = intent.getParcelableExtra(
ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);
final NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
final String reason = intent.getParcelableExtra(ConnectivityManager.EXTRA_REASON);
final String connectivityAction = intent.getParcelableExtra(
ConnectivityManager.CONNECTIVITY_ACTION);
LOG.i(String.format("+++++ action = %s, networkType = %s, otherNetworkInfo = %s, "
+ "reason = %s, connectAction = %s, ActiveNetworkInfo = %s", action, networkType,
otherNetworkInfo, reason, connectivityAction, networkInfo));
}
}