Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the caller ID in Android 9

I have been using the following code in a BroadcastReceiver to get the caller ID of incoming calls:

@Override
public void onReceive(Context aContext, Intent aIntent) {
   String action = aIntent.getAction();

   if (action==null) return;
   if (!action.equals("android.intent.action.PHONE_STATE")) return;

   String curState = aIntent.getStringExtra(TelephonyManager.EXTRA_STATE);

   if ((TelephonyManager.EXTRA_STATE_RINGING.equals(curState))
      &&(TelephonyManager.EXTRA_STATE_IDLE.equals(oldState)))){
      String incNumber = aIntent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);

      // do something here
   }
   oldState=curState;
}

Unfortunately this has stopped working in Android 9.0 (API 28). More specifically, aIntent.getStringExtra(EXTRA_INCOMING_NUMBER) always returns null. In android versions<=API 27 everything works correctly

I have also added the READ_PHONE_STATE and READ_CALL_LOG permissions in the manifest file.

Any ideas? Anybody else experiencing the same problem?

Thanks in advance for your help.

like image 899
haris Avatar asked Aug 24 '18 18:08

haris


People also ask

Why is Caller ID not working on my Android?

To check if caller ID is turned on: In your phone dialer settings, turn on or display your Caller ID setting. Visit the Devices page, select your device, and look for steps to display Caller ID.

Why does my Phone not show who is calling?

Enable Call Notification To enable the notification again, follow these steps: 1] Open Settings and go to Apps & notifications. 2] Here look for the default Phone app, tap on it. 3] After that tap on Notifications and see if the “Show notifications” toggle is on.


2 Answers

I found the answer to my question:

First, in Android 9, you have to explicitly ask for both the READ_PHONE_STATE and the READ_CALL_LOG permissions at run time. In previous Android versions you only had to ask for the READ_PHONE_STATE permission. Both of them have to be asked at run time.

Second, if both of the above permissions have been given, the onReceive method is called twice (!!). The first time the intent is "empty" (EXTRA_INCOMING_NUMBER is null). The second time the intent is normally populated as it should. This is documented in the TelephonyManager Documentation.

like image 179
haris Avatar answered Oct 12 '22 19:10

haris


Add READ_CALL_LOG permission in manifest as below :

<uses-permission android:name="android.permission.READ_CALL_LOG" />

Then

Apps -> Your App -> Permissions -> Grant Call Logs Permission

Your should get phone number now, after the second time your receiver is called

like image 27
Obakeng Balatseng Avatar answered Oct 12 '22 17:10

Obakeng Balatseng