目前我有一个服务
,我用它在应用程序打开时在后台播放声音文件:
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
中启动,如下所示:
BackgroundSoundService backgroundSoundService = new Intent(this, BackgroundSoundService.class);
我希望 Service
在应用程序打开时继续运行,但在应用程序最小化或销毁时停止。我认为最初的解决方案是覆盖 onPause
和 onDestroy
,并实现这一行:
stopService(backgroundSoundService);
然而,当我随后切换到另一个 Activity
时,onPause
被触发并且 Service
停止。如何确保 Service
在应用程序在前台打开时继续运行,但在应用程序最小化或关闭时停止?
最佳答案
您可以尝试使用 onBackPressed
来发现您的 Android 应用何时将被最小化。
您可能有一个 Activity,它是主要的 MainActivity
,在按下 时会导致 App 最小化。然后停止服务
。
顺便说一句,您应该使用Singleton 来为您的backgroundSoundService
使所有可以最小化应用程序的 Activity 扩展此 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
这很棘手,因为没有按键事件来区分“Home pressed”。
你可以做的是使用isFinishing onPause
中的方法。
当 Activity 进入后台
时,按下Home Page键将NO完成
所以只需要一个 bool 值来检查您是否调用了(使用 Intent
)其他 Activity。
将您的 onPause
方法更新为:
@Override
public void onPause() {
if(!isFinishing()){
if(!calledOtherActivity){
stopService(serviceRef);
}
}
}
关于android - 如何在应用程序暂停或销毁时停止服务,但在切换到新 Activity 时不停止服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36252733/