如何在应用程序暂停或销毁时停止服务,而在切换到新的活动时如何停止服务? [英] How to stop Service when app is paused or destroyed but not when it switches to a new Activity?
问题描述
当前,我有一个Service
,我正在使用它在打开应用程序的同时在后台播放声音文件:
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();
}
}
Service
像这样在我的MainActivity
中启动:
And the Service
is started in my MainActivity
like so:
BackgroundSoundService backgroundSoundService = new Intent(this, BackgroundSoundService.class);
我希望Service
在应用程序打开时继续运行,尽管在最小化或销毁应用程序时停止运行.我认为最初的解决方案是覆盖onPause
和onDestroy
并实现以下代码:
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);
但是,当我随后切换到另一个Activity
时,会触发onPause
,并且Service
停止.如何确保Service
只要在前台打开该应用程序就可以继续运行,而在最小化或关闭该应用程序时停止运行?
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?
推荐答案
您可以尝试使用onBackPressed
来发现何时将Android应用程序最小化.
You can try using onBackPressed
in order to discover when your android app is going to be minimized.
您可能有一个活动,它是主要的MainActivity
,后按会导致该应用最小化.只需停止Service
然后.
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.
在此之前,您应该使用 Singleton ,以便为backgroundSoundService
Btw you should use a Singleton in order to keep a Reference for your backgroundSoundService
进行所有可以使应用程序最小化的活动扩展此BaseActivity
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.
您可以使用onPause中的> isFinishing 方法.
What you can do is to use isFinishing method in onPause
.
当活动进入Background
时,按主页键
因此,只需一个布尔值即可检查您是否调用过(使用Intent
)其他活动.
So just have a boolean to check if you called (Using Intent
) other Activity.
将您的onPause
方法更新为:
@Override
public void onPause() {
if(!isFinishing()){
if(!calledOtherActivity){
stopService(serviceRef);
}
}
}
这篇关于如何在应用程序暂停或销毁时停止服务,而在切换到新的活动时如何停止服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!