简体   繁体   中英

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>

If you want to receive media button, you have to play audio and use mediasession.

ig

    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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM