拔下耳机时静音

时间:2014-08-03 12:21:18

标签: android

我拔掉耳机时试图将音频静音。我有一个BroadcastReceiver,我这样做:

 public void onReceive(Context context, Intent intent) {

    if (intent.hasExtra("state")){
         if (headsetConnected && intent.getIntExtra("state", 0) == 0){
             myActivity.music.setVolume((float) 0);
             headsetConnected = false;

         } else if (!headsetConnected && intent.getIntExtra("state", 0) == 1){
            headsetConnected = true;
             myActivity.music.setVolume((float) 1);
         }
     }
}

但是当我拔下耳机时,音乐仍会响起一秒钟。 我该如何解决?谢谢。

1 个答案:

答案 0 :(得分:1)

试试吧..它肯定有用..

private class NoisyAudioStreamReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (AudioManager.ACTION_AUDIO_BECOMING_NOISY.equals(intent.getAction())) {
            pause();
        }
    }
}

private IntentFilter intentFilter = new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY);

private void startPlayback() {
    registerReceiver(myNoisyAudioStreamReceiver(), intentFilter);
}

private void stopPlayback() {
    unregisterReceiver(myNoisyAudioStreamReceiver);
}

我在此链接找到了答案:http://developer.android.com/training/managing-audio/audio-output.html

不要忘记在清单中添加此权限:

<uses-permission android:name="android.permission.ACTION_HEADSET_PLUG"></uses-permission>