Android擷取手機狀態和監聽手機來電狀態

來源:互聯網
上載者:User

Android擷取手機狀態和監聽手機來電狀態

擷取手機狀態:

import android.content.Context;import android.telephony.TelephonyManager;//獲得相應的系統服務TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);        /**         * 返回電話狀態         *          * CALL_STATE_IDLE 無任何狀態時          * CALL_STATE_OFFHOOK 接起電話時         * CALL_STATE_RINGING 電話進來時          */        tm.getCallState();        if(tm.getCallState() == TelephonyManager.CALL_STATE_IDLE) {        Log.d("test", "call state idle...");        } else if(tm.getCallState() == TelephonyManager.CALL_STATE_OFFHOOK) {        Log.d("test", "call state offhook...");        } else if(tm.getCallState() == TelephonyManager.CALL_STATE_RINGING) {        Log.d("test", "call state ringing...");        }


監聽手機來電狀態:

        //獲得相應的系統服務    TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);    //使用TelephonyManager對象的listen(PhoneStateListener listener, int events)    //實現PhoneStateListener listener並實現相應的方法    public class MyPhoneCallListener extends PhoneStateListener    {    @Override    public void onCallStateChanged(int state, String incomingNumber)    {      switch (state) {        case TelephonyManager.CALL_STATE_OFFHOOK:                   //電話通話的狀態            Toast.makeText(Main.this, "正在通話...", Toast.LENGTH_SHORT).show();            break;        case TelephonyManager.CALL_STATE_RINGING:                   //電話響鈴的狀態            Toast.makeText(Main.this, incomingNumber, Toast.LENGTH_SHORT).show();            break;      }      super.onCallStateChanged(state, incomingNumber);    }


第一個參數需要實現PhoneStateListener listener並實現相應的方法,第二個參數是PhoneStateListener的靜態常量,此處由於是監聽電話狀態,所以需要傳入LISTEN_CALL_STATE,而同時也需要在AndroidManifest中註冊相應的許可權


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.