TelephonyManager.EXTRA_INCOMING_NUMBER 在 Android 9 上始终为空

TelephonyManager.EXTRA_INCOMING_NUMBER always null on Android 9

在 Android 9 通话:

String incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);

总是returnnull,我如何在Android9下解决这个问题?它适用于我的旧版本。 现在怎么查到来电号码?

您需要先授予 READ_PHONE_STATEREAD_CALL_LOG 权限,然后准备好进行两次广播 - 一次没有编号 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.

还有

 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; 
            }

        }
    }

主要活动

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);
}

清单

   <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"/>