Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 短按耳機鍵控制 FM:攔截 MEDIA_BUTTON 廣播的實作

編輯:關於 Android 程式設計

耳機線控的播放/暫停鍵,系統預設是交給音樂播放器處理的。若 FM 正在播放,卻希望這個鍵能控制收音機,就得自己攔下 MEDIA_BUTTON 這個廣播。以下做法以 MTK 平台的 FMRadioActivity 為例。

一、註冊廣播接收器

在清單檔中為 Activity 的內部類別 MediaButtonReceiver 加上 intent-filter,action 為 android.intent.action.MEDIA_BUTTON。用內部類別的好處是能直接存取 Activity 狀態,命名上要寫成「.FMRadioActivity$MediaButtonReceiver」。

二、定義回呼介面

在 Activity 中宣告一個 MediaButtonListener 介面,並實作它來處理實際的按鍵邏輯:

public interface MediaButtonListener {
    void onMediaButtonCall(Intent intent);
}

private MediaButtonListener mMediaButtonListener = new MediaButtonListener() {
    @Override
    public void onMediaButtonCall(Intent intent) {
        String action = intent.getAction();
        KeyEvent event = (KeyEvent)
            intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);

        if (Intent.ACTION_MEDIA_BUTTON.equals(action)) {
            if (KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE == event.getKeyCode()
                    && event.getAction() == KeyEvent.ACTION_UP) {
                if (mIsPlaying) {
                    refreshImageButton(false);
                    refreshActionMenuItem(false);
                    refreshPopupMenuItem(false);
                    refreshActionMenuPower(false);
                    exitService();
                }
            } else if (KeyEvent.KEYCODE_MEDIA_NEXT == event.getKeyCode()
                    && event.getAction() == KeyEvent.ACTION_UP) {
                if (mIsPlaying) {
                    seekStation(mCurrentStation, true);   // 換下一個台
                }
            }
        }
    }
};

這裡刻意判斷 ACTION_UP,避免按下與放開各觸發一次而變成「按一下等於按兩下」;KEYCODE_MEDIA_NEXT 則借用來做「下一個電台」,很符合收音機的使用語彙。

三、接收器與註冊時機

public static class MediaButtonReceiver extends BroadcastReceiver {
    static MediaButtonListener mListener = null;

    @Override
    public void onReceive(Context context, Intent intent) {
        if (null != mListener) {
            mListener.onMediaButtonCall(intent);
            this.abortBroadcast();     // 攔截,不讓音樂播放器接手
        }
    }

    public static void registerMediaButtonListener(MediaButtonListener callback) {
        mListener = callback;
    }
}

然後在三個時機做對應處理:onCreate 中註冊監聽器並呼叫 AudioManager.registerMediaButtonEventReceiver 指定自己的 ComponentName;powerupFM 時再註冊一次,確保 FM 一開就取得控制權;exitService 時呼叫 unregisterMediaButtonEventReceiver 釋放,把控制權還給系統。

abortBroadcast() 是這裡的關鍵。少了它,即使你的接收器收到了事件,系統仍會把按鍵繼續派送給其他接收器,音樂播放器可能同時被觸發。

四、幾個實務提醒

第一,Android 8.0 之後隱含廣播的註冊限制收緊,MEDIA_BUTTON 雖屬豁免名單,但用 MediaSession 才是官方推薦路線——建立 MediaSession 並設定 MediaSession.Callback,能同時拿到線控按鍵與藍牙耳機、手錶的控制事件,相容性遠比廣播好。第二,接收器中使用靜態變數傳遞監聽器容易在 Activity 重建後指向已銷毀的物件,記得在 onDestroy 中清空。第三,多按鍵耳機(音量、上一首)需要分別判斷 keyCode,並注意長按與連擊的行為定義。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved