Android 当OnAudioFocusChangeListener=AudioManager.AUDIOFOCUS\u丢失时停止服务
我很难停止我的媒体播放器类,这扩展了服务。我可以很好地呼叫stop,但在尝试使用stopService(Intent)时,遇到了一个强制关闭。我在与上下文相关的日志中获得nullpointer异常。我在网上找不到有关这方面的任何文件。以下是我尝试过的代码部分:Android 当OnAudioFocusChangeListener=AudioManager.AUDIOFOCUS\u丢失时停止服务,android,Android,我很难停止我的媒体播放器类,这扩展了服务。我可以很好地呼叫stop,但在尝试使用stopService(Intent)时,遇到了一个强制关闭。我在与上下文相关的日志中获得nullpointer异常。我在网上找不到有关这方面的任何文件。以下是我尝试过的代码部分: static OnAudioFocusChangeListener audioFocusChangeListener = new OnAudioFocusChangeListener() { public void onAudio
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);
}
}
};
好的,所以我无法获得正确的上下文。所以我创建了一个BroadcastReceiver,并从AudioFocusListener内部使用sendBroadcast()。然后,在BroadcastReceiver onReceive()方法中,我停止了Play.class,并打算使用stopService。现在效果很好。也许这会对将来的人有所帮助