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

Android 來電與去電監聽實戰:三個問題講透

編輯:Android 程式設計入門

寫文章要有用,就得先把問題定義清楚。關於電話狀態監聽,我把它拆成三個問題來談。

  1. 監聽來電去電到底能做什麼?
  2. 怎麼監聽?來電和去電的方式一樣嗎?
  3. 實戰時有哪些坑要避開?

一、監聽電話能做什麼

最典型的兩個應用:一是替來電做標識,告訴使用者這通電話疑似詐騙、推銷或廣告;二是攔截特定號碼自動掛斷,把打擾擋在響聲之前。這也是各家來電辨識 App 的核心能力。

二、來電監聽:PhoneStateListener

來電監聽靠 PhoneStateListener。做法是自己繼承它做一層封裝,再把這個物件註冊到系統的電話管理服務 TelephonyManager 上,之後就能在回呼方法 onCallStateChanged(int state, String incomingNumber) 裡拿到狀態與來電號碼。

註冊監聽:

// phoneServiceName 是服務名,通常是 "phone",即 Context.TELEPHONY_SERVICE
TelephonyManager telephonyManager =
        (TelephonyManager) mContext.getSystemService(phoneServiceName);
if (telephonyManager != null) {
    try {
        telephonyManager.listen(mTelephonyListener, PhoneStateListener.LISTEN_CALL_STATE);
    } catch (Exception e) {
        // 註冊失敗多半是權限或 ROM 差異導致,記得捕捉
    }
}

在回呼裡判斷狀態:

@Override
public void onCallStateChanged(int state, String incomingNumber) {
    switch (state) {
        case TelephonyManager.CALL_STATE_IDLE:
            // 沒有通話活動,電話已掛斷
            break;
        case TelephonyManager.CALL_STATE_RINGING:
            // 來電響鈴中
            break;
        case TelephonyManager.CALL_STATE_OFFHOOK:
            // 至少有一通電話正在撥出、通話或保留
            break;
        default:
            break;
    }
    mCallState = state;
}

三個狀態常數的原始碼註解:

/** Device call state: No activity. */
public static final int CALL_STATE_IDLE = 0;
/** Device call state: Ringing. A new call arrived and is ringing or waiting. */
public static final int CALL_STATE_RINGING = 1;
/** Device call state: Off-hook. At least one call exists that is dialing,
 * active, or on hold, and no calls are ringing or waiting. */
public static final int CALL_STATE_OFFHOOK = 2;

提醒一個常見誤解:CALL_STATE_RINGING 才是響鈴,OFFHOOK 是已接通或撥出中。很多教學把兩者註解寫反了。

三、去電監聽:走廣播

去電沒有現成的 Listener 可用,得靠 NEW_OUTGOING_CALL 這個系統廣播。寫一個繼承 BroadcastReceiver 的類別,在清單檔裡註冊並攔住 action:

<receiver android:name="com.test.OutgoingCallListener">
    <intent-filter>
        <action android:name="android.intent.action.PHONE_STATE"/>
        <action android:name="android.intent.action.NEW_OUTGOING_CALL" />
    </intent-filter>
</receiver>

所以答案是:來電和去電的監聽機制並不一樣,一個用 Listener,一個用廣播。

四、實戰要注意的三件事

1. 雙卡雙待怎麼拿

雙卡機每台卡各對應一個 phone 服務與各自的 PhoneStateListener,服務名稱還可能被廠商改過(例如 MIUI 某些版本的命名規則就與原生不同)。只能靠「逐一試取」的方式探測:

public ArrayList<String> getMultSimCardInfo() {
    // 這個方法是靠實機反覆嘗試累積出來的經驗,不同廠商仍可能有差異
    ArrayList<String> phoneServerList = new ArrayList<String>();
    for (int i = 1; i < 3; i++) {
        try {
            String phoneServiceName;
            if (MiuiUtils.isMiuiV6()) {
                phoneServiceName = "phone." + String.valueOf(i - 1);
            } else {
                phoneServiceName = "phone" + String.valueOf(i);
            }
            // 試著取服務,取不到就跳過
            IBinder iBinder = ServiceManager.getService(phoneServiceName);
            if (iBinder == null) continue;
            ITelephony iTelephony = ITelephony.Stub.asInterface(iBinder);
            if (iTelephony == null) continue;
            phoneServerList.add(phoneServiceName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    phoneServerList.add(Context.TELEPHONY_SERVICE); // 保底加上預設服務
    return phoneServerList;
}

2. 掛斷電話要多路並進

掛斷電話本身就沒有「保證成功」的公開 API,所以實務上會串好幾種手段,一種不行就換下一種:

public boolean endCall() {
    boolean callSuccess = false;
    ITelephony telephonyService = getTelephonyService();
    try {
        if (telephonyService != null) {
            callSuccess = telephonyService.endCall();
        }
    } catch (RemoteException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (!callSuccess) {
        // 第一種失敗,改用 service call 指令再試
        Executor eS = Executors.newSingleThreadExecutor();
        eS.execute(new Runnable() {
            @Override
            public void run() {
                disconnectCall();
            }
        });
        callSuccess = true;
    }
    return callSuccess;
}

private boolean disconnectCall() {
    Runtime runtime = Runtime.getRuntime();
    try {
        runtime.exec("service call phone 5 \n");
    } catch (Exception exc) {
        exc.printStackTrace();
        return false;
    }
    return true;
}

// 前兩招都不行,最後用反射硬呼叫一次
public static boolean killCall(Context context) {
    try {
        TelephonyManager telephonyManager =
                (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        Class classTelephony = Class.forName(telephonyManager.getClass().getName());
        Method methodGetITelephony = classTelephony.getDeclaredMethod("getITelephony");
        methodGetITelephony.setAccessible(true); // 方法原本是 private
        Object telephonyInterface = methodGetITelephony.invoke(telephonyManager);
        Class telephonyInterfaceClass = Class.forName(telephonyInterface.getClass().getName());
        Method methodEndCall = telephonyInterfaceClass.getDeclaredMethod("endCall");
        methodEndCall.invoke(telephonyInterface);
    } catch (Exception ex) {
        // 反射呼叫可能失敗的原因很多,別忘了捕捉
        return false;
    }
    return true;
}

要說清楚的是,這幾段都踩在非公開 API 上,Android 版本一升就可能失效,上架前務必在多台裝置、多個系統版本上實測。

3. 權限別忘了加

<uses-permission android:name="android.permission.CALL_PHONE" />

另外還需要 READ_PHONE_STATE,部分情境會需要 READ_CALL_LOG;Android 6.0 以後這些都屬於執行期危險權限,得動態向使用者請求。

延伸閱讀

想理解整體框架與機制,可參考 Telecom / Telephony 的 framework 分析文章;想確認各 API 與欄位的確切含義,直接翻官方 TelephonyManager 與 PhoneStateListener 文件會最準。

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