0

I'm trying to play an mp3 when app is closed. It works when I'm out of the app but when i swipe it off from task manager the song ends. How can I make the service continue playing after close? This is my service:

@Override
public IBinder onBind(Intent intent) {
    return null;
}
@Override
public void onCreate() {
    super.onCreate();
}
@Override
public void onTaskRemoved(Intent rootIntent) {
    Log.d("MusicService", "onTaskRemoved");
}
@Override
public void onDestroy() {
    super.onDestroy();
}
@Override

public int onStartCommand(Intent intent, int flags, int startId) {
    return super.onStartCommand(intent, flags, startId);
}

This is my main activity:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    start = (Button)findViewById(R.id.start);
    stop = (Button)findViewById(R.id.stop);
    mp = MediaPlayer.create(getApplicationContext(),R.raw.gucci);
    start.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startService(new Intent(MainActivity.this,MyService.class));
            mp.start();

        }
    });
    stop.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mp.pause();
            stopService(new Intent(MainActivity.this,MyService.class));
        }
    });
}
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115

2 Answers2

0

NOTE: Other way may be not usable (ignore if not usable).

Don't give user the option to clear it from recents menu.

Use this manifest attribute for each activity component in your Player app

android:excludeFromRecents

Napolean
  • 5,303
  • 2
  • 29
  • 35
-1

just return START_STICKY in onstartcommand method of your service class . it will run forever in background .

Mohit Hooda
  • 273
  • 3
  • 9
  • @Override public int onStartCommand(Intent intent, int flags, int startId) { return START_STICKY; } Thats how i usually do .. it works for me every time – Mohit Hooda Dec 26 '17 at 06:43