androidbroadcastreceivertelephonymanager

Get incoming call number programmatically on android


I am trying to get incoming call info using broadcast receivers on android studio. following are the methods i tried:

<receiver android:name=".receivers.IncomingCalls">
            <intent-filter>
                <action android:name="android.intent.action.PHONE_STATE" />
            </intent-filter>
        </receiver>

On this receiver's intent i tried:

Method one:

incnumber=intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);

Method two:

final String state1 = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
        telephony.listen(new PhoneStateListener(){
            @Override
            public void onCallStateChanged(int state, final String incomingNumber) {
                super.onCallStateChanged(state, incomingNumber);
                incnumber=incomingNumber;
            }
        },PhoneStateListener.LISTEN_CALL_STATE);

Method Three:

incnumber=intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);

All the three methods return empty incnumber.

By the way, I am running this project on android pie, Please help me out.


Solution

  • Try this way... permission

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

    Make a Broadcast receiver say ServiceReceiver assign its action in Manifest.

    <receiver android:name=".ServiceReceiver" >
    <intent-filter>
        <action android:name="android.intent.action.PHONE_STATE" />
    </intent-filter>
    

    ServiceReceiver.Java

    public class ServiceReceiver extends BroadcastReceiver {
    
    @Override
    public void onReceive(final Context context, Intent intent) {
        TelephonyManager telephony = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
        telephony.listen(new PhoneStateListener(){
            @Override
            public void onCallStateChanged(int state, String incomingNumber) {
                super.onCallStateChanged(state, incomingNumber);
                System.out.println("incomingNumber : "+incomingNumber);
            }
        },PhoneStateListener.LISTEN_CALL_STATE);
    }
    

    }