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

Android 實現自動接聽與掛斷電話

編輯:關於 Android 程式設計

通話自定義場景(通話錄音、來電自動應答、簡易會議系統等)經常需要程序化地接聽或掛斷電話。由於 Android 對通話相關操作管控嚴格,這類功能需要借助反射調用系統隱藏接口,並依賴系統簽名或特權權限。下面給出一套可直接借鑒的實現。

一、工具類 PhoneUtils

package com.ebupt.phonerecorddemo.server;

import java.lang.reflect.Method;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import com.android.internal.telephony.ITelephony;

public class PhoneUtils {
    static String TAG = "PhoneUtils";

    /**
     * 從 TelephonyManager 中實例化 ITelephony 並返回
     */
    static public ITelephony getITelephony(TelephonyManager telMgr) throws Exception {
        Method getITelephonyMethod = telMgr.getClass().getDeclaredMethod("getITelephony");
        getITelephonyMethod.setAccessible(true);// 私有化函數也能使用
        return (ITelephony) getITelephonyMethod.invoke(telMgr);
    }

    // 自動接聽
    public static void autoAnswerPhone(Context c, TelephonyManager tm) {
        try {
            Log.i(TAG, "autoAnswerPhone");
            ITelephony itelephony = getITelephony(tm);
            // itelephony.silenceRinger();
            itelephony.answerRingingCall();
        } catch (Exception e) {
            e.printStackTrace();
            try {
                Log.e(TAG, "用於 Android 2.3 及 2.3 以上的版本上");
                Intent intent = new Intent("android.intent.action.MEDIA_BUTTON");
                KeyEvent keyEvent = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_HEADSETHOOK);
                intent.putExtra("android.intent.extra.KEY_EVENT", keyEvent);
                c.sendOrderedBroadcast(intent, "android.permission.CALL_PRIVILEGED");

                intent = new Intent("android.intent.action.MEDIA_BUTTON");
                keyEvent = new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_HEADSETHOOK);
                intent.putExtra("android.intent.extra.KEY_EVENT", keyEvent);
                c.sendOrderedBroadcast(intent, "android.permission.CALL_PRIVILEGED");

                Intent localIntent1 = new Intent(Intent.ACTION_HEADSET_PLUG);
                localIntent1.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                localIntent1.putExtra("state", 1);
                localIntent1.putExtra("microphone", 1);
                localIntent1.putExtra("name", "Headset");
                c.sendOrderedBroadcast(localIntent1, "android.permission.CALL_PRIVILEGED");

                Intent localIntent2 = new Intent(Intent.ACTION_MEDIA_BUTTON);
                KeyEvent localKeyEvent1 = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_HEADSETHOOK);
                localIntent2.putExtra("android.intent.extra.KEY_EVENT", localKeyEvent1);
                c.sendOrderedBroadcast(localIntent2, "android.permission.CALL_PRIVILEGED");

                Intent localIntent3 = new Intent(Intent.ACTION_MEDIA_BUTTON);
                KeyEvent localKeyEvent2 = new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_HEADSETHOOK);
                localIntent3.putExtra("android.intent.extra.KEY_EVENT", localKeyEvent2);
                c.sendOrderedBroadcast(localIntent3, "android.permission.CALL_PRIVILEGED");

                Intent localIntent4 = new Intent(Intent.ACTION_HEADSET_PLUG);
                localIntent4.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                localIntent4.putExtra("state", 0);
                localIntent4.putExtra("microphone", 1);
                localIntent4.putExtra("name", "Headset");
                c.sendOrderedBroadcast(localIntent4, "android.permission.CALL_PRIVILEGED");
            } catch (Exception e2) {
                e2.printStackTrace();
                Intent meidaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
                KeyEvent keyEvent = new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_HEADSETHOOK);
                meidaButtonIntent.putExtra(Intent.EXTRA_KEY_EVENT, keyEvent);
                c.sendOrderedBroadcast(meidaButtonIntent, null);
            }
        }
    }

    // 自動掛斷
    public static void endPhone(Context c, TelephonyManager tm) {
        try {
            Log.i(TAG, "endPhone");
            ITelephony iTelephony;
            Method getITelephonyMethod = TelephonyManager.class
                    .getDeclaredMethod("getITelephony", (Class[]) null);
            getITelephonyMethod.setAccessible(true);
            iTelephony = (ITelephony) getITelephonyMethod.invoke(tm, (Object[]) null);
            // 掛斷電話
            iTelephony.endCall();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

二、ITelephony 接口

這是我們通過反射拿到的目標接口,定義在 com.android.internal.telephony 包下:

package com.android.internal.telephony;

/**
 * Interface used to interact with the phone. Mostly this is used by the
 * TelephonyManager class. A few places are still using this directly.
 * Please clean them up if possible and use TelephonyManager instead.
 * {@hide}
 */
interface ITelephony {

    /**
     * End call or go to the Home screen
     * @return whether it hung up
     */
    boolean endCall();

    /**
     * Answer the currently-ringing call.
     * 若已有當前通話,會自動保持;若兩路都佔用,則掛斷當前通話。
     */
    void answerRingingCall();

    /**
     * Silence the ringer if an incoming call is currently ringing.
     * 若鈴聲已靜音或根本沒有來電,調用也無副作用。
     */
    void silenceRinger();

    /** Allow mobile data connections. */
    boolean enableDataConnectivity();

    /** Disallow mobile data connections. */
    boolean disableDataConnectivity();

    /** Report whether data connectivity is possible. */
    boolean isDataConnectivityPossible();
}

三、來電狀態廣播接收者

要實現「自動接聽」,前提是能感知來電。註冊一個監聽 android.intent.action.PHONE_STATE 的廣播接收者,根據通話狀態分發處理:

package com.ebupt.phonerecorddemo.server;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import android.util.Log;

public class PhoneReceiver extends BroadcastReceiver {
    String TAG = "PhoneReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {
        TelephonyManager tm = (TelephonyManager) context
                .getSystemService(Service.TELEPHONY_SERVICE);

        switch (tm.getCallState()) {
        case TelephonyManager.CALL_STATE_OFFHOOK: // 電話打進來接通狀態;電話打出時首先監聽到的狀態
            Log.i("onCallStateChanged", "CALL_STATE_OFFHOOK");
            break;
        case TelephonyManager.CALL_STATE_RINGING: // 電話打進來狀態
            Log.i("onCallStateChanged", "CALL_STATE_RINGING");
            PhoneUtils.autoAnswerPhone(context, tm);
            break;
        case TelephonyManager.CALL_STATE_IDLE: // 無論打出還是打進,結束時都會監聽到的狀態
            Log.i("onCallStateChanged", "CALL_STATE_IDLE");
            break;
        }
    }
}

實現原理與注意事項

為什麼需要兩套方案? answerRingingCall() 是最直接的路徑,但它是 @hide 接口,需要反射調用;在部分較新系統版本上,反射會因為隱藏 API 限制而失敗。此時的備選方案是「偽造耳機按鍵事件」:先發送一條 HEADSET_PLUG 廣播假裝插上了耳機,再發一對 MEDIA_BUTTON 按下/抬起事件(KEYCODE_HEADSETHOOK 就是耳機線控鍵),系統便會當作用戶按了接聽鍵。最後再補一條 state=0 的 HEADSET_PLUG 把耳機狀態還原,避免影響後續音頻路由。最外層還有一層兜底,只發一個 ACTION_UP 的媒體鍵事件。

權限要求。 無論哪種方案,都需要在 Manifest 中聲明:

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

而 android.permission.CALL_PRIVILEGED 屬於系統/特權權限,普通第三方應用無法獲得,這意味著廣播備選方案實際上只在系統應用或具備系統簽名的 APK 中可靠生效。此外,來電廣播接收者需要在 Manifest 中靜態注册並配置 android.intent.action.PHONE_STATE 的 intent-filter,同時加上足夠的優先級。

版本差異。 從 Android 各版本的演進來看,ITelephony 的方法簽名和 TelephonyManager 的內部實現都有過調整(例如後續版本增加了 answerRingingCall 的公開替代方案 TelecomManager.acceptRingingCall())。因此生產環境中建議做多路兼容:優先嘗試反射,失敗則降級到公開 API,並在日誌中記錄失敗原因以便排查。

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