当应用程序在后台且电池电量受限时,Android 13 前台服务将停止

问题描述 投票:0回答:1

在 Android 13 中,当应用程序处于后台并且电池受到限制时,前台服务会停止。大约一分钟后就会发生这种情况。

根据 Android 开发人员指南,当前正在运行的服务将停止,新服务将不会启动,下面是相同的链接。请告诉我如何在电池有限且应用程序处于后台的情况下保持服务运行?

https://developer.android.com/topic/performance/background-optimization

我修改了代码如下,但前台服务仍然停止并从托盘中删除了通知。

val notification: Notification = ...;
Service.startForeground(notification, FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE)

<manifest>
    ...
     <service
        android:name=".services.TestService"
        android:directBootAware="true"
        android:enabled="true"
        android:exported="false"
        android:foregroundServiceType="connectedDevice"
        android:stopWithTask="false" />
</manifest>

启动ForeGroundService

val startIntent = Intent(applicationContext, TestService::class.java)
startIntent.action = ACTION_START_FOREGROUND
ContextCompat.startForegroundService(applicationContext, startIntent)
android foreground-service android-13 background-foreground
1个回答
0
投票

通知可能会被删除,因为在 android 13 中需要新的权限:“POST_NOTIFICATIONS”

此外,当屏幕关闭时,手机会进入打瞌睡模式,睡眠/延迟功能将无法工作,因此请检查您的服务是否使用此功能,因为我认为您是否会最小化应用程序,它会在后台考虑,但前台服务会继续工作。

您还可以使用它来安排锁定屏幕/关闭屏幕中的工作 只需创建您的 AlarmReceiver...通过继承广播接收器

private fun setAlarmClock() {
val intent = Intent(requireContext(), AlarmReceiver::class.java)
alarmIntent = PendingIntent.getBroadcast(requireContext(), 0, intent, PendingIntent.FLAG_IMMUTABLE)

val intervalMillis = 5000L

val alarmClockInfo = AlarmManager.AlarmClockInfo(System.currentTimeMillis() + intervalMillis, alarmIntent)
alarmManager.setAlarmClock(alarmClockInfo, alarmIntent)
}
© www.soinside.com 2019 - 2024. All rights reserved.