我有一個音樂服務,在應用程序的背景中播放音樂。我希望音樂能夠繼續播放應用程序的所有活動,但在應用程序在後臺運行時停止播放(即,當用戶轉到其他應用程序或按下主頁按鈕而不從正在運行的應用程序中刪除應用程序)當用戶按主頁按鈕時停止Android服務
這是我的MusicService代碼:
public class MusicService extends Service {
public static MediaPlayer player;
public IBinder onBind(Intent arg0) {
return null;
}
public int onStartCommand(Intent intent, int flags, int startId) {
player= MediaPlayer.create(this,R.raw.music1);
player.start();
player.setLooping(true);
return super.onStartCommand(intent,flags,startId);
}
}
,這是我的表現與音樂有關的服務的一部分:
<service android:name=".MusicService" android:stopWithTask="true" />
編輯:如果有人知道如何在沒有服務的情況下播放背景音樂,只要音樂在整個播放過程中播放,應用程序打開並在按下主屏幕按鈕時關閉。
但如果用戶退出任何隨機活動會怎麼樣?我該如何處理停止音樂? –