简体   繁体   中英

How do I know when application is in the background?

I have an application that is a menu with several options, every option when chosen will lead to a new activity. I also have music playing in the background using a service. I want my music play continuously no matter what activity is focused.

My problem is:

  • If I am NOT override onPause() or onStop(), the music will go fine when I open another activity. BUT when I press home button, music still plays.
  • If I DO override onPause() or onStop(), the music will stop when I press Home button, but it also stops when another activity is opened.

So what should I do now?

You can override onPause() and use a boolean flag.
Set the boolean to true if you are launching a new activity. When onPause() is called you'll know if it is not true then you should stop the music.

boolean keepPlaying = false;

protected void onPause() { 
    if(!keepPlaying)
        stopService(new Intent(this, MediaPlayerServices.class)); 
    super.onPause();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM