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

喜夏-厌秋 提交于 2019-12-11 05:14:02

问题


I have a network state change Broadcast Receiver setup for my app. I need to receive wifi connect-disconnect events even when phone is in sleep mode. This works when phone is charging and in sleep, but doesn't when its not in sleep.

here is code

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
        } 
    }
}
}

here is how its registered in manifest

 <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>

I am aware of doze mode related issue in Marshmallow and above devices but I am not even receiving events in Kitkat devices when phone is in sleep and its not connected to charger.


回答1:


Use a 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.



来源:https://stackoverflow.com/questions/41057584/connectivity-change-broadcast-receiver-not-triggering-when-phone-is-in-sleep-mod

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!