思路: 之前需求 是统计拨打电话离开页面和再次进入页面的时间差,开始考虑采用生命周期 onResume 和拨打电话 进行及时,可是测试 中结果发现 android 的权限弹框 和 拨打电话在不同的手机上 会提前多次调用系统 的 onResume 方法,最终考虑采用监听 系统的拨打电话的监听,监听 收到电话的状态和挂断的状态。
private boolean isCall;
private long firstCallTime;
private long callTime;
private TelephonyManager tm;
private MyPhoneListener myPhoneListener;
/*拨打电话的方法*/
private void callMobile(String phone){
tm = (TelephonyManager) getActivity().getSystemService(TELEPHONY_SERVICE);
myPhoneListener = new MyPhoneListener();
tm.listen(myPhoneListener, PhoneStateListener.LISTEN_CALL_STATE);
Intent intent = new Intent();//Intent.ACTION_CALL,Uri.parse(listphone.get(position))
intent.setAction(Intent.ACTION_CALL);//直接拨出电话
// intent.setAction(Intent.ACTION_DIAL);//只调用拨号界面,不拨出电话
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setData(Uri.parse("tel:" + phone));
// intent.setData(Uri.parse("tel:" + 10086));
startActivity(intent);
// isCall = true;
// firstCallTime = System.currentTimeMillis();
}
class MyPhoneListener extends PhoneStateListener {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
super.onCallStateChanged(state, incomingNumber);
switch (state) {
case TelephonyManager.CALL_STATE_IDLE://空闲
if (isCall) {
callTime = System.currentTimeMillis() - firstCallTime;
isCall = false;
costTime = (int) (callTime / 1000);
mPresenter.mark(id, costTime + "", "mobile", "", token);
if (tm != null&&myPhoneListener!=null) {
tm.listen(myPhoneListener, PhoneStateListener.LISTEN_NONE);
}
}
break;
case TelephonyManager.CALL_STATE_RINGING://响铃
break;
case TelephonyManager.CALL_STATE_OFFHOOK://通话状态
isCall = true;
firstCallTime = System.currentTimeMillis();
break;
default:
break;
}
}
}
@Override
public void onDestroy() {
super.onDestroy();
//取消电话监听
if (tm != null&&myPhoneListener!=null) {
tm.listen(myPhoneListener, PhoneStateListener.LISTEN_NONE);
}
}
网友评论