问题
On Android 9 the call:
String incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
Always return null
, how can I fix this under Android 9? It works for my old releases.
How can I get the incoming number of a call, these days?
回答1:
You need both READ_PHONE_STATE
and READ_CALL_LOG
permissions granted first, and then be ready for two broadcasts - one with no number as documented here:
If the receiving app has Manifest.permission.READ_CALL_LOG and Manifest.permission.READ_PHONE_STATE permission, it will receive the broadcast twice; one with the EXTRA_INCOMING_NUMBER populated with the phone number, and another with it blank.
回答2:
Also
public void onReceive(Context context, Intent intent) {
//We listen to two intents. The new outgoing call only tells us of an outgoing call. We use it to get the number.
if (intent.getAction().equals("android.intent.action.NEW_OUTGOING_CALL")) {
savedNumber = intent.getExtras().getString("android.intent.extra.PHONE_NUMBER");
}
else{
String stateStr = intent.getExtras().getString(TelephonyManager.EXTRA_STATE);
String number = intent.getExtras().getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
int state = 0;
if(stateStr.equals(TelephonyManager.EXTRA_STATE_IDLE)){
state = TelephonyManager.CALL_STATE_IDLE;
}
else if(stateStr.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)){
state = TelephonyManager.CALL_STATE_OFFHOOK;
}
else if(stateStr.equals(TelephonyManager.EXTRA_STATE_RINGING)){
state = TelephonyManager.CALL_STATE_RINGING;
}
if (number != null && !number.isEmpty() && !number.equals("null")) {
onCallStateChanged(context, state, number);
Log.d("TEST :","NUMBER =>"+number);
return;
}
}
}
MainActivity
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_CALL_LOG) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.SYSTEM_ALERT_WINDOW) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.READ_CALL_LOG, Manifest.permission.SYSTEM_ALERT_WINDOW},
1);
}
Manifest
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"/>
<uses-permission android:name="android.permission.READ_CALL_LOG"/>
来源:https://stackoverflow.com/questions/55634155/telephonymanager-extra-incoming-number-always-null-on-android-9