RemoteControlClient是从API 14也就是android 4.0开始出现的类,用于在锁屏状态控制音乐播放。界面是系统提供的。
api doc文档上附了一段注册代码
ComponentName myEventReceiver = new ComponentName(getPackageName(), MyRemoteControlEventReceiver.class.getName()); AudioManager myAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); myAudioManager.registerMediaButtonEventReceiver(myEventReceiver); // build the PendingIntent for the remote control client Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON); mediaButtonIntent.setComponent(myEventReceiver); PendingIntent mediaPendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, mediaButtonIntent, 0); // create and register the remote control client RemoteControlClient myRemoteControlClient = new RemoteControlClient(mediaPendingIntent); myAudioManager.registerRemoteControlClient(myRemoteControlClient);上面的代码开始时注册了耳机按键的事件,接着注册了RemoteControlClient。
要想弄出RemoteControlClient的界面,上面的代码还不够,还需要把当前音乐状态设置为正在播放
mClient.setPlaybackState(RemoteControlClient.PLAYSTATE_PLAYING)
并且必须获取当前的stream focus
am.requestAudioFocus(new OnAudioFocusChangeListener() { @Override public void onAudioFocusChange(int focusChange) { System.out.println("focusChange = " + focusChange); } }, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
这样,在锁屏状态系统界面就能出现了,默认只有一个播放暂停按钮。要想显示额外的信息,使用editMetadata(boolean startEmpty)去put,如果想多显示几个控制按钮,如下:
int flags = RemoteControlClient.FLAG_KEY_MEDIA_PREVIOUS | RemoteControlClient.FLAG_KEY_MEDIA_NEXT | RemoteControlClient.FLAG_KEY_MEDIA_PLAY | RemoteControlClient.FLAG_KEY_MEDIA_PAUSE | RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE | RemoteControlClient.FLAG_KEY_MEDIA_STOP; mClient.setTransportControlFlags(flags);
所有按键的响应事件都在注册的receiver中。