首页 > 其他分享> > android – registerMediaButtonEventReceiver替代setMediaButtonReceiver(PendingIntent mbr)不工作
android – registerMediaButtonEventReceiver替代setMediaButtonReceiver(PendingIntent mbr)不工作
作者:互联网
按下耳机需要将我的应用程序带到前台我这是使用registerMediaButtonEventReceiver()方法,它适用于以下android os 5.1设备.现在这个方法在API级别21中已弃用.我使用mediasession.setMediaButtonReciever()将优先级设置为高,但它不起作用.
AudioManager mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
ComponentName mediaComponent = new ComponentName(context.getPackageName(), HeadsetReceiver.class.getName());
mAudioManager.registerMediaButtonEventReceiver(mediaComponent);
mediaHandler.postDelayed(this, 1000L);
我每1秒发布一次这个以获得我的优先级应用程序.我在5.1中使用此代码,但是按下媒体按钮音乐开始.我的应用程序没有任何事件将应用程序带到前台.提前致谢..
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);
解决方法:
您还必须像这样设置PlaybackState:
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);
标签:android,android-activity,android-intent,android-mediaplayer,android-audiomanager 来源: https://codeday.me/bug/20190628/1315422.html