【发布时间】:2015-01-17 17:28:14
【问题描述】:
我正在开发一个应用程序,我正在使用一项服务来播放背景音乐。 音乐仅在应用程序正在使用时播放,即在前台。 当我使用主页按钮或返回按钮离开应用程序时,音乐将停止(应用程序可能会留在后台但不可见 -> 没有音乐)。 当我重新进入应用程序(使用主页按钮并切换回应用程序)时,音乐也会恢复。
我的服务:
public class MusicService extends Service {
MediaPlayer myPlayer;
private final IBinder localBinder = new LocalBinder();
public class LocalBinder extends Binder {
MusicService getService() {
return MusicService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return localBinder;
}
public boolean onUnbind(Intent intent) {
return true;
// called when the last Activity is unbound from this service
// stop your timed operations here
}
@Override
public void onCreate() {
Toast.makeText(this, "Music Service Created", Toast.LENGTH_LONG).show();
myPlayer = MediaPlayer.create(this, R.raw.ost);
myPlayer.setLooping(true); // Set looping
}
@Override
public void onDestroy() {
Toast.makeText(this, "Music Service Stopped", Toast.LENGTH_LONG).show();
myPlayer.stop();
}
@Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "Music Service Started", Toast.LENGTH_LONG).show();
if(!myPlayer.isPlaying())
myPlayer.start();
}
}
我还在为所有活动使用父类。在那个父类中,我想在方法 onPause() 和 onStop() 上停止服务:
ComponentName topActivity = taskInfo.get(0).topActivity;
if(!topActivity.getPackageName().equals(getApplicationContext().getPackageName())) {
stopService(new Intent(this, MusicService.class));
我在启动器活动中启动服务
startService(new Intent(this, MusicService.class));
Intent intent = new Intent(this, MusicService.class);
bindService(intent, this, 0);
现在我的问题:当我按下主页按钮时服务不会停止,当我离开应用程序时服务不会停止(返回按钮)。 当我杀死应用程序的任务时,服务会在几秒钟后再次启动,音乐将一直播放,直到我在设置中强制应用程序停止服务或卸载应用程序。
那么,当应用程序处于不可见背景或关闭时,如何完全关闭服务?我在这里经历了几个线程,youtube视频,教程并尝试了很多。我也尝试了非服务解决方案,但我无法解决问题。
谢谢!
【问题讨论】:
-
Service只在你想做一些后台任务时使用,因为你不需要后台任务,所以你不应该使用Service,而应该在Application级别使用MediaPlayer控件
-
然后我必须在启动新 Activity 时停止媒体播放器并在新 Activity 上再次启动播放器。
-
否,在应用层创建 MediaPlayer 对象时,您可以在任何屏幕中导航到任何屏幕,播放器将一直播放直到您停止/暂停它
-
你只播放一首歌吗?或更改某些活动的歌曲?
-
这只是一首 20 秒的歌曲,永远重复。