java – NetworkInfo没有正确响应运行Nougat的手机上的网络更改

前端之家收集整理的这篇文章主要介绍了java – NetworkInfo没有正确响应运行Nougat的手机上的网络更改前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

前言:在运行6.0.1的手机上运行正常.但是在运行7.1.1的手机上,它不是,如下所示.

build.gradle(模块:app)

compileSdkVersion 25
buildToolsVersion "25.0.0"
applicationId "com.gesslar.threshvote"
minSdkVersion 19
targetSdkVersion 25

AndroidManifest.xml中

NetworkUtil.java
我有一个BroadcastReceiver,我用它来简单地调用NetworkUtil.updateNetworkStatus(context);

public static void updateNetworkStatus(Context context) {
    final ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    final NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
    if (activeNetwork == null) {
        Log.d(TAG,"NO CONNECTION INFORMATION");
        return;
    }
    if (activeNetwork.isConnected()) {
        Log.d(TAG,"WE ARE CONNECTED TO A NETWORK");
    } else {
        Log.d(TAG,"WE ARE NOT CONNECTED TO A NETWORK");
        return;
    }
    Log.d(TAG,"NETWORK TYPE: " + activeNetwork.getTypeName());
}

从WiFi和数据连接开始我已经完成了以下测试
关闭WiFi

03-08 20:15:04.664 29796-29796/com.gesslar.threshvote D/NetworkUtil: NO CONNECTION INFORMATION

打开WiFi:

03-08 20:15:26.333 29796-29796/com.gesslar.threshvote D/NetworkUtil: WE ARE CONNECTED TO A NETWORK
03-08 20:15:26.333 29796-29796/com.gesslar.threshvote D/NetworkUtil: NETWORK TYPE: MOBILE

关闭数据:

No log line written

打开数据:

No log line written

关闭WiFi然后关闭数据:

1) 03-08 20:17:13.029 29796-29796/com.gesslar.threshvote D/NetworkUtil: NO CONNECTION INFORMATION
2) No log line written

关闭两个,打开WiFi:

03-08 20:18:00.198 29796-29796/com.gesslar.threshvote D/NetworkUtil: NO CONNECTION INFORMATION
^ showed as soon as it started seeking for WiFi,but no further log line was written when WiFi became active.

我对结果感到非常困惑.我在其他地方看到我应该在运行时绑定它,但是,我唯一的活动是Preferences活动.该应用程序不具有运行时UI,而是使用后台IntentService和Notifications.

最佳答案
根据android docs,

Apps targeting Android 7.0 (API level 24) and higher do not receive
CONNECTIVITY_ACTION broadcasts if they declare the broadcast receiver
in their manifest. Apps will still receive CONNECTIVITY_ACTION
broadcasts if they register their BroadcastReceiver with
Context.registerReceiver() and that context is still valid.

所以你需要做的是启动一个服务,创建一个广播接收器NetworkChangeReceiver的新实例并注册它以通过使用它来监听它到android.net.conn.CONNECTIVITY_CHANGE

registerReceiver(new NetworkChangeReceiver(),new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"))

猜你在找的Android相关文章