I "created" an application and when I go back or I press the home button to exit from the application, the audio from my application is still running! I have to close all running apps to make it stop.
How can I stop the audio running when I press the home button?
Override the onPause() method of all your activities, and turn off/pause/stop the music when it's called. You might want use a boolean flag to check if you're moving within your app, a scenario in which you'd want the music to continue:
boolean movingInApp = false;
....
movingInApp = true;
Intent intent...
.....
public void onPause() {
if(!movingInApp) {
//stop service
}
}
public void onResume() {
movingInApp = false;
//Rest of your code
}
By setting the value of movingInApp
to true
before launching any intent etc, you can prevent your app from stopping the music. Remember to set it to false
again later in your onResume()
method. If the system makes your app go to the background, this will be false, and your music will be stopped.
When you click back, the app keeps on running in the background.
If you want to stop the music any time you get out of a certain activity override onStop or onPause to stop your sound. Something like that
@Override
protected void onStop(){
super.onStop();
//your code for stopping the sound
}