Android監聽通話正確操作方法介紹
對智能手機有所了解的朋友都知道其中一個應用廣泛的手機操作系統Android 開源手機操作系統。那么在這一系統中想要實現通話的監聽功能的話,我們應當如何操作呢?在這里就為大家詳細介紹了Android監聽通話的相關實現方法。#t#
開發應用程序的時候,我們希望能夠監聽電話的呼入,以便執行暫停音樂播放器等操作,當電話結束之后,再次恢復播放。在Android平臺可以通過TelephonyManager和PhoneStateListener來完成此任務。
TelephonyManager作為一個Service接口提供給用戶查詢電話相關的內容,比如IMEI,LineNumber1等。通過下面的代碼即可獲得TelephonyManager的實例。
- TelephonyManager mTelephonyMgr = (TelephonyManager) this
- .getSystemService(Context.TELEPHONY_SERVICE);
在Android平臺中,PhoneStateListener是個很有用的監聽器,用來監聽電話的狀態,比如呼叫狀態和連接服務等。Android監聽通話方法如下所示:
- public void onCallForwardingIndicatorChanged(boolean cfi)
- public void onCallStateChanged(int state,
String incomingNumber)- public void onCellLocationChanged(CellLocation location)
- public void onDataActivity(int direction)
- public void onDataConnectionStateChanged(int state)
- public void onMessageWaitingIndicatorChanged(boolean mwi)
- public void onServiceStateChanged
(ServiceState serviceState)- public void onSignalStrengthChanged(int asu)
這里我們只需要覆蓋onCallStateChanged()方法即可監聽呼叫狀態。在TelephonyManager中定義了三種狀態,分別是振鈴(RINGING),摘機(OFFHOOK)和空閑(IDLE),我們通過state的值就知道現在的電話狀態了。
獲得了TelephonyManager接口之后,調用listen()方法即可實現Android監聽通話。
- mTelephonyMgr.listen(new TeleListener(),
- PhoneStateListener.LISTEN_CALL_STATE);
下面是個簡單的測試例子,只是把呼叫狀態追加到TextView之上。
- package com.j2medev;
- import android.app.Activity;
- import android.content.Context;
- import android.os.Bundle;
- import android.telephony.PhoneStateListener;
- import android.telephony.TelephonyManager;
- import android.util.Log;
- import android.widget.TextView;
- public class Telephony extends Activity {
- private static final String TAG = "Telephony";
- TextView view = null;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- TelephonyManager mTelephonyMgr = (TelephonyManager) this
- .getSystemService(Context.TELEPHONY_SERVICE);
- mTelephonyMgr.listen(new TeleListener(),
- PhoneStateListener.LISTEN_CALL_STATE);
- view = new TextView(this);
- view.setText("listen the state of phone\n");
- setContentView(view);
- }
- class TeleListener extends PhoneStateListener {
- @Override
- public void onCallStateChanged(int state,
String incomingNumber) {- super.onCallStateChanged(state, incomingNumber);
- switch (state) {
- case TelephonyManager.CALL_STATE_IDLE: {
- Log.e(TAG, "CALL_STATE_IDLE");
- view.append("CALL_STATE_IDLE " + "\n");
- break;
- }
- case TelephonyManager.CALL_STATE_OFFHOOK: {
- Log.e(TAG, "CALL_STATE_OFFHOOK");
- view.append("CALL_STATE_OFFHOOK" + "\n");
- break;
- }
- case TelephonyManager.CALL_STATE_RINGING: {
- Log.e(TAG, "CALL_STATE_RINGING");
- view.append("CALL_STATE_RINGING" + "\n");
- break;
- }
- default:
- break;
- }
- }
- }
- }
不要忘記在AndroidManifest.xml里面添加個permission.
- < uses-permission android:name=
"android.permission.READ_PHONE_STATE" />
Android監聽通話的具體操作方法就為大家介紹到這里。