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

Android 電話自動接聽與掛斷詳解

編輯:關於 Android 程式設計

一、通過 aidl 及反射實現掛斷電話

具體分三步:

(1)新建 ITelephony.aidl,必須新建 com.android.internal.telephony 包並放入 ITelephony.aidl 文件(構建後在 gen 下會生成 ITelephony.java 接口),文件內容如下:

package com.android.internal.telephony; interface ITelephony{ boolean endCall(); void answerRingingCall(); }

(2)在需要的類中添加如下方法,通過反射獲取電話接口的實例:

/** * @param context * @return */ private static ITelephony getITelephony(Context context) { TelephonyManager mTelephonyManager = (TelephonyManager) context .getSystemService(TELEPHONY_SERVICE); Class c = TelephonyManager.class; Method getITelephonyMethod = null; try { getITelephonyMethod = c.getDeclaredMethod("getITelephony", (Class[]) null); // 獲取聲明的方法 getITelephonyMethod.setAccessible(true); } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } try { ITelephony iTelephony = (ITelephony) getITelephonyMethod.invoke( mTelephonyManager, (Object[]) null); // 獲取實例 return iTelephony; } catch (Exception e) { e.printStackTrace(); } return iTelephony; }

(3)來電時調用此實例,再調用 endCall() 方法:

mTelephonyManager = (TelephonyManager) this .getSystemService(TELEPHONY_SERVICE); mTelephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE); //電話實例 PhoneStateListener phoneStateListener = new PhoneStateListener() { @Override public void onCallStateChanged(int state, String incomingNumber) { switch (state) { case TelephonyManager.CALL_STATE_RINGING : iTelephony = getITelephony(getApplicationContext()); //獲取電話接口 if (iTelephony != null) { try { iTelephony.endCall(); // 掛斷電話 Toast.makeText(getApplicationContext(), "endCall " + incomingNumber +" successful!", 3000).show(); } catch (RemoteException e) { e.printStackTrace(); } } break; default : break; } } };

注意:以上反射方法適用於 2.3 以前的版本,2.3 以上就失效了。

二、通過廣播通知系統進行接聽和掛斷

由於 Android 2.3 以上增加了對 android.permission.MODIFY_PHONE_STATE 的限制,2.3 之前通過反射調用 ITelephony 的做法已不適用。

查閱系統 PhoneAPP 應用(PhoneGlobals.java)可知,它實現了對耳機插入、多媒體按鍵等通知的接收與處理。個人判斷,如果系統接收到相應廣播,應該可以進行接聽或掛斷操作。2.3 以上的實現方式:

public synchronized void answerRingingCall() { // 2.3以上執行以下代碼實現自動接聽 Intent mintent = new Intent(Intent.ACTION_MEDIA_BUTTON); //按下音量 KeyEvent keyEvent = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_HEADSETHOOK); mintent.putExtra("android.intent.extra.KEY_EVENT", keyEvent); // 通話權限 允許程序撥打電話,替換系統的撥號器界面 mContext.sendOrderedBroadcast(mintent,"android.permission.CALL_PRIVILEGED"); mintent = new Intent(Intent.ACTION_MEDIA_BUTTON); keyEvent = new KeyEvent(KeyEvent.ACTION_UP,KeyEvent.KEYCODE_HEADSETHOOK); mintent.putExtra("android.intent.extra.KEY_EVENT", keyEvent); mContext.sendOrderedBroadcast(mintent,"android.permission.CALL_PRIVILEGED"); }

兩種方式都需要的權限:

   

綜合這兩種方法,就能做出電話自動接聽和掛斷的 APP 了。

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