編輯:Android 程式設計入門
寫文章要有用,就得先把問題定義清楚。關於電話狀態監聽,我把它拆成三個問題來談。
最典型的兩個應用:一是替來電做標識,告訴使用者這通電話疑似詐騙、推銷或廣告;二是攔截特定號碼自動掛斷,把打擾擋在響聲之前。這也是各家來電辨識 App 的核心能力。
來電監聽靠 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,一個用廣播。
雙卡機每台卡各對應一個 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;
}
掛斷電話本身就沒有「保證成功」的公開 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 版本一升就可能失效,上架前務必在多台裝置、多個系統版本上實測。
<uses-permission android:name="android.permission.CALL_PHONE" />
另外還需要 READ_PHONE_STATE,部分情境會需要 READ_CALL_LOG;Android 6.0 以後這些都屬於執行期危險權限,得動態向使用者請求。
想理解整體框架與機制,可參考 Telecom / Telephony 的 framework 分析文章;想確認各 API 與欄位的確切含義,直接翻官方 TelephonyManager 與 PhoneStateListener 文件會最準。
Android 圖片顯示元件 ImageView 詳解
ImageView 是 Android 中最基礎的圖片顯示元件,掌握它才能真正做好介面呈現。本文將說明它的基本概念、關鍵屬性,並透過實作釐清 src 與 backgrou
Android Touch 事件傳遞機制解析
Android 的觸控事件由 MotionEvent 表示,包含觸碰位置、時間、動作類型與多指觸控資訊。事件處理主要圍繞分發、攔截與消費三個概念。事件類型常見事件包含 A
Android Activity 的四種啟動模式詳解(附實例)
在深入探討啟動模式之前,先了解 Android 對 Activity 的管理機制。Android 採用 Task 來管理多個 Activity:當我們啟動一個應用時,系統
Android Studio 導入第三方庫(SlidingMenu)完整教程
身為 Android 初學者,看著網上各種例子,特此記錄一下導入第三方庫的過程。注意:本教程針對像 SlidingMenu 這樣使用 Android Studio 結構的