I have Android App which plays music from URL, but when my telephone goes to sleep-mode it plays 5 mins and then stops playing if I unlock my device its continue playing.
I've tried this Playing music in sleep/standby mode in Android 2.3.3 solution but it not helped.
Also, I've tried to use startForegroundService() but it can be used only on android 8 and higher. But my projects minimal version is android 5.
MainActivity.java
public static Srting src = "http://clips.vorwaerts-gmbh.de/VfE_html5.mp4";
public void Play(View view){
startService(new Intent(this, MyService.class));
play.setEnabled(false);
}
MyService.java
public class MyService extends Service {
MediaPlayer ambientMediaPlayer;
@Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onCreate(){
ambientMediaPlayer = new MediaPlayer();
ambientMediaPlayer.setLooping(true);
ambientMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId){
try {
ambientMediaPlayer.setDataSource(MainActivity.src);
ambientMediaPlayer.prepare();
ambientMediaPlayer.start();
}catch (IOException e){
e.printStackTrace();
}
return START_STICKY;
}
@Override
public void onDestroy() {
ambientMediaPlayer.stop();
}
}
You can't use startService
, if you are targeting android oreo and above. You have to use startForeground
or startForegroundService
. See this post https://developer.android.com/distribute/best-practices/develop/target-sdk#prenougat. so try below example.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(new Intent(this, MyService.class));
} else {
startService(new Intent(this, MyService.class));
}