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

修正 Android 音訊焦點:掛斷電話後音樂與鬧鐘同時響起的問題

編輯:關於 Android 程式設計

問題現象是這樣的:後台播放音樂的同時設定了鬧鐘,期間打了一通電話,掛斷之後鬧鐘與音樂卻同時響起。根因出在通話結束後音訊焦點(Audio Focus)的重新分配判斷過於寬鬆,導致互不關聯的兩路音訊一起被喚醒。

需要修改的檔案:frameworks\base\media\java\android\media\MediaFocusControl.java

步驟一、補充 import

import com.android.internal.telephony.ITelephony;
import android.os.ServiceManager;

步驟二、新增取得當前通話狀態的方法

優先透過 ITelephony#getPreciseCallState() 取得精確狀態;若該服務不可用或拋出 RemoteException,則退回使用 TelephonyManager#getCallState() 的較粗粒度結果。

private int getPhoneCallState() {
    int phoneCallState = TelephonyManager.CALL_STATE_IDLE;

    TelephonyManager telephonyManager =
            (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
    ITelephony telephonyService = ITelephony.Stub.asInterface(
            ServiceManager.getService(Context.TELEPHONY_SERVICE));

    if (telephonyService != null) {
        Log.w(TAG, "getPhoneCallState: telephonyService != null");
        try {
            phoneCallState = telephonyService.getPreciseCallState();
        } catch (RemoteException ex) {
            if (telephonyManager != null) {
                phoneCallState = telephonyManager.getCallState();
            }
            Log.w(TAG, "Catch exception when getPreciseCallState: ex = " + ex.getMessage());
        }
    } else {
        Log.w(TAG, "getPhoneCallState: telephonyService == null");
        if (telephonyManager != null) {
            phoneCallState = telephonyManager.getCallState();
        }
    }
    Log.w(TAG, "getPhoneCallState: phoneCallState = " + phoneCallState);
    return phoneCallState;
}

步驟三、收緊 canReassignAudioFocus() 的判斷條件

原本的方法只檢查焦點堆疊頂端是否為通話焦點(IN_VOICE_COMM_FOCUS_ID)。修改後再加上「當前通話狀態必須不是 IDLE」這個條件,也就是只有在通話進行中或來電響鈴時,才拒絕重新分配焦點。

修改前:

private boolean canReassignAudioFocus() {
    // focus requests are rejected during a phone call or when the phone is ringing
    // this is equivalent to IN_VOICE_COMM_FOCUS_ID having the focus
    if (!mFocusStack.isEmpty() && mFocusStack.peek().hasSameClient(IN_VOICE_COMM_FOCUS_ID)) {
        return false;
    }
    return true;
}

修改後:

private boolean canReassignAudioFocus() {
    // focus requests are rejected during a phone call or when the phone is ringing
    // this is equivalent to IN_VOICE_COMM_FOCUS_ID having the focus
    if (!mFocusStack.isEmpty()
            && mFocusStack.peek().hasSameClient(IN_VOICE_COMM_FOCUS_ID)
            && (getPhoneCallState() != TelephonyManager.CALL_STATE_IDLE)) {
        Log.w(TAG, "canReassignAudioFocus: return false");
        return false;
    }
    Log.w(TAG, "canReassignAudioFocus: return true");
    return true;
}

這樣一來,通話結束、焦點堆疊已空或狀態回到 IDLE 時,焦點就能正常重新分配,不會再出現鬧鐘與音樂同時發聲的情況。修改原始碼後需重新編譯 framework 並刷新機器的系統鏡像才能驗證。

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