2

我有一個音樂服務,在應用程序的背景中播放音樂。我希望音樂能夠繼續播放應用程序的所有活動,但在應用程序在後臺運行時停止播放(即,當用戶轉到其他應用程序或按下主頁按鈕而不從正在運行的應用程序中刪除應用程序)當用戶按主頁按鈕時停止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" /> 

編輯:如果有人知道如何在沒有服務的情況下播放背景音樂,只要音樂在整個播放過程中播放,應用程序打開並在按下主屏幕按鈕時關閉。

回答

0

Basicaly你必須定義巫活動是你的退出點,然後,如果你想開始播放使用

Intent intent = new Intent(context,YourService.class); 
intent.setAction(YourService.ACTION_PLAY); 

編輯onStartCommand這樣

private boolean playing; // use this var to determine if the service is playing 
public int onStartCommand(Intent intent, int flags, int startId) { 

    String action = intent.getAction(); 
    if(action == ACTION_PLAY) { 
    // No each time your start an activity start the service with ACTION_PLAY but in ACTION_PLAY process check if the player if not already runing 
     if(!playing) { 
     player= MediaPlayer.create(this,R.raw.music1); 
     player.start(); 
     player.setLooping(true); 
     // here you set playing to true 
     playing = true; 
    } 
} else if(action.equals(ACTION_STOP) { 
     // Set playing to false 
     playing = false; 
     // This is just an exemple : Now here increase a delay little bit so that the player will not stop automaticaly after leaving activity 
     new Handler().postDelayed(new Runnable(){ 
       @override 
       public void run() { 
       // No before stoping the play service 
       // check playing if playing dont go further 
       if(playing) return; 
       if(player!=null && player.isPlaying()) { 
        player.stop(); 
        player.release(); 
        player.reset(); // To avoid mediaPlayer has went away with unhandled error warning 
        player = null; 
        // And stop the service 
        stopSelf(); 
       }  
       } 
     },2500); 
} 
return START_STICKY;} 

現在和停止

Intent intent = new Intent(context,YourService.class); 
intent.setAction(YourService.ACTION_STOP); 

並且不要忘記定義兩個動作要素字段

如果您不想定義您的退出點,您可以定義一個布爾值,以確定您的服務正在使用中,因此不會被延遲的處理程序停止 現在,每次有一個活動啓動時,通過操作ACTION_PLAY啓動服務 一旦它停止開始ACTION_STOP的服務,將確保每一項活動必須開始和停止播放 也不要忘記調整延遲的能力
希望它能幫助

+0

但如果用戶退出任何隨機活動會怎麼樣?我該如何處理停止音樂? –

0

我想這個問題最好的解決辦法是停止ActivityonPause()中的音樂並開始每個的onResume()中的音樂。您遇到的問題是,當您的應用程序從一個Activity切換到另一個時,音樂會結結巴巴。爲了解決這個問題,你應該在onPause()中發佈一個Runnable(即停止音樂)到Handler,但是發佈它以便它不會立即運行。它應該延遲大約200毫秒。在onResume()中,取消Runnable,使其不運行。這將防止口吃,但在用戶按下HOME按鈕後200毫秒停止播放音樂。


另一種選擇是不使用Service,但只要保持MediaPlayer比如在你的Application類。您仍然想要停止並開始播放onPause()onResume()中的音樂,但只需撥打Application課程中的某些方法,您就可以更直接地進行操作。您需要創建一個自定義Application類,extends Application並將其添加到您的清單。

相關問題