Android RemoteController使用
RemoteController在API 19 引進,用來給音樂控制提供標準接口。長久以來,音樂播放在Android平臺沒有一個標準的接口,所有播放器都使用自己的方式實現對音樂的控制,最常見的方式是在Service中進行音樂播放,通過PendingIntent進行播放事件的傳遞及控制,因此就帶來了一個問題。任何一個第三方app無法通過標準方式獲取到當前正在播放的音樂的信息,更無法進行控制。RemoteController的出現恰好解決了這個問題,RemoteController需要和RemoteControlClient配合使用,從命名上能夠看出,RemoteController是控制及信息獲取端的接口,用來進行音樂信息的獲取以及音樂播放動作的發送。RemoteControlClient是播放器端的接口,用來獲取并執行播放動作,同時講當前播放狀態信息進行同步。
1.繼承 NotificationListenerService 并實現RemoteController.OnClientUpdateListener接口來創建remoteController對象并獲取播放進度
@TargetApi(Build.VERSION_CODES.KITKAT) public class MusicStateListener extends NotificationListenerServiceimplements RemoteController.OnClientUpdateListener { }NotificationListenerService的主要作用是用來獲取和操作通知欄通知,由于很奇葩的原因,為了獲取合法的remoteController對象,必須實現這樣一個NotificationListenerService并作為onClientUpdateListener傳入remoteController來實現。
public void registerRemoteController() {remoteController = new RemoteController(this, this);boolean registered;try {registered = ((AudioManager) getSystemService(AUDIO_SERVICE)).registerRemoteController(remoteController);} catch (NullPointerException e) {registered = false;}if (registered) {try {remoteController.setArtworkConfiguration(getResources().getDimensionPixelSize(R.dimen.remote_artwork_bitmap_width),getResources().getDimensionPixelSize(R.dimen.remote_artwork_bitmap_height));remoteController.setSynchronizationMode(RemoteController.POSITION_SYNCHRONIZATION_CHECK);} catch (IllegalArgumentException e) {e.printStackTrace();}}}RemoteController的初始化傳入的兩個參數分別是context和updateListener,而且此處的context必須是notificationListenerService
2.獲取播放信息
合法register之后在回調中會接收到播放信息,包括播放/暫停等動作信息以及歌曲的meta信息
/*** Interface definition for the callbacks to be invoked whenever media events, metadata* and playback status are available.*/ public interface OnClientUpdateListener {/*** Called whenever all information, previously received through the other* methods of the listener, is no longer valid and is about to be refreshed.* This is typically called whenever a new {@link RemoteControlClient} has been selected* by the system to have its media information published.* @param clearing true if there is no selected RemoteControlClient and no information* is available.*/public void onClientChange(boolean clearing);/*** Called whenever the playback state has changed.* It is called when no information is known about the playback progress in the media and* the playback speed.* @param state one of the playback states authorized* in {@link RemoteControlClient#setPlaybackState(int)}.*/public void onClientPlaybackStateUpdate(int state);/*** Called whenever the playback state has changed, and playback position* and speed are known.* @param state one of the playback states authorized* in {@link RemoteControlClient#setPlaybackState(int)}.* @param stateChangeTimeMs the system time at which the state change was reported,* expressed in ms. Based on {@link android.os.SystemClock#elapsedRealtime()}.* @param currentPosMs a positive value for the current media playback position expressed* in ms, a negative value if the position is temporarily unknown.* @param speed a value expressed as a ratio of 1x playback: 1.0f is normal playback,* 2.0f is 2x, 0.5f is half-speed, -2.0f is rewind at 2x speed. 0.0f means nothing is* playing (e.g. when state is {@link RemoteControlClient#PLAYSTATE_ERROR}).*/public void onClientPlaybackStateUpdate(int state, long stateChangeTimeMs,long currentPosMs, float speed);/*** Called whenever the transport control flags have changed.* @param transportControlFlags one of the flags authorized* in {@link RemoteControlClient#setTransportControlFlags(int)}.*/public void onClientTransportControlUpdate(int transportControlFlags);/*** Called whenever new metadata is available.* See the {@link MediaMetadataEditor#putLong(int, long)},* {@link MediaMetadataEditor#putString(int, String)},* {@link MediaMetadataEditor#putBitmap(int, Bitmap)}, and* {@link MediaMetadataEditor#putObject(int, Object)} methods for the various keys that* can be queried.* @param metadataEditor the container of the new metadata.*/public void onClientMetadataUpdate(MetadataEditor metadataEditor); };音樂的meta信息從onClientMetadataUpdate回調中獲取,能夠獲取到的字段包括歌手、名稱、專輯名稱、專輯封面等。注意此處獲取到的專輯封面bitmap的尺寸是由注冊remoteController時setArtworkConfiguration (int, int)來決定的
API文檔
3.音樂控制
音樂的控制主要通過remoteController的sendMediaKeyEvent來實現?需要注意的是音樂的控制在邏輯上是模擬按鈕的點擊動作來實現的,所以在send一個keyCode時需要先后send KEY_ACTION_DOWN和KEY_ACTION_UP兩個event來實現,所以我的實現是這樣的
public boolean sendMusicKeyEvent(int keyCode) {if (!clientIdLost && remoteController != null) {// send "down" and "up" key events.KeyEvent keyEvent = new KeyEvent(KeyEvent.ACTION_DOWN, keyCode);boolean down = remoteController.sendMediaKeyEvent(keyEvent);keyEvent = new KeyEvent(KeyEvent.ACTION_UP, keyCode);boolean up = remoteController.sendMediaKeyEvent(keyEvent);return down && up;} else {long eventTime = SystemClock.uptimeMillis();KeyEvent key = new KeyEvent(eventTime, eventTime, KeyEvent.ACTION_DOWN, keyCode, 0);dispatchMediaKeyToAudioService(key);dispatchMediaKeyToAudioService(KeyEvent.changeAction(key, KeyEvent.ACTION_UP));}return false;}private void dispatchMediaKeyToAudioService(KeyEvent event) {AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);if (audioManager != null) {try {audioManager.dispatchMediaKeyEvent(event);} catch (Exception e) {e.printStackTrace();}}}前面一部分是剛才講到的通過remoteController來sendMediaKeyEvent,后面一部分是當remoteClient發生變化時remoteController的傳遞會失效,此時可以通過AudioManager來傳遞事件,
注意事項
1.注冊RemoteController時OnClientUpdateListener必須是NotificationListenerService?2.發送KeyEvent時先發送ACTION_DOWN再發送ACTION_UP才是一個完整的事件;
- 2014年10月08日發布?
- 更多
總結
以上是生活随笔為你收集整理的Android RemoteController使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 关于ViewTreeObserver的理
- 下一篇: 视频播放器的界面设计并实现播放器