我正在尝试检测用户何时接收呼叫,何时呼叫某人,何时呼叫结束。有人能解释一下为什么我在接到电话和呼叫时会有这么多日志消息吗?
我在Android Manifest中的接收器
<receiver android:name="com.prjct3.amadey.myapplication3.MyReceiver">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE"/>
</intent-filter>
</receiver>这是我的代码。
public class MyReceiver extends BroadcastReceiver {
PhoneStateListener listener;
String incoming_nr;
private int prev_state;
String TAG="Point_1";
@Override
public void onReceive(final Context context, Intent intent) {
Log.i("Point","onReceive");
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
listener=new PhoneStateListener(){
@Override
public void onCallStateChanged(int state, String incomingNumber) {
// TODO Auto-generated method stub
super.onCallStateChanged(state, incomingNumber);
switch(state){
case TelephonyManager.CALL_STATE_RINGING:
Log.d(TAG, "CALL_STATE_RINGING");
prev_state=state;
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
Log.d(TAG, "CALL_STATE_OFFHOOK");
prev_state=state;
break;
case TelephonyManager.CALL_STATE_IDLE:
Log.d(TAG, "CALL_STATE_IDLE==>"+incomingNumber);
if((prev_state==TelephonyManager.CALL_STATE_OFFHOOK)){
prev_state=state;
//Answered Call which is ended
}
if((prev_state==TelephonyManager.CALL_STATE_RINGING)){
prev_state=state;
//Rejected or Missed call
}
break;
}
}
};
tm.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
}
}还有我的LogCat
06-19 11:13:26.580 7519-7519/? D/Point_1﹕ CALL_STATE_IDLE==>null
06-19 11:13:26.705 7519-7519/? D/Point_1﹕ CALL_STATE_IDLE==>null
06-19 11:13:26.706 7519-7519/? D/Point_1﹕ CALL_STATE_IDLE==>null
06-19 11:19:05.669 7704-7704/? D/Point_1﹕ CALL_STATE_RINGING
06-19 11:19:05.669 7704-7704/? D/Point_1﹕ CALL_STATE_IDLE==>
06-19 11:19:08.471 7704-7704/? D/Point_1﹕ CALL_STATE_IDLE==>+76398291345
06-19 11:19:08.523 7704-7704/? D/Point_1﹕ CALL_STATE_IDLE==>+76398291345
06-19 11:19:08.524 7704-7704/? D/Point_1﹕ CALL_STATE_IDLE==>
06-19 11:19:32.053 7704-7704/? D/Point_1﹕ CALL_STATE_OFFHOOK
06-19 11:19:32.053 7704-7704/? D/Point_1﹕ CALL_STATE_OFFHOOK
06-19 11:19:32.076 7704-7704/? D/Point_1﹕ CALL_STATE_OFFHOOK
06-19 11:19:32.076 7704-7704/? D/Point_1﹕ CALL_STATE_IDLE==>
06-19 11:19:39.248 7704-7704/? D/Point_1﹕ CALL_STATE_IDLE==>
06-19 11:19:39.271 7704-7704/? D/Point_1﹕ CALL_STATE_IDLE==>
06-19 11:19:39.288 7704-7704/? D/Point_1﹕ CALL_STATE_IDLE==>
06-19 11:19:39.333 7704-7704/? D/Point_1﹕ CALL_STATE_IDLE==>
06-19 11:19:39.333 7704-7704/? D/Point_1﹕ CALL_STATE_IDLE==>谢谢。
发布于 2016-06-19 15:45:09
当您的广播接收器的onReceive()被调用时,每次您尝试收听一个新的PhoneStateListener.You时,只需要执行一次。
if (phoneStateListener == null) {
phoneStateListener = new ThePhoneStateListener(arg0);
}检查电话状态监听器是否为空,然后进行初始化。
https://stackoverflow.com/questions/37904853
复制相似问题