Vrashab Kotian
Vrashab Kotian

Reputation: 27

Why are Music Services in Android never affected by doze mode?

Can anyone please explain to me at technical level, why does a music player's service run continuously after the screen is turned off. Why is it never affected by doze mode? I want to create a service along similar lines, but it should perform a particular task every 20 seconds continuously.

I would be glad if anyone can explain this. Thanks in advance.

Upvotes: 1

Views: 783

Answers (1)

Elletlar
Elletlar

Reputation: 3224

The music player's service runs as a 'foreground service'.

Foreground services for the most part are unaffected by doze when used in combination with a partial wakelock:

Purpose of WakeLock in modern Android?

If your app needs to create a foreground service while the app is in the background:

ContextCompat.startForegroundService()

Inside the service, promote it to the foreground and post the notification by calling:

startForeground()

From the Android docs: "A foreground service performs some operation that is noticeable to the user. For example, an audio app would use a foreground service to play an audio track. Foreground services must display a Notification. Foreground services continue running even when the user isn't interacting with the app."

https://developer.android.com/guide/components/services

Typically, a music app will change the foreground service notification from a 'liability' that annoys the user to an asset by displaying an image of the artist, the current track and offer media buttons like play/pause/rewind/forward.

A foreground service should not generally be used to do regularly scheduled work because it will greatly reduce the device's battery life.

Instead, try to use WorkManager, JobScheduler or Firebase Cloud Messaging to wake the device up only when necessary.

Execute frequent tasks using the Work Manager API

But it will not be possible to "poll" or run your code every 20 seconds with these solutions. You really need to find a solution that works with "Doze" instead of fighting against it.

Upvotes: 2

Related Questions