BroadcastReceiver has no internet access

2019-08-04 16:35发布

问题:

I'm facing a problem with my broadcast receiver.

I have set an alarm for 6am, it has to fire my broadcast receiver, which only has to download some data from internet and process it.

If I set the alarm for 3pm, for example, it works fine. But the problem is at 6am, it fails downloading because it does not have network connectivity.

I perform a partial wake lock before attempting download. Can it be related to this? Does the phone enter some deep sleep and partial wake lock is not enough?

What else can it be? I have double checked to leave the phone with Network Data enabled, and I do receive emails and whatsapp during night time.

Is there a way to make android recover that connectivity?

Any hint or help is more than welcome!

Best regards, Federico.

My code:

OnReceive method from BroadcastReceiver:

@Override
public void onReceive(Context context, Intent intent) {
    ...
    // acquire partial wake lock
    _PowerManager.acquire();

    // check internet access
    if (!_Utils.isDataEnabled()){
        // here is where it enters at 6am, isDataEnabled return false, so it enters here
        _Log.d("_BroadcastReceiver_Synchronize:onReceive","No internet, cancel sinc");
         // release partial wake lock
        _PowerManager.release();
        return;
    }

    // excecute async task that downloads data
    _WebServicesGet ws = new _WebServicesGet(null, null, null);
    ws.syncAll(this, false);
    return;
}

_Utils.isDataEnabled:

public static Boolean isDataEnabled() {
    // this method returns false at 6am
    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

回答1:

CommonsWare put me in the right track.

The answer was the doze mode: android 6 and up can put the phone into a doze mode, in which apps won't receive internet access (among other things). So if you have set an alarm and a wake lock, you will get CPU access but no Internet access. The documentation says that if the device is plugged in it will not enter doze mode, but in my case it did enter despite the plug status:

From official documentation:

If a user leaves a device unplugged and stationary for a period of time, with the screen off, the device enters Doze mode.

That was confusing.

Any way, I tried whitelisting my app, and it started working just fine. Alarm goes off at 6am, and the broadcast receiver now has internet access.

Again from official documentation:

Users can manually configure the whitelist in Settings > Battery > Battery Optimization. Alternatively, the system provides ways for apps to ask users to whitelist them.

Hope I made myself clear, and that this helps someone else.

Thanks to CommonsWare.