我Broadcast Receiver
为我的应用设置了网络状态更改设置。即使手机处于睡眠模式,我也需要接收 wifi 连接断开事件。这在手机正在充电并处于睡眠状态时有效,但在手机未处于睡眠状态时无效。
这是代码
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 及以上设备中与打盹模式相关的问题,但当手机处于睡眠状态且未连接到充电器时,我什至没有在 Kitkat 设备中收到事件。