在Android平台中,PhoneStateListener是个很有用的监听器,用来监听电话的状态,比如呼叫状态和连接服务等。Android监听通话方法如下所示: java代码: 复制代码 代码如下: 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监听通话。 java代码: mTelephonyMgr.listen(new TeleListener(), PhoneStateListener.LISTEN_CALL_STATE); 下面是个简单的测试例子,只是把呼叫状态追加到TextView之上。 java代码: 复制代码 代码如下: package eoe.demo; 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
"); 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 " + "
"); break; } case TelephonyManager.CALL_STATE_OFFHOOK: { Log.e(TAG, "CALL_STATE_OFFHOOK"); view.append("CALL_STATE_OFFHOOK" + "
"); break; } case TelephonyManager.CALL_STATE_RINGING: { Log.e(TAG, "CALL_STATE_RINGING"); view.append("CALL_STATE_RINGING" + "
"); break; } default: break; } } } }