1

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();
    }
}
Mayank Patel
  • 3,868
  • 10
  • 36
  • 59
Max Dev
  • 189
  • 1
  • 1
  • 12

2 Answers2

0

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));
    }
Naveen
  • 350
  • 2
  • 12
  • Thanks! But if someone start my application in android lower than Oreo, they whould have the same problem? – Max Dev Apr 15 '19 at 11:16
0

It looks like it is a bug START_STICKY does not work on Android KitKat .

QtDog
  • 21
  • 4