2012-03-12 40 views
0

我無法停止擴展服務的媒體播放器類。我可以稱之爲停止,但在嘗試使用stopService(Intent)時會強行關閉。我在與上下文相關的日誌中獲得空指針異常。我在網上找不到關於此的任何文檔。以下是我試過的部分代碼:當OnAudioFocusChangeListener = AudioManager.AUDIOFOCUS_LOSS時停止服務

static OnAudioFocusChangeListener audioFocusChangeListener = new OnAudioFocusChangeListener() 
{ 
    public void onAudioFocusChange(int focusChange) 
    { 
     if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) 
     { 
      mp.setVolume(0.01f, 0.01f); 
     } 
     else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) 
     { 
      mp.setVolume(1.0f, 1.0f); 
     } 
     else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) 
     { 

       //stop playback and release everything---------------still need to confirm this is working 
       Play playService = new Play(); 
       playService.stopPlaying(); 
       //playService.stopAllServices(); 
       //Intent stopPlayingService = new Intent("com.joebutt.mouseworldradio.Play"); 
       //playService.getApplicationContext(); 
       //Context context = (Context) OnAudioFocusChangeListener.this; 
       Intent stopPlayingService = new Intent(playService.getBaseContext(), Play.class); 
       //stopPlayingService.setAction(Intent.); 
       //stopService(stopPlayingService); 
       playService.stopService(stopPlayingService); 


     } 
    } 
}; 

回答

0

好吧,我無法獲得正確的上下文。所以我所做的就是創建一個BroadcastReceiver並從AudioFocusListener中使用sendBroadcast()。然後在我的BroadcastReceiver的onReceive()方法中,我使用stopService停止了我的Play.class。現在效果很好。也許這將在未來幫助別人。