I am using my own music player app that uses a foreground service with a android.media.MediaPlayer
with wake mode PARTIAL_WAKE_LOCK
to play music. The permissions FOREGROUND_SERVICE
and WAKE_LOCK
are declared in the manifest.
All this has worked fine for years on my Huawei device running Android 9 (API 28) but on my new Samsung Galaxy A51 running Android 10 (API 29) the music stops playing after a while. The first few songs are fine but after while the next song doesn't start playing after the end of the previous song is reached (the next song is started in MediaPlayer.OnCompletionListener.onCompletion()
). It's not that the app gets killed, as soon as I turn on the screen the next song starts playing.
I've tried whitelisting my app in the Android preferences "Apps/Special access/Optimize battery usage" and using ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS
. I've read about using something like MediaSession
to register my app as a music player and a few other StackOverflow posts describing similar issues and I've tried a few solutions but nothing is working. Maybe someone can send me in the right direction.
EDIT: This is how the MediaPlayer
is started from the service (minified version):
@Override
public void onCreate() {
player = new MediaPlayer();
player.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
player.setAudioAttributes(new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.setUsage(AudioAttributes.USAGE_MEDIA)
.build()
);
player.setOnPreparedListener(this);
player.setOnCompletionListener(this);
player.setOnErrorListener(this);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
play();
}
public void play() {
player.reset();
player.setDataSource(getApplicationContext(), getSong().getContentUri());
player.prepareAsync();
}
@Override
public void onPrepared(MediaPlayer player) {
setVolume();
player.start();
}
@Override
public void onCompletion(MediaPlayer player) {
// Go to next song.
play();
}