我希望我的音乐播放器在断开耳机时暂停音乐,并在重新连接耳机时恢复音乐。我有这个设置与广播接收器一起工作,但问题是我可以在断开耳机后瞬间听到扬声器播放的音乐。这就像我的接收器没有足够快地接收广播?发生了什么事?
这里我在我的主要活动类
中的onCreate
方法中注册我的接收器
MusicIntentReceiver receiver = new MusicIntentReceiver();
registerReceiver(receiver, new IntentFilter(Intent.ACTION_HEADSET_PLUG));
这是我的意图接收器类
public class MusicIntentReceiver extends android.content.BroadcastReceiver {
@Override
public void onReceive(Context ctx, Intent intent) {
if (intent.getAction().equals(android.media.AudioManager.ACTION_HEADSET_PLUG)) {
if(intent.getIntExtra("state",0)==0){ // 0 for unplugged (if it becomes unplugged)
//Pause music
}
if(intent.getIntExtra("state",0)==1){ // 1 for plugged (if it becomes plugged)
//Resume music
}
}
}
}
答案 0 :(得分:0)
尝试暂停AudioManager.ACTION_AUDIO_BECOMING_NOISY
上的音乐 - 它出现在AudioManager.ACTION_HEADSET_PLUG
之前(大约1秒左右)。类似的东西:
IntentFilter filter = new IntentFilter();
filter.addAction(AudioManager.ACTION_HEADSET_PLUG);
filter.addAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
registerReceiver(receiverHeadset, filter);
...
public class MusicIntentReceiver extends android.content.BroadcastReceiver {
@Override
public void onReceive(Context ctx, Intent intent) {
if (intent.getAction().equals(AudioManager.ACTION_AUDIO_BECOMING_NOISY)) {
// Pause music
} else if (intent.getAction().equals(android.media.AudioManager.ACTION_HEADSET_PLUG)) {
if(intent.getIntExtra("state",0)==1){ // 1 for plugged (if it becomes plugged)
//Resume music
}
}
}
}