How To Stop Service When App Is Paused Or Destroyed But Not When It Switches To A New Activity?
Solution 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
publicabstractclassBaseActivityextendsActivity {
@OverridepublicvoidonBackPressed() {
//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);
}
}
}
Post a Comment for "How To Stop Service When App Is Paused Or Destroyed But Not When It Switches To A New Activity?"