How to stop Service when app is paused or destroyed but not when it switches to a new Activity?

情到浓时终转凉″ 提交于 2019-12-10 15:38:40

问题


Currently I have a Service which I am using to play a sound file in the background whilst the app is open:

public class BackgroundSoundService extends Service {

    MediaPlayer player;

    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        player = MediaPlayer.create(this, R.raw.sound);
        player.setLooping(true);
        player.setVolume(100, 100);
    }

    public int onStartCommand(Intent intent, int flags, int startId) {
        player.start();
        return 1;
    }

    @Override
    public void onDestroy() {
        player.stop();
        player.release();
    }
}

And the Service is started in my MainActivity like so:

BackgroundSoundService backgroundSoundService = new Intent(this, BackgroundSoundService.class);

I want the Service to continue to run whilst the app is open, although to stop when the app is minimised or destroyed. I thought the initial solution to this would be to override onPause and onDestroy, and implement this line:

stopService(backgroundSoundService);

However when I then switch to another Activity, onPause is then triggered and the Service stops. How can I ensure that the Service continues to run as long as the application is open in the foreground but stops when the app is minimised or closed?


回答1:


You can try using onBackPressed in order to discover when your android app is going to be minimized.

You probably have an Activity Which is the main MainActivity that on back pressed will cause the App to minimize. Just stop the Service then.

Btw you should use a Singleton in order to keep a Reference for your backgroundSoundService

Make all your Activities that can minimize the app Extends this BaseActivity

public abstract class BaseActivity extends Activity {

    @Override
    public void onBackPressed() {
        //check if should be minimized...
        //if so stop the Service
    }

}

Need a solution for Home button

This is tricky because there is no Key event in order to distinguish `Home pressed.

What you can do is to use isFinishing method in onPause.

When activity will go to the Background it will NOT finish when pressing the Home Page key

So just have a boolean to check if you called (Using Intent) other Activity.

the update your onPause method to:

@Override
public void onPause() {
    if(!isFinishing()){
        if(!calledOtherActivity){
            stopService(serviceRef);
        }
    }
}


来源:https://stackoverflow.com/questions/36252733/how-to-stop-service-when-app-is-paused-or-destroyed-but-not-when-it-switches-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!