Reputation: 105
I have a service that uses AudioManager to continually listen for music playing in a separate music app with isMusicActive. That means the service needs to always be running in the background. Basically the purpose of the app is to track the amount of time spent listening to music.
I've been using it on Marshmallow and now I want to achieve the same thing on Oreo, but there doesn't seem to be a way to do it because of the restrictions on background services. I can't use a foreground service because the music app will be in the foreground. Is the only solution for this to create my own music app?
Upvotes: 1
Views: 392
Reputation: 14183
Without help from the system your best chance is to use use a foreground Service.
I can't use a foreground service because the music app will be in the foreground
You can, you will just need to show a notification as long as the Service is in foreground.
The ratio behind the restrictions on background tasks is that the user should be somehow aware that they're running, having a task running 24/7 can have a huge impact on the battery.
There might be other options for what you want to achieve though. You could have a periodic timer (say, every 5 minutes), and then check if the music is playing only at the intervals. You could have a rough estimation based only on the observations at intervals. E.g. if you detected music playing 3 times in a row and the interval is 5 minutes you count ~15 minutes of listening.
Upvotes: 1