接收耳机拔出时间太长

Receive unplugging of headphones takes too long

我想在用户拔下耳机时暂停 MediaPlayer。我发现我可以使用 "ACTION_AUDIO_BECOMING_NOISY" 广播,所以我试了一下!

理论上是可以的,但是接收时间太长了。音乐仍会播放 3-5 秒,然后用户才真正 pauses.This 无法接受。

其他开发人员如何能够在毫秒内暂停它?有更好的解决方案吗?

我的 BroadcastReceiver 实际上是用于通知的:

public class NotificationBroadcast extends BroadcastReceiver {

...

@Override
public void onReceive(Context context, Intent intent) {

    if (intent.getAction().equals(android.media.AudioManager.ACTION_AUDIO_BECOMING_NOISY)) {

        Intent iPause = new Intent(context , SongService.class);
        iPause.putExtra("com.Hohos.mplay.Services.SongService.MEDIA_ACTION", NOTIFY_EXTRA_PAUSE);
        context.startService(iPause);
    }

...
}

我也加了<uses-permission android:name="android.permission.ACTION_HEADSET_PLUG"/> , 这真的没有什么区别

感谢你们的帮助!

要知道用户何时拔下耳机,您需要聆听动作 ACTION_HEADSET_PLUG 并检查 state 额外内容:

Broadcast Action: Wired Headset plugged in or unplugged.

The intent will have the following extra values:

  • state - 0 for unplugged, 1 for plugged.
  • name - Headset type, human readable string
  • microphone - 1 if headset has a microphone, 0 otherwise

这是一个例子:

public class MainActivity extends Activity {

    private HeadsetBroadcastReceiver mHeadsetBroadcastReceiver;

    @Override 
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myReceiver = new HeadsetBroadcastReceiver();
    }

    @Override 
    protected void onResume() {
        IntentFilter filter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
        registerReceiver(mHeadsetBroadcastReceiver, filter);
        super.onResume();
    }

    @Override 
    protected void onPause() {
        unregisterReceiver(mHeadsetBroadcastReceiver);
        super.onPause();
    }

    private class HeadsetBroadcastReceiver extends BroadcastReceiver {
        @Override 
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
                int state = intent.getIntExtra("state", -1);

                if (state == 0) {
                    //Headset is unplugged
                } else if(state == 1) {
                    //Headset is plugged
                }
            }
        }
    }
}