Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

registerMediaButtonEventReceiver Alternative setMediaButtonReceiver (PendingIntent mbr) not working

On press of headset need to bring my application to foreground for this I am Using registerMediaButtonEventReceiver() method, its working fine for below android os 5.1 devices. Now this method deprecated in API level 21. I am using mediasession.setMediaButtonReciever() to take the priority high but its not working.

AudioManager mAudioManager  = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        ComponentName mediaComponent = new ComponentName(context.getPackageName(), HeadsetReceiver.class.getName());
        mAudioManager.registerMediaButtonEventReceiver(mediaComponent);
        mediaHandler.postDelayed(this, 1000L);

I am posting this for every 1 sec to get my priority app. I am using this code in 5.1 but on press of media button music starting. my app not getting any event to bring app to foreground. Thanks in Advance..

 MediaSession mSession =  new MediaSession(context,context.getPackageName());
        Intent intent = new Intent(context, HeadsetReceiver.class);
        PendingIntent pintent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        mSession.setMediaButtonReceiver(pintent);
        mSession.setActive(true);
        mediaHandler.postDelayed(this, 1000L);
like image 856
Gopi Krishna Avatar asked Oct 19 '22 04:10

Gopi Krishna


1 Answers

You also have to set a PlaybackState like this:

PlaybackState state = new PlaybackState.Builder()
                        .setActions(PlaybackStateCompat.ACTION_FAST_FORWARD | PlaybackStateCompat.ACTION_PAUSE | PlaybackStateCompat.ACTION_PLAY | PlaybackStateCompat.ACTION_PLAY_PAUSE | PlaybackStateCompat.ACTION_SKIP_TO_NEXT | PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS | PlaybackStateCompat.ACTION_STOP)
                        .setState(PlaybackStateCompat.STATE_PLAYING, 0, 1, SystemClock.elapsedRealtime())
                        .build();
mSession.setPlaybackState(state);
like image 57
DSoldo Avatar answered Jan 04 '23 06:01

DSoldo