Android 13 Foreground service is stopping when app is in background with battery Restricted

1.5k Views Asked by At

In Android 13, Foreground Service is stopped when the application is background and battery is restricted. This happens after a minute or so.

As per the Android developer guide the current running services will be stopped and new services will be not launched and below is the link for the same. Please let me know how to keep service running even if the battery is restricted and application is background?

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

I have modified code as below, but still the foreground service is stopped and removed the notification from the tray.

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>

Starting ForeGroundService

val startIntent = Intent(applicationContext, TestService::class.java)
startIntent.action = ACTION_START_FOREGROUND
ContextCompat.startForegroundService(applicationContext, startIntent)
1

There are 1 best solutions below

0
Eli On

The notification may be removed because in android 13 there is new permission that required:"POST_NOTIFICATIONS"

Also when the screen is turned off the phone enter to DOZE mode and sleep/delay functions will not work, so check if your service uses this functions, becuase I think if you will minimized the app its consider in the background but the Foreground Service will continute to work.

Also you can use this to schedule work in the lock screen/turned off screen just create your AlarmReceiver... via inheritance from broadcast receiver

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