待机模式 - 前台服务是否继续运行?

11

我很困惑阅读此文并试图弄清楚前台服务是否会在设备进入深度打盹模式时运行。有人能澄清一下吗?我想知道在棉花糖及以上版本上,前台服务是否可以继续运行。我一直认为所有线程(包括前台服务)在设备休眠时都被挂起了。

我看到了打盹模式限制,但没有关于前台服务的内容。我很困惑,如果我的服务超过了打盹模式的安全设置,那么我的服务是否仍将继续运行。

从我所了解的打盹模式限制来看,只有网络调用被停止了。但是,假设我正在进行一些长时间运行的主线程工作,这意味着它可以继续在打盹模式下运行,对吗?

2个回答

15

前台服务在Doze模式下不会被杀死,这是一个很好的解决方法来覆盖Doze模式。 杀死前台服务高度依赖于移动操作系统。 例如华为,在一段时间后会杀死前台服务,您将无法确定该期间。 其他一些手机检测到意外的电池消耗后,会杀死最旧的前台服务。 去年,我观察手机在启用或未启用Doze模式时如何关闭前台服务,花费了大约6个月的时间。 我尝试了多种解决方案来覆盖Doze模式,以每10秒钟检测一次位置,最好的解决方案是前台服务。 因此,在某些手机上可能会出现意外行为,但它是Doze和待机模式的最佳解决方案。 您可以查看这篇文章 您也可以查看这个教程


1
我需要在Wear OS上定期执行网络调用,为此我开发了一个简单的可运行程序,它以固定速率将自身发布到线程中,并将其作为私有成员放置在前台服务中,在调用startService时开始运行。30分钟后,正确的行为停止,调用不再执行,但前台服务仍然保持活动状态。从那时起,每次我打开屏幕时,正确的行为就会恢复,并在关闭屏幕时再次停止。有什么想法吗? - Andrea Nisticò
2
在 Pixel 4 XL 上,前台服务在Doze模式下会被终止。 - IgorGanapolsky
2
@IgorGanapolsky 即使应用程序的电池优化关闭了? - lasec0203
1
@lasec0203 是的。我找到的唯一解决方法是获取部分唤醒锁。 - IgorGanapolsky
大家好,你们知道如何判断Android是否终止了前台服务吗?我需要在这种情况下通知后端服务器。 - ledragon
显示剩余5条评论

6

Doze模式是为了节省电池而设计的。您应该将您的应用程序加入白名单以停用Doze模式。

来源: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. 忽略电池优化

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

1
把下面关于编程的内容从英语翻译成中文。请仅返回已经翻译好的文本:这不是问题要求的。 - Shivam Sharma
1
这会防止服务被杀死吗? - IgorGanapolsky
翻译:不是很清楚,我误解了这个问题。抱歉。我猜它问我如何防止休眠模式,而不是如何防止服务进入休眠模式。 - Hatay Berkay Işıkoğlu
我不确定这个,我的应用似乎仍然会在Doze模式下受到工作延迟(意味着workermanager.equeue()直到我解锁设备才会触发),即使在电池优化白名单上。值得一提的是,我在Pixel XL(安卓10)上进行测试。 - lasec0203
WorkManager并不是一个前台服务,而WorkManager.Task会尊重Doze模式。 - Galeen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接