I have a problem with the new Android version, that is 8.0 (Oreo). I have to register a broadcast and I do this with this code:
// android.intent.action.MEDIA_BUTTON
IntentFilter filter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
r = new MediaButtonIntentReceiver();
// this line sets receiver priority
filter.setPriority(999);
registerReceiver(r, filter);
This works on older Android version but on Android 8 this doesn't work because it is necessary register explicit broadcast but I don't know how. How can I register explicit broadcast to detect media button?
This is in Manifest.xml:
<receiver android:name=".MediaButtonIntentReceiver">
<intent-filter android:priority="999">
<action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter>
</receiver>
If you want to receive media button, you have to play audio and use mediasession.
i.g
MediaSession ms = new MediaSession(getApplicationContext(), getPackageName());
ms.setActive(true);
ms.setCallback(new MediaSession.Callback() {
@Override
public boolean onMediaButtonEvent(Intent mediaButtonIntent) {
Log.e("hmhm", "hmhm media button");
return super.onMediaButtonEvent(mediaButtonIntent);
}
});
// you can button by receiver after terminating your app
ms.setMediaButtonReceiver(mbr);
// play dummy audio
AudioTrack at = new AudioTrack(AudioManager.STREAM_MUSIC, 48000, AudioFormat.CHANNEL_OUT_STEREO, AudioFormat.ENCODING_PCM_16BIT,
AudioTrack.getMinBufferSize(48000, AudioFormat.CHANNEL_OUT_STEREO, AudioFormat.ENCODING_PCM_16BIT), AudioTrack.MODE_STREAM);
at.play();
// a little sleep
at.stop();
at.release();
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