当 phone 处于睡眠模式时,连接更改广播接收器未触发

Connectivity Change Broadcast receiver not triggering when phone is in sleep mode

我为我的应用设置了网络状态更改 Broadcast Receiver。即使 phone 处于睡眠模式,我也需要接收 wifi 连接-断开事件。这在 phone 正在充电和处于睡眠状态时有效,但在未处于睡眠状态时无效。

这是代码

public class NetworkConnectionReceiver extends WakefulBroadcastReceiver {
public static final String INTENT_CONNECTIVITY_CHANGE = "android.net.conn.CONNECTIVITY_CHANGE";

@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equalsIgnoreCase(INTENT_CONNECTIVITY_CHANGE)) {
        NetworkChangedEvent event = new NetworkChangedEvent();
        NetworkInfo activeNetworkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
        boolean wifiConnected = activeNetworkInfo != null
                && activeNetworkInfo.isConnected()
                && activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI;

        if (wifiConnected) {
            // start a service here
        } 
    }
}
}

这是它在清单中的注册方式

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

我知道 Marshmallow 及以上设备中的打瞌睡模式相关问题,但当 phone 处于睡眠状态且未连接充电器时,我什至没有收到 Kitkat 设备中的事件。

使用 WakefulBroadcastReceiver:

Helper for the common pattern of implementing a BroadcastReceiver that receives a device wakeup event and then passes the work off to a Service, while ensuring that the device does not go back to sleep during the transition.

This class takes care of creating and managing a partial wake lock for you; you must request the WAKE_LOCK permission to use it.