Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How register Broadcast Receiver for media button in Oreo?

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>
like image 739
Alessandro Marino Avatar asked Feb 17 '18 11:02

Alessandro Marino


1 Answers

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();
like image 102
오효민 Avatar answered Sep 16 '22 19:09

오효민