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

Android 來電掛斷實作:以反射呼叫隱藏的 endCall

編輯:關於 Android 程式設計

在 Android 1.5 之前,掛斷電話非常容易,直接呼叫 TelephonyManager 的 endCall() 就好。但 1.5 之後,Google 基於安全考量把 endCall 隱藏起來(標上 @hide),一般開發者拿不到這個方法。繞過去的經典做法就是反射。

源碼裡的線索

TelephonyManager 是透過系統服務取得的:

registerService(TELEPHONY_SERVICE, new ServiceFetcher() {
    public Object createService(ContextImpl ctx) {
        return new TelephonyManager(ctx.getOuterContext());
    }
});

而 android.os.ServiceManager 提供了 getService 方法,可以拿到系統服務的 IBinder:

/**
 * Returns a reference to a service with the given name.
 * @param name the name of the service to get
 * @return a reference to the service, or null if the service doesn't exist
 */
public static IBinder getService(String name) {
    return null;
}

android.telephony.TelephonyManager 是 ITelephony 介面的代理,而 ITelephony 裡的 endCall 被標記為隱藏:

/**
 * Interface used to interact with the phone.
 * {@hide}
 */
interface ITelephony {
    /**
     * End call or go to the Home screen
     * @return whether it hung up
     */
    boolean endCall();
}

整體結構

TelephonyManager 實際上是系統電話服務的代理物件,透過 AIDL 取得 IBinder 之後再做一層封裝,只代理部分公開方法。因此關係是:

TelephonyManager  ──IBinder(AIDL)──▶  系統電話服務
   代理物件

利用「綁定服務會回傳 IBinder,再用 IBinder 呼叫服務內方法」這個特性,就能繞過被隱藏的 API。

實作步驟

  1. 以反射載入 android.os.ServiceManager 類別。
  2. 呼叫它的 getService 方法取得 IBinder 物件。
  3. 在專案中建立 com.android.internal.telephony 套件(套件名稱不能改),把 ITelephony.aidl 複製進去;再建立 android.telephony 套件,複製 NeighboringCellInfo.aidl。
  4. 呼叫 endCall。

程式碼

private void endCall() {
    // ServiceManager 被系統隱藏了,只能用反射
    try {
        Class<?> clazz = CallSMSSafeService.class.getClassLoader()
                .loadClass("android.os.ServiceManager");
        Method method = clazz.getDeclaredMethod("getService", String.class);
        IBinder iBinder = (IBinder) method.invoke(null, TELEPHONY_SERVICE);
        ITelephony.Stub.asInterface(iBinder).endCall();
    } catch (Exception e) {
        e.printStackTrace();
        Log.i(TAG, "攔截電話異常");
    }
}

記得在 Manifest 加上權限,否則會拿到 SecurityException:

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

這段程式碼今天還能用嗎?

老實說,不能。這篇文章記錄的是 2014 年前後的寫法,而上面的方案在後續版本中被層層堵死,值得把時間線講清楚:

  • Android 5.x 起,ServiceManager 的 getService 逐漸改為 greylist/blacklist 管控,反射呼叫會出現警告甚至被攔。
  • Android 9(API 28)導入非 SDK 介面限制,未列入白名單的隱藏 API 反射呼叫會直接拋出例外。
  • Android 8.0 起,即使成功取得 IBinder,未持有 CALL_PRIVILEGED 權限的一般應用也無法實際掛斷通話——這個權限是 signature 等級,只有系統簽章的應用拿得到。

因此,如果你的需求是「攔截來電並自動掛斷」,現行的正確做法是使用 InCallService 或 CallScreeningService(API 24 以上)。後者正是為此設計的官方 API,只需在 onScreenCall() 中呼叫 response.disconnectCall(),應用還需要具備「預設電話應用」或「來電顯示應用」的角色。若需求是「結束自己撥出的通話」,則用 TelecomManager 的 endCall() 或 in-call 服務即可。

本文保留下來,價值在於示範一個通用的除錯思路:當官方 API 被隱藏時,先從源碼找出底層的 AIDL 介面與 ServiceManager 服務名,再判斷權限是否允許。這套方法在理解 Android framework 分層上仍然很有用,只是別再把它當成正式方案。

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