I managed to get my headset buttons get recognized by my app when pressed, but one of the buttons needs to call a method that's in MyCustomActivity. The problem is onReceive's 1st parameter is a Context that cannot be cast to Activity and so I am forced to implement my BroadcastReceiver as an inner class inside MyCustomActivity.
So far so good but how do I register this inner MediaButtonEventReceiver in the manifest?
For the independent class, this was simple:
<receiver android:name=".RemoteControlReceiver">
<intent-filter>
<action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter>
</receiver>
What is the trick/syntax to do the same for MyCustomActivity's mReceiver?
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context ctx, Intent intent) {
// ...
}
}
You don't, if it's meant to be part of the Activity, you register it dynamically:
BroadcastReceiver receiver;
@Override
protected void onCreate (Bundle b)
{
super.onCreate (b);
IntentFilter filter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
filter.setPriority(10000);
receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context ctx, Intent intent) {
// ...
}
};
registerReceiver (receiver, filter);
}
Then don't forget to unregister in onPause() (to avoid leaking).
@Override
protected void onPause()
{
try{
unregisterReceiver (receiver);
}
catch (IllegalStateException e)
{
e.printStackTrace();
}
super.onPause();
}
This dynamic registration does mean however, that if your Activity isn't in the foreground, the button won't work. You can try unregistering in onDestroy() instead, but the surest way to avoid leaking is onPause().
Alternatively, to make the button respond no matter what, consider making a Service, and having that register your receiver.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With