当API低于21时,我的应用程序无法读取传入的号码。如何才能使其正常工作?我试过这种方法:http://mmarvick.github.io/blog/blog/lollipop-multiple-broadcastreceiver-call-state/但不起作用
代码:
public class PhoneStateBroadcastReceiver extends BroadcastReceiver {
private static final String TAG = "PhoneStateBroadcast";
Context mContext;
String incoming_nr;
private static int prev_state;
static CustomPhoneStateListener customPhoneListener;
@Override
public void onReceive(Context context, Intent intent) {
TelephonyManager telephony = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE); //TelephonyManager object
if(customPhoneListener == null){
customPhoneListener = new CustomPhoneStateListener();
telephony.listen(customPhoneListener, PhoneStateListener.LISTEN_CALL_STATE);
}
Bundle bundle = intent.getExtras();
String phoneNr = bundle.getString("incoming_number");
incoming_nr = phoneNr;
Log.v(TAG, "phoneNr: " + phoneNr);
mContext = context;
}
public class CustomPhoneStateListener extends PhoneStateListener {
private static final String TAG = "CustomPhoneStateListnr";
@Override
public void onCallStateChanged(int state, String incomingNumber){
if(incomingNumber != null && incomingNumber.length() > 0){
incoming_nr = incomingNumber;
}
//if(prev_state == state) return;
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==>"+incoming_nr);
if(prev_state == TelephonyManager.CALL_STATE_OFFHOOK){
Intent i = new Intent(mContext, PostCallPromptActivity.class);
i.putExtra(Constants.EXTRA_CALL_LOG_NUMBER, incomingNumber);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(i);
prev_state = state;
//Answered Call which is ended
}
if((prev_state == TelephonyManager.CALL_STATE_RINGING)){
prev_state = state;
//Rejected or Missed call
}
break;
}
}
}
}