2012-03-12 42 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。现在效果很好。也许这将在未来帮助别人。