BroadcastReceiver 无法访问互联网

BroadcastReceiver has no internet access

我的广播接收器出现问题。

我设置了早上 6 点的闹钟,它必须触发我的广播接收器,它只需要从互联网下载一些数据并进行处理。

例如,如果我将闹钟设置为下午 3 点,它就可以正常工作。但是问题是早上6点,因为没有网络连接,下载失败。

我在尝试下载之前执行了部分唤醒锁定。会不会和这个有关? phone 是否进入深度睡眠和部分唤醒锁定不够?

还能是什么?我已经仔细检查以启用 phone 网络数据,并且我确实在夜间收到电子邮件和 whatsapp。

有没有办法让 android 恢复连接?

非常欢迎任何提示或帮助!

此致, 费德里科

我的代码:

来自 BroadcastReceiver 的 OnReceive 方法:

@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();
}

CommonsWare 让我走上正轨。

答案是打瞌睡模式:android 6 及更高版本可以让 phone 进入打瞌睡模式,在该模式下,应用程序将无法访问互联网(除其他外)。因此,如果您设置了闹钟和唤醒锁,您将获得 CPU 访问权限,但无法访问互联网。文档说如果设备插入它不会进入打瞌睡模式,但在我的情况下它确实进入了尽管插入状态:

来自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.

这令人困惑。

无论如何,我尝试将我的应用列入白名单,它开始工作得很好。闹钟在早上 6 点响起,广播接收器现在可以访问互联网。

再次来自 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.

希望我说清楚了,这对其他人有帮助。

感谢 CommonsWare。