How do I intercept button presses on the headset in Android?

帅比萌擦擦* 提交于 2019-11-28 06:59:34

I recently developed an application which responded to the media button. I tested it in the Samsung Galaxy S II, and it worked.

First, in your AndroidManifest.xml, inside the <application> area, place the following:

<!-- Broadcast Receivers -->
<receiver android:name="net.work.box.controller.receivers.RemoteControlReceiver" >
    <intent-filter android:priority="1000000000000000" >
        <action android:name="android.intent.action.MEDIA_BUTTON" />
    </intent-filter>
</receiver>

Then, create a BroadcastReceiver in a different file:

public class RemoteControlReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction()) {
            KeyEvent event = (KeyEvent) intent .getParcelableExtra(Intent.EXTRA_KEY_EVENT);

            if (event == null) {
                return;
            }

            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                context.sendBroadcast(new Intent(Intents.ACTION_PLAYER_PAUSE));
            }
        }
    }

}

This is probably not the best solution out there (specially the hard coded android:priority above). However, it tried a couple of other techniques and none of them seemed to work. So I have to resort to this one... I hope I helped.

Gabriel H

Thanks for contributing.

For all the others struggling here are the final conclusions :

After lots of blood tears I finally managed to realize that there are two types of broadcasts I can intercept: some like ACTION_HEADSET_PLUG are required to be registered in the activities code.

Others like ACTION_MEDIA_BUTTON are required to be registered in the Manifest file.

In this example to intercept both intents we require to do both.

Set it in the code and in the manifest file.

if (Intent.ACTION_MEDIA_BUTTON.equals(action)) {
    if (intent.hasExtra(Intent.EXTRA_KEY_EVENT)) {
        String key = intent.getStringExtra(Intent.EXTRA_KEY_EVENT);
        toast("Button "+key+" was pressed");
    } else
        toast("Some button was pressed");
}

This code return Toast "Button null was pressed"

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!