Intent.ACTION_HEADSET_PLUG的状态额外总是返回1

时间:2014-07-06 14:36:26

标签: android android-intent android-broadcast

我使用BroadcastReceiver来了解耳机是否插在设备上,但是"状态"意图额外立即返回1(插入)在每种情况下。

这是我的代码:

public class Class {

  boolean isHeadsetOn;
  IntentFilter headsetReceiverFilter;
  HeadsetPluggedReceiver headsetReceiver;

  public Class(Context context) {
    this.headsetReceiverFilter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
    this.headsetReceiver = new HeadsetPluggedReceiver();
    context.registerReceiver(this.headsetReceiver, this.headsetReceiverFilter);
  }

  private class HeadsetPluggedReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
      switch(intent.getIntExtra("state", -1)) {
        case 0:
          Synthesizer.this.isHeadsetOn = false;
          Log.d("onreceive", "off");
        case 1:
          Synthesizer.this.isHeadsetOn = true;
          Log.d("onreceive", "on");
        default:
          // shit
      }
    }

  }

}

这是我的日志:

// not plugged. plugging in
onreceive | on
// unplugging
onreceive | off
onreceive | on
// plugging in again
onreceive | on
// plugging off again
onreceive | off
onreceive | on

我该如何解决这个问题?

提前谢谢。

2 个答案:

答案 0 :(得分:1)

**应该是:**

@Override
public void onReceive(Context context, Intent intent) {
  switch(intent.getIntExtra("state", -1)) {
    case 0:
      Synthesizer.this.isHeadsetOn = false;
      Log.d("onreceive", "off");
      break; //<---------
    case 1:
      Synthesizer.this.isHeadsetOn = true;
      Log.d("onreceive", "on");
      break; //<---------
    default:
      // shit
  }
}

}

答案 1 :(得分:0)

您的交换机案例中需要使用break语句。现在你的逻辑正在落到案例1。