我正在尝试暂停拔下耳机时播放的音乐。
我创建了一个BroadcastReceiver,它侦听ACTION_HEADSET_PLUG意图并在状态 extra为0时(对于unplugged)对它们进行操作。我的问题是,每当活动开始时,我的BroadcastReceiver都会收到ACTION_HEADSET_PLUG意图。这不是我期望的行为。我希望只有在插入耳机或拔下耳机时才会触发Intent。
是否有理由在使用该IntentFilter注册接收器后立即捕获ACTION_HEADSET_PLUG Intent?有没有明确的方法可以解决这个问题?
我认为,由于默认音乐播放器在拔下耳机时实现了类似功能,因此可以实现。
我错过了什么?
这是注册码
registerReceiver(new HeadsetConnectionReceiver(),
new IntentFilter(Intent.ACTION_HEADSET_PLUG));
这是HeadsetConnectionReceiver
的定义public class HeadsetConnectionReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Log.w(TAG, "ACTION_HEADSET_PLUG Intent received");
}
}
答案 0 :(得分:17)
感谢Jake的回复。我应该更新原帖,以表明我发现了我遇到的问题。经过一些研究,我发现ACTION_HEADSET_PLUG Intent是使用Context中的sendStickyBroadcast方法广播的。
Sticky Intents由广播后的系统保存。只要注册了新的BroadcastReceiver以接收它,就会捕获该Intent。它在注册后立即触发,包含最后更新的值。对于耳机,这对于确定首次注册接收器时已插入耳机非常有用。
这是我用来接收ACTION_HEADSET_PLUG意图的代码:
private boolean headsetConnected = false;
public void onReceive(Context context, Intent intent) {
if (intent.hasExtra("state")){
if (headsetConnected && intent.getIntExtra("state", 0) == 0){
headsetConnected = false;
if (isPlaying()){
stopStreaming();
}
} else if (!headsetConnected && intent.getIntExtra("state", 0) == 1){
headsetConnected = true;
}
}
}
答案 1 :(得分:0)
拔下耳机时,我使用不同的方法停止播放。我不希望你使用它,因为你已经很好,但其他一些人可能会发现它很有用。如果您控制了音频焦点,那么Android会向您发送一个变得嘈杂的事件音频,因此如果您为此事件编写接收器,它将看起来像
public void onReceive(Context context, Intent intent) {
if (AudioManager.ACTION_AUDIO_BECOMING_NOISY.equals(intent.getAction())) {
if (isPlaying()){
stopStreaming();
}
}
}
答案 2 :(得分:-2)
我遇到了同样的问题。我不确定是什么导致它,但至少在我的测试中它似乎是一致的,这意味着你可以解决它。我通过添加一个以true开头的布尔成员变量来做到这一点,并在第一次onReceive(Context, Intent)
调用时设置为false。然后该标志控制我是否实际处理了unplug事件。
供您参考,以下是我用来做的代码,可在上下文here中找到。
private boolean isFirst;
public void onReceive(Context context, Intent intent)
{
if(!isFirst)
{
// Do stuff...
}
else
{
Log.d("Hearing Saver", "First run receieved.");
isFirst = false;
}
}