如何检测 android 耳机按钮点击 4.0 及更高版本

How to detect android headset button click on 4.0 and higher

我正在尝试检测与此相关的耳机按钮点击

http://android.amberfog.com/?p=415

这是我试过的代码

public class MainActivity extends Activity {


    private IntentFilter mIntentFilter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.actvity_main);

        mIntentFilter = new IntentFilter();
        mIntentFilter.addAction(Intent.ACTION_MEDIA_BUTTON);
        mIntentFilter.setPriority(2147483647);



        registerReceiver(mReceiver, mIntentFilter);
    }

    @Override
    public void onResume() {
        super.onResume();
        registerReceiver(mReceiver, mIntentFilter);
    }

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {


            String intentAction = intent.getAction();
            if (!Intent.ACTION_MEDIA_BUTTON.equals(intentAction)) {
                return;
            }
            KeyEvent event = (KeyEvent)intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
            if (event == null) {
                return;
            }
            int action = event.getAction();
            if (action == KeyEvent.ACTION_DOWN) {
                Toast.makeText(MainActivity.this,"Your Message", Toast.LENGTH_LONG).show();

            }
            abortBroadcast();

        }
    };

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

我想要做的就是获取有关收到按钮点击的 toast 消息,但未检测到它究竟应该做什么才能检测到按钮点击。

我正在使用 Android 4.2.1

在真实的 android 设备上进行测试

您是否在 AndroidManifest.xml 中注册了您的广播接收器?

<receiver android:name=".MainActivity">
    <intent-filter>
        <action android:name="android.intent.action.MEDIA_BUTTON" />
    </intent-filter>
</receiver>