获取电话通相关状态方法及说明:
1>编写一个监听器类,该类继承自PhoneStateListener:
重写该类中的监听方法:
classMyPhoneListener extends PhoneStateListener{
/**
* 当电话状态改变了将会执行该方法
*/
@Override
publicvoid onCallStateChanged(int state, String incomingNumber) {
Log.i("info","incomingNumber:"+incomingNumber);
switch(state) {
caseTelephonyManager.CALL_STATE_IDLE:
Log.i("info","CALL_STATE_IDLE");
break;
caseTelephonyManager.CALL_STATE_OFFHOOK:
Log.i("info","CALL_STATE_OFFHOOK");
break;
caseTelephonyManager.CALL_STATE_RINGING:
Log.i("info","CALL_STATE_RINGING");
break;
}
}
}
2>创建并启动监听服务(需要执行如下代码才能监听并执行监听器中重写的onCallStateChangerd方法);
TelephonyManagermanager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
manager.listen(new MyPhotoListener(),PhoneStateListener.LISTEN_CALL_STATE);
3>在清单文件中注册权限。
android.permisison.READ_PHONE_STATE
/** Device call state: No activity. */
手机没有发生通话行为,空闲状态;
结束通话会触发该事件。
public static final int CALL_STATE_IDLE= 0;
/** Device call state: Ringing. A new callarrived 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 onecall exists
* that is dialing, active, or on hold,and no calls are ringing
* or waiting. */
这个要重点说一下,看有资料翻译OFFHOOK是挂机,这个是错误的。挂机会直接执行CALL_STATE_IDLE。OFFHOOK是摘机,就是接电话。
原文翻译:电话的(通话)状态:摘机。至少存在一个拨号,接通,或者呼叫保持的业务,并且不存在其他呼叫的振铃或者呼叫等待。
就是在拨号时、接电话时、接通处于呼叫等待中的来电时、都会触发该事件。
publicstaticfinalintCALL_STATE_OFFHOOK = 2;