When I exit an application the sound runs on the background

落花浮王杯 提交于 2019-11-27 06:27:32

问题


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?


回答1:


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.




回答2:


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
}


来源:https://stackoverflow.com/questions/12652133/when-i-exit-an-application-the-sound-runs-on-the-background

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