我试图在通话结束时检测用户何时接听电话,打电话给某人。有人可以解释我为什么在接到电话和打电话时有这么多的日志信息?
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==>
感谢。
答案 0 :(得分:0)
每当你试图收听一个新的PhoneStateListener时,你的广播接收器的onReceive()被调用了。你只需要做一次。
if (phoneStateListener == null) {
phoneStateListener = new ThePhoneStateListener(arg0);
}
检查电话状态监听器是否为空的条件然后初始化它。