JDS JDS - 2 months ago 56
Java Question

Android - registering a headset button click with BroadcastReceiver

Alright, so I have a headset w/ single button and want to do a simple Toast when the button is pressed.

Right now I have the following code:

public class MediaButtonIntentReceiver extends BroadcastReceiver {

public MediaButtonIntentReceiver() {
super();
}

@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) {
// do something
Toast.makeText(context, "BUTTON PRESSED!", Toast.LENGTH_SHORT).show();
}
abortBroadcast();
}
}


And my main activity is the following:

public class mainActivity extends Activity {

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

IntentFilter filter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
MediaButtonIntentReceiver r = new MediaButtonIntentReceiver();
registerReceiver(r, filter);

}
}


Nothing happens though when I push the button though.

I'm pretty sure something is wrong with my permissions/xml in the manifest. Here's the receiver XML so far:

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


....

and:



I notice in LogCat that when I press the button I get an error from "BluetoothIntentReceiver" saying "onReceive() Action : android.intent.action.MEDIA_BUTTON"

Thanks for any help guys, been really stuck on this the last few days.

JDS JDS
Answer

Just wanted to answer my own question in case others come across similar issues.

The code does work, just I wasn't seeing the Toast because I had another headset button controller app installed (and running in the background), so I guess it took priority over mine. However when I put

    IntentFilter filter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);//"android.intent.action.MEDIA_BUTTON"
    MediaButtonIntentReceiver r = new MediaButtonIntentReceiver();
    filter.setPriority(1000); //this line sets receiver priority
    registerReceiver(r, filter);

It was able to work even with the other app installed. Also, you don't need both the above AND the XML, one or the other is fine as ways of registering the intent receiver.