5

前言:这在运行 6.0.1 的手机上运行良好。但在我运行 7.1.1 的手机上,它不是,如下图所示。

build.gradle(模块:应用程序)

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

AndroidManifest.xml

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

    <receiver
        android:name=".NetworkChangeReceiver"
        android:enabled="true"
        android:exported="true">
        <intent-filter>
            <action android:name="android.net.wifi.WIFI_STATE_CHANGED"/>
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
        </intent-filter>
    </receiver>

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。

4

1 回答 1

4

根据android 文档

面向 Android 7.0(API 级别 24)及更高版本的应用如果在其清单中声明广播接收器,则不会接收 CONNECTIVITY_ACTION 广播。如果应用程序使用 Context.registerReceiver() 注册其 BroadcastReceiver 并且该上下文仍然有效,则应用程序仍将接收 CONNECTIVITY_ACTION 广播。

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

registerReceiver(new NetworkChangeReceiver(), new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"))
于 2017-03-11T19:51:48.850 回答