为什么这款耳机检测代码会执行两次?

时间:2014-01-31 12:45:19

标签: java android android-intent

我发现几个类似的耳机状态检测示例都使用开关来确定ACTION_HEADSET_PLUG广播的状态。我在服务中使用此代码,以便在插入耳机时触发其他代码。

以下示例确实检测到正确的耳机状态但由于某种原因似乎运行了两次..当我插入耳机时,我连接了两个“Headset is plugged”日志消息,当我拔下插头时另外两个“Headset was unplugged”。我在switch语句中删除的任何代码也会被调用两次。我不明白为什么会这样。怎么能改变这个,所以我的代码只调用一次?

public class HeadsetObserverService extends Service {

private static final String TAG = "HeadsetObserverService";

@Override
public IBinder onBind(Intent arg0) {
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    // Create a filter. We are interested in the Intent.ACTION_HEADSET_PLUG action
    IntentFilter filter = new IntentFilter();
    filter.addAction(Intent.ACTION_HEADSET_PLUG);

    // Register a new HeadsetReceiver
    registerReceiver(new HeadsetReceiver(), filter);

    // We return START_STICKY. If our service gets destroyed, Android will try to restart it when resources are available.      
    return START_STICKY;
}

private class HeadsetReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
            int state = intent.getIntExtra("state", -1);
            switch (state) {
            case 0:
                 Log.d("unplugged", "Headset was unplugged");

                 // Cancel notification here

            break;
            case 1:
                 Log.d("plugged", "Headset is plugged");

                 // Show notification

            break;

            default:
                Log.w("uh", "I have no idea what the headset state is");
            }
        }
    }
}

}

1 个答案:

答案 0 :(得分:0)

希望您能从this stackoverflow answer.

获得一些线索

此问题是sendStickyBroadcast.

的原因