1.第一步,写一个Receiver继承自BroadcastReceiver
public class MyPhoneState extends PhoneStateListener {
MyService myService;
@Override
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
case TelephonyManager.CALL_STATE_IDLE: //空闲
// DebugLogUtil.getInstance().Info("通话:空闲");
break;
case TelephonyManager.CALL_STATE_RINGING: //来电
DebugLogUtil.getInstance().Info("通话:来电");
break;
case TelephonyManager.CALL_STATE_OFFHOOK: //摘机(正在通话中)
// DebugLogUtil.getInstance().Info("通话:摘机");
break;
}
}
}
权限:uses-permissionandroid:name=“android.permission.READ_PHONE_STATE”/
来电action为TelephonyManager.ACTION_PHONE_STATE_CHANGED
去电action为Intent.ACTION_NEW_OUTGOING_CALL
写广播接收者
public class PhoneStateReceiver extends BroadcastReceiver {
/*来电action为TelephonyManager.ACTION_PHONE_STATE_CHANGED
去电action为Intent.ACTION_NEW_OUTGOING_CALL*/
// private static MyPhoneStateListener phoneListener = new MyPhoneStateListener();
private static boolean incomingFlag = false;
private static String incoming_number = null;
@Override
public void onReceive(Context context, Intent intent) {
//如果是拨打电话
if (intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)) {
incomingFlag = false;
String phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
DebugLogUtil.getInstance().Info("call OUT:" + phoneNumber);
} else {
//如果是来电
TelephonyManager tm =
(TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE);
switch (tm.getCallState()) {
case TelephonyManager.CALL_STATE_RINGING:
incomingFlag = true;//标识当前是来电
incoming_number = intent.getStringExtra("incoming_number");
DebugLogUtil.getInstance().Info("新来电:" + incoming_number);
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
if (incomingFlag) {
DebugLogUtil.getInstance().Info("incoming ACCEPT :" + incoming_number);
}
break;
case TelephonyManager.CALL_STATE_IDLE:
if (incomingFlag) {
DebugLogUtil.getInstance().Info("空闲");
}
break;
}
}
}
}
开始调用:
TelephonyManager m = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
MyPhoneState state = new MyPhoneState();
m.listen(state, PhoneStateListener.LISTEN_CALL_STATE);
大功告成;下面是不使用手机自带来电界面进行来电处理。