Here's my effort to make a working code to handle a headset button event the best way. I read the Android developer guide, but it is obviously wrong because they ask to start listening registering a class name.
am.registerMediaButtonEventReceiver(RemoteControlReceiver); // Wrong
So I check out other examples to correct the code. For example many secret suggestions have been published in this question, I also tried other code such as this, and another solution with MediaSession, and cleaning the unneeded I wrote this code:
I implemented the class RemoteControlReceiver. Apparently there is no need for a static inner class, in fact, see this comment:
public class RemoteControlReceiver extends BroadcastReceiver {
public RemoteControlReceiver() {
super();
}
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "EVENT!!", Toast.LENGTH_SHORT).show();
if (Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction())) {
KeyEvent event = (KeyEvent) intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if (KeyEvent.KEYCODE_MEDIA_PLAY == event.getKeyCode()) {
Toast.makeText(context, "EVENT!!", Toast.LENGTH_SHORT).show();
}
}
}
}
Then I registered the intent inside the MainActivity onCreate(){...
AudioManager am = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
ComponentName mReceiverComponent = new ComponentName(this, RemoteControlReceiver.class);
am.registerMediaButtonEventReceiver(mReceiverComponent);
The registerMediaButtonEventReceiver is deprecated by the way...
Inside the manifest I recorder the filter, after the activity tag:
<activity>
...
</activity>
<receiver android:name=".RemoteControlReceiver" android:enabled="true">
<intent-filter android:priority="2147483647">
<action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter>
</receiver>
Note: with a static inner class would be, e.g., ".MainActivity$RemoteControlReceiver".
I am working on
compileSdkVersion 24
buildToolsVersion "24.0.0"
...
minSdkVersion 21
targetSdkVersion 24
Here my questions:
- Why the registerMediaButtonEventReceiver is deprecated? Seems all this paradigm is wrong nowadays, but I found no information on how to handle these class of problems on the Android Developer Portal.
- Which way may I interact with the MainActivity? My purpose is to perform an action on the MainActivity when some headset operation has been performed.
MainActivity$MediaButtonReceiver
but your class is calledRemoteControlReceiver
. Which is it? – Taffrail