1:AndroidManifest.xml 注册广播
<!--打电话广播-->
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"/>
<!--监听电话状态-->
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<receiver android:name=".service.PhoneBroadcastReceiver">
<intent-filter android:priority="1000">
//主动打电话时,发送的广播
<action android:name="android.intent.action.NEW_OUTGOING_CALL"/>
//电话状态改变时,发送的广播 (振铃,挂断,接通)
<action android:name="android.intent.action.PHONE_STATE"/>
</intent-filter>
</receiver>
2:onReceive
@Override
public void onReceive(Context context, Intent intent) {
log.info("收到电话广播:{}", intent == null ? "null" : intent.getAction());
// 如果是拨打电话
if (intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)) {
//拨打电话会优先,收到此广播. 再收到 android.intent.action.PHONE_STATE 的 TelephonyManager.CALL_STATE_OFFHOOK 状态广播;
String phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
log.info("call OUT:{}", phoneNumber);//获取拨打的手机号码
} else {
// 如果是来电
TelephonyManager tManager = (TelephonyManager) context
.getSystemService(Service.TELEPHONY_SERVICE);
//电话的状态
switch (tManager.getCallState()) {
case TelephonyManager.CALL_STATE_RINGING:
//等待接听状态
mIncomingNumber = intent.getStringExtra("incoming_number");
log.info("RINGING :" + mIncomingNumber);
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
//接听状态
break;
case TelephonyManager.CALL_STATE_IDLE:
//挂断状态
break;
}
}
}
3:附加阅读
如果需要挂断电话参考: (可以模拟耳机线上的接听和挂断广播, 实现相应的功能.)
http://gqdy365.iteye.com/blog/2173057
http://bbs.51cto.com/thread-1078059-1.html
http://blog.csdn.net/sodino/article/details/6181610
网友评论