Android 来电悬浮框的探索
基于项目中需要,监听系统来电弹出自定义的悬浮框,综合其他博主共享的资源,成功在项目中实现了这一功能。本着达则兼济天下的崇高理想,分享出来,以供参阅。开始之前推荐一篇关于悬浮框层级的博文:浮窗开发层级问题
根据需求我把整个功能分割了以下几个部分:
- 监听系统来电的广播
- 接收广播处理通话状态
- 悬浮框界面
- 接听功能实现
- 挂断功能实现
监听系统来电的广播
AndroidManifest.xml中注册监听系统来电的广播之前需要添加权限:
<uses-permission
android:name="android.permission.READ_PHONE_STATE">
</uses-permission>
注册广播:
<receiver android:name="com.softi.cs.ui.receiver.CSCallReceiver" >
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
<action android:name="android.intent.action.NEW_OUTGOING_CALL" />
<action android:name="call.cs.call.ending.action" />
</intent-filter>
</receiver>
接收广播处理通话状态
接收广播的类:CSCallReceiver .java
public class CSCallReceiver extends BroadcastReceiver {
private Context mContext;
private boolean incomingFlag=false;
private String incoming_number="";
private String TAG="CSCallReceiver";
private String phoneNumber;
@Override
public void onReceive(Context context, Intent intent) {
mContext = context;
TelephonyManager sTelephoneyManager = (TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE);
//如果是拨打电话
if(intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)){ //外呼不做处理
incomingFlag = false;
phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
Log.i(TAG, "call OUT:"+phoneNumber);
}else if(intent.getAction().equals("call.cs.call.ending.action")){
//处理挂断,在PhoneActivity接收广播 并延时4秒关闭界面,为了遮盖系统电话关闭页面
sendCloseBroadCast();
}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");
Intent myIntent =new Intent(context,PhoneActivity.class);
myIntent.putExtra("incoming_number", incoming_number);
myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(myIntent);
Log.i(TAG, "RINGING :"+ incoming_number);
break;
case TelephonyManager.CALL_STATE_OFFHOOK: