I am playing an audio stream from mediaPlayer using a service but it stops playing the song after approx one minute of being in the background or the screen turned off. While on the other hand it works fine and completes the song when the appication is kept open.
public class MyService extends Service implements MediaPlayer.OnPreparedListener {
MediaPlayer mediaPlayer = null;
String audio_stream;
Context context;
public int onStartCommand(Intent intent, int flags, int startId) {
audio_stream = intent.getStringExtra("url");
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(audio_stream);
} catch (IOException e) {
//e.printStackTrace();
}
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
return false;
}
});
return START_STICKY;
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onPrepared(MediaPlayer mp) {
Log.d("Channel", audio_stream+"he");
mp.start();
}
@Override
public void onDestroy() {
super.onDestroy();
if (mediaPlayer != null) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer = null;
}else{
Log.d("channel", "this is the case");
}
}
@Override
public void onLowMemory() {
super.onLowMemory();
mediaPlayer.release();
}
}
Before MediaPlayer stops, it gives 4 lines in the log which are
V/MediaPlayer: resetDrmState: mDrmInfo=null mDrmProvisioningThread=null mPrepareDrmInProgress=false mActiveDrmScheme=false
V/MediaPlayer: cleanDrmObj: mDrmObj=null mDrmSessionId=null
V/MediaPlayer: resetDrmState: mDrmInfo=null mDrmProvisioningThread=null mPrepareDrmInProgress=false mActiveDrmScheme=false
V/MediaPlayer: cleanDrmObj: mDrmObj=null mDrmSessionId=null
I am unable to understand where the problem is exactly and how can I proceed to overcome it.
Thank you
2
Answers
On Android 8.0 and higher devices, you need to have this be a foreground service, with an associated
Notification
. Otherwise, your service will be stopped after a minute.Is correct! on Android 8.0 and higher devices must have a foreground service with a notification. I had the same problem and it was solved this way.