Key Art for "Using Android Headset Buttons (Earphone Buttons) " by Matthew Gaunt

Using Android Headset Buttons (Earphone Buttons)


I needed to get access to the button presses on the earphone buttons that are built into the earphones that come with the Nexus One (Also with the G1 I think?) and I found it a tad harder than I expected, largely because I expected someone else of done it already for me.

So anyway, here we go in terms of how to get you up an running.

In your main activity you need to register a Broadcast Receiver:

HardButtonReceiver buttonReceiver = new HardButtonReceiver();
IntentFilter iF = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
registerReceiver(buttonReceiver, iF);

We set the priority to high for the intent filter so we gain first dibs on the button press, otherwise the media player application might be the first application to detect the press and then drop the receiver, this will hence cause your broadcast receiver to appear as though it's not working.

Now that we've set that up, we need something to catch the broadcasted intents.

public class HardButtonReceiver extends BroadcastReceiver {
    public void onReceive(Context context, Intent intent) {
        Log.v("TestApp", "Button press received");
        KeyEvent key = (KeyEvent) intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
        if(key.getAction() == KeyEvent.ACTION_UP) {
            int keycode = key.getKeyCode();
            if(keycode == KeyEvent.KEYCODE_MEDIA_NEXT) {
                Log.d("TestApp", "Next Pressed");
            } else if(keycode == KeyEvent.KEYCODE_MEDIA_PREVIOUS) {
                Log.d("TestApp", "Previous pressed");
            } else if(keycode == KeyEvent.KEYCODE_HEADSETHOOK) {
                Log.d("TestApp", "Head Set Hook pressed");

And that is all there is to it, for more information it might be worth looking at this thread:

UPDATE: I've uploaded a full example on my github page, for details see:

Orig Photo:

Profile photo
Matt Gaunt
Staff Developer Programs Engineer at Google