Sanik
Sanik

Reputation: 35

Quit app when pressed home button in android

I have an application which has background music in it. When I am pressing the home button, the background music is still playing. After that when I am clicking the recent apps button, to the right of the home button, and closing the app by swiping or pressing X, it is restarting as if the application is started again instead of closing the currently playing music. How do I solve this problem?

Where do I add the onTaskRemoved() method?

package com.example.dmacs.myapplication;

/**
 * Created by dmacs on 4/8/16.
 */
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;

import java.util.Random;

/**
 * Created by digen on 3/8/16.
 */
public class BackgroundAudioService extends Service implements MediaPlayer.OnCompletionListener {
    MediaPlayer mediaPlayer;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        int mfile[] = new int[5];

        mfile[0]= R.raw.bgm1;
        mfile[1]= R.raw.bgm2;
        mfile[2]= R.raw.bgm3;
        mfile[3]= R.raw.bgm4;
        mfile[4]= R.raw.bgm5;

        Random random = new Random();
        int Low = 0;
        int High = mfile.length;
        int randomInt = random.nextInt(High-Low) + Low;



        mediaPlayer = MediaPlayer.create(this, mfile[randomInt]);// raw/s.mp3
        mediaPlayer.setOnCompletionListener(this);
    }

        @Override
        public int onStartCommand (Intent intent,int flags, int startId){
            if (!mediaPlayer.isPlaying()) {
                mediaPlayer.start();
            }
            return START_STICKY;
        }

    public void onDestroy() {
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
        }
        mediaPlayer.release();

    }

    public void onCompletion(MediaPlayer _mediaPlayer) {
        stopSelf();
    }



}

Upvotes: 1

Views: 1459

Answers (1)

earthw0rmjim
earthw0rmjim

Reputation: 19417

Clicking the Home button obviously won't stop a Service running in the background and swiping the app out of Recents won't work either, the OS will restart the Service because of START_STICKY returned from onStartCommand().

You just have to stop the Service when appropriate (in onPause(), for example) by calling stopService().

To stop your Service when your app is getting swiped out of Recents, you could just override onTaskRemoved() and call stopSelf() from there:

@Override
public void onTaskRemoved(Intent rootIntent) {
    stopSelf();
}

Upvotes: 1

Related Questions