I\'m trying to add a simple broadcast receiver to my audio application, so that I can mute everything when the user clicks their ACTION_MEDIA_BUTTON on their headset. I\'ve rea
A Receiver for the ACTION_MEDIA_BUTTON action should be registered with AudioManager's registerMediaButtonEventReceiver() method, instead of the regular registerReceiver() method in the Activity. Unlike normal dynamic Receiver registration, however, this method takes the class as the parameter, instead of an instance of the class. The easiest way to this is to create a separate class file for it:
public class MediaButtonIntentReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
...
}
}
And we would need this Receiver listed in the manifest, as well:
Now, the example in the link we've referred to is wrong, as the registerMediaButtonEventReceiver() method is expecting a ComponentName object, not just the name of the Receiver class itself. We need to change the example as follows:
AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
am.registerMediaButtonEventReceiver(
new ComponentName(this, MediaButtonIntentReceiver.class));
And, as we've established, you don't need the mContext field, as you are in anActivity Context, and can just use getSystemService() without qualification. You can also do away with the IntentFilter object, as the listing in the manifest takes care of that already.