0
在我的應用程序中有一個背景音樂,用服務完成。在我的應用程序中有很多活動,所以我希望音樂可以在其中播放,但也可以在屏幕關閉或用戶關閉應用程序時關閉。在一個活動的java我寫道:音樂作爲背景音樂,服務,在所有活動期間關閉onStop和onPause
public void onPause() {
super.onPause();
stopService(new Intent(Activity.this, Service.class));
}
public void onStop() {
super.onStop();
stopService(new Intent(Activity.this, Service.class));
}
public void onResume() {
super.onResume();
startService(new Intent(Activity.this, Service.class));
}
public void onRestart() {
super.onRestart();
startService(new Intent(Activity.this, Service.class));
}
問題是,當我切換到另一個活動,服務/音樂停止。 如何在所有活動中播放音樂,還要在所有活動中關閉onStop和onPause?謝謝。
我的服務:
public class Service 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() {
}
}