I registered a broadcast receiver to handle the pressing of headset media button, both in my foreground service:
public void onCreate() {
//...
headSetReceiver = new HeadSetIntentReceiver();
IntentFilter filter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
filter.addAction(Intent.ACTION_MEDIA_BUTTON);
ContextCompat.registerReceiver(this, headSetReceiver, filter, ContextCompat.RECEIVER_EXPORTED);
and in manifest:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<receiver android:name=".HeadSetIntentReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.ACTION_HEADSET_PLUG"/>
<action android:name="android.intent.action.MEDIA_BUTTON"/>
</intent-filter>
</receiver>
I'm facing a pseudo random behaviour: sometimes the receiver is called (but only if I maintain the manifest declaration, the dynamic registration seems not to be effective), sometimes not! Perhaps something is 'eating' the message? Reading the documentation, it should be sufficient registering the receiver in the onCreate method of the service (and I prefer this: I want my receiver to be called only if service is running, not always!) but this is not working!
I'm targeting sdk 33 and testing on Samsung A12 (api level 36)
[SOLVED] Finally I abandoned the idea of the broadcast receiver and used MediaSession:
MediaSession.Callback callback = new MediaSession.Callback() {
@Override
public boolean onMediaButtonEvent(@NonNull Intent intent) {
String action = intent.getAction();
if (action != null) {
if (action.equals(Intent.ACTION_MEDIA_BUTTON)) {
//...do stuff here
}
}
return super.onMediaButtonEvent(intent);
}
};
mediaSession = new MediaSession(this, "PlayerService");
mediaSession.setCallback(callback);
mediaSession.setActive(true);