Android來電監聽和去電監聽,android來電監聽

來源:互聯網
上載者:User

Android來電監聽和去電監聽,android來電監聽

我覺得寫文章就得寫得有用一些的,必須要有自己的思想,關於來電去電監聽將按照下面三個問題展開

1、監聽來電去電有什麼用?

2、怎麼監聽,來電去電監聽方式一樣嗎?

3、實戰,有什麼需要特別注意地方?

 

監聽來電去電能幹什麼

1、能夠對監聽到的電話做個標識,告訴使用者這個電話是詐騙、推銷、廣告什麼的

2、能夠針對那些特殊的電話進行自動掛斷,避免打擾到使用者

 

來電去電的監聽方式(不一樣的方式)

1、來電監聽(PhoneStateListener)

  來電監聽是使用PhoneStateListener類,使用方式是,將PhoneStateListener對象(一般是自己繼承PhoneStateListener類完成一些封裝)註冊到系統電話管理服務中去(TelephonyManager

然後通過PhoneStateListener的回調方法onCallStateChanged(int state, String incomingNumber) 實現來電的監聽 (詳細實現可以參考後面給出的拓展閱讀部分)

  註冊監聽

// phoneServiceName是服務名,一般是 "phone" --> Context.TELEPHONY_SERVICETelephonyManager telephonyManager = (TelephonyManager) mContext.getSystemService(phoneServiceName);if(telephonyManager != null) {    try {        // 註冊來電監聽        telephonyManager.listen(mTelephonyListener, PhoneStateListener.LISTEN_CALL_STATE);    } catch(Exception e) {        // 異常捕捉    }}

  PhoneStateListener的onCallStateChanged方法監聽來電狀態

@Overridepublic void onCallStateChanged(int state, String incomingNumber) {    switch (state) {        case TelephonyManager.CALL_STATE_IDLE:            // 電話掛斷            break;        case TelephonyManager.CALL_STATE_OFFHOOK:            // 來電響鈴            break;        case TelephonyManager.CALL_STATE_RINGING:            // 來電接通            break;        default:            break;    }}

  三種狀態源碼解釋

/** 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. In the latter case, another call is *  already active. */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;    // 來電接通

 

2、去電監聽(通過廣播來實現)

// OutgoingCallListener繼承一個BroadcastReceiver<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>

 

實戰,有什麼需要特別注意地方

1、雙卡雙待的手機怎麼擷取

  對於雙卡手機,每張卡都對應一個Service和一個FirewallPhoneStateListener,需要給每個服務註冊自己的FirewallPhoneStateListener,服務的名稱還會有點變化,廠商可能會修改

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、掛斷電話

  掛斷電話使用系統服務提供的介面去掛斷,但是掛斷電話是個並不能保證成功的方法,所以會有多種方式掛斷同時使用,下面提供

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 == false) {        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;}// 使用endCall掛斷不了,再使用killCall反射調用再掛一次public static boolean killCall(Context context) {    try {        // Get the boring old TelephonyManager        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);        // Get the getITelephony() method        Class classTelephony = Class.forName(telephonyManager.getClass().getName());        Method methodGetITelephony = classTelephony.getDeclaredMethod("getITelephony");        // Ignore that the method is supposed to be private        methodGetITelephony.setAccessible(true);        // Invoke getITelephony() to get the ITelephony interface        Object telephonyInterface = methodGetITelephony.invoke(telephonyManager);        // Get the endCall method from ITelephony        Class telephonyInterfaceClass = Class.forName(telephonyInterface.getClass().getName());        Method methodEndCall = telephonyInterfaceClass.getDeclaredMethod("endCall");        // Invoke endCall()        methodEndCall.invoke(telephonyInterface);    } catch (Exception ex) { // Many things can go wrong with reflection calls        return false;    }    return true;}

 

3、掛斷電話需要許可權

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

 

拓展閱讀:

這篇文章重點從整體架構機制方面來介紹電話監聽

http://www.cnblogs.com/bastard/archive/2012/11/23/2784559.html

這篇文章重點介紹一些api方法已經變數的含義

http://blog.csdn.net/skiffloveblue/article/details/7491618

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.