打瞌睡模式 - 前台服务是否继续 运行?

Doze mode - do foreground services continue to run?

我很困惑 并试图弄清楚前台服务是否会 运行 当设备进入深度休眠模式时。有人可以澄清一下。我想知道在 marshmallow 和更高版本上前台服务是否可以继续 运行。我一直认为当设备休眠时,所有线程甚至前台服务都被暂停。

我看到了 doze mode restrictions,但与前台服务无关。如果我的服务超过休眠模式安全设置,我会很困惑。

据我所知,在打瞌睡模式限制中,网络呼叫已停止。但是可以说我正在做一些长时间的 运行ning 主线程工作,这意味着它可以继续 运行 对吗?即使在打瞌睡模式下?

打瞌睡模式用于节省电池电量。您应该将您的应用程序放入白名单以停用打瞌睡模式。

来源:https://developer.android.com/training/monitoring-device-state/doze-standby

Support for other use cases Almost all apps should be able to support Doze by managing network connectivity, alarms, jobs, and syncs properly, and by using FCM high-priority messages. For a narrow set of use cases, this might not be sufficient. For such cases, the system provides a configurable whitelist of apps that are partially exempt from Doze and App Standby optimizations.

An app that is whitelisted can use the network and hold partial wake locks during Doze and App Standby. However, other restrictions

still apply to the whitelisted app, just as they do to other apps. For example, the whitelisted app’s jobs and syncs are deferred (on API level 23 and below), and its regular AlarmManager alarms do not fire. An app can check whether it is currently on the exemption whitelist by calling isIgnoringBatteryOptimizations().

以及如何将您的应用程序插入白名单: 1. 步骤 --> 在您的 xml 文件中添加此权限。

<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />

2.Step İgnore 电池优化

if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    Intent intent = new Intent();
    String packageName = getPackageName();
    PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
    if (!pm.isIgnoringBatteryOptimizations(packageName)) {
        intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
        intent.setData(Uri.parse("package:" + packageName));
        startActivity(intent);
    }
}

前台服务在休眠模式下不会被终止,这是覆盖休眠模式的一个很好的解决方法。 关闭前台服务高度依赖移动设备 OS。 像华为一样,时间一长就把前台服务杀掉,时间长短你也说不准。 如果检测到意外的电池消耗,其他一些手机会终止最旧的前台服务。 去年,我花了大约 6 个月的时间观察手机在打瞌睡模式是否激活时杀死前台服务的行为。 我尝试了不止一种解决方案来覆盖打瞌睡模式以每 10 秒检测一次位置,最好的解决方案是前台服务。 所以你会在某些手机上遇到意外行为,但它是打瞌睡和待机模式的最佳解决方案。 你可以看到这个 article 你也可以看看这个 tutorial