如何在關閉應用程序或關閉屏幕時關閉服務(背景音樂),但切換到其他活動時無法關閉服務(背景音樂)?打開活動時背景音樂會停止
目前音樂播放良好,我持續到屏幕關閉或關閉應用程序,但也關閉,當我切換到另一個活動。這可能是由onStop
和分配給每個活動引起的。請幫我解決這個問題
我的服務:
public class MyService extends Service {
private final String TAG = null;
MediaPlayer player;
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.music;
player.setLooping(true); // Set looping
player.setVolume(100, 100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return 1;
}
public void onStart(Intent intent, int startId) {
// TO DO
}
public IBinder onUnBind(Intent arg0) {
// TO DO Auto-generated method
return null;
}
protected void onStop() {
player.pause();
}
public void onPause() {
player.pause();
}
@Override
public void onDestroy() {
player.stop();
player.release();
}
@Override
public void onLowMemory() {
}
}
我的例子活動有這樣:
public void onPause() {
super.onPause();
stopService(new Intent(a.this, MyService.class));
}
public void onStop() {
super.onStop();
stopService(new Intent(a.this, MyService.class));
}
public void onResume() {
super.onResume();
startService(new Intent(a.this, MyService.class));
}
public void onRestart() {
super.onRestart();
startService(new Intent(a.this, MyService.class));
}
您能解釋第一個選項嗎? –