当OnAudioFocusChangeListener = AudioManager.AUDIOFOCUS_LOSS时停止服务

时间:2012-03-12 20:48:13

标签: android

我无法停止我的媒体播放器课程,这扩展了服务范围。我可以调用stop就好了,但是在尝试使用stopService(Intent)时会收到一个强制关闭。我在与上下文相关的日志中获得了nullpointer异常。我在网上找不到任何关于此的文档。以下是我尝试过的代码部分:

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);


        }
    }
};

1 个答案:

答案 0 :(得分:0)

好的,所以我无法得到正确的上下文。所以我所做的是创建了一个BroadcastReceiver,并在AudioFocusListener中使用了sendBroadcast()。然后在我的BroadcastReceiver onReceive()方法中,我使用stopService意图停止了我的Play.class。现在很棒。也许这将有助于将来的人。