一、来电监听
1、成员变量:
private PhoneStateListener listener;
private TelephonyManager tm;
2、注册电话状态监听代码:
tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
listener = new PhoneStateListener() {
@Override
public void onCallStateChanged(int state, final String incomingNumber) {
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
System.out.println("CALL_STATE_IDLE");
break;
case TelephonyManager.CALL_STATE_RINGING:
System.out.println("CALL_STATE_RINGING");
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
System.out.println("CALL_STATE_OFFHOOK");
break;
default:
break;
}
super.onCallStateChanged(state, incomingNumber);
}
}
tm.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
3、取消电话状态监听代码:
@Override
public void onDestroy() {
tm.listen(listener, PhoneStateListener.LISTEN_NONE);
}
二、外拨监听
TelephonyManager只能监听”来电响铃”、”空闲”、及”接通电话”状态,不能监听外拨状态,需要使用广播接收者才能监听外拨。
注意:TelephonyManager不管是来电还是外拨,”接通电话”状态都会被回调。
1、外拨电话的广播的实现
/**
* @author Administrator
* 外拨电话的广播
*/
private class OutCallReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
isOutCall = true;
String phoneNumber = getResultData();
showLocationToast(phoneNumber);
}
}
2、注册外拨广播接收者
private OutCallReceiver outCallReceiver;
@Override
public void onCreate() {
outCallReceiver = new OutCallReceiver();
IntentFilter filter = new IntentFilter("android.intent.action.NEW_OUTGOING_CALL");
registerReceiver(outCallReceiver, filter);
}
3、取消外拨广播接收者
@Override
public void onDestroy() {
unregisterReceiver(outCallReceiver);
super.onDestroy();
}
4、清单文件中添加权限
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />