0

I use a class that extends BroadcastReceiver. how can I get the phone number during an incoming or outgoing call?

This is my department:

public class MyCallReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context , Intent intent) {
     
        if (intent.getStringExtra( TelephonyManager.EXTRA_STATE ).equals( TelephonyManager.EXTRA_STATE_OFFHOOK )) {
          //Call started

        } else if (intent.getStringExtra( TelephonyManager.EXTRA_STATE ).equals( TelephonyManager.EXTRA_STATE_IDLE )) {
           //Call ended

        } else if (intent.getStringExtra( TelephonyManager.EXTRA_STATE ).equals( TelephonyManager.EXTRA_STATE_RINGING )) {
             //Incoming call
            }
    } }
dotcom
  • 17
  • 4

1 Answers1

1

you can get it this way.

public class CallRecevier extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        try {
            TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            telephony.listen(new PhoneStateListener() {
                @Override
                public void onCallStateChanged(int state, String phoneNumber) {
                    super.onCallStateChanged(state, phoneNumber);
                    if (state == 1 || state == 2) {
                        if (phoneNumber != null && !phoneNumber.equals("")) {
                           Tİmber.e("Call Number: %s",phoneNumber);
                        }
                    }
                }
            }, PhoneStateListener.LISTEN_CALL_STATE);
        } catch (Exception e) {
            Timber.e("Error: %s", e.getLocalizedMessage());
        }
    }
}
BroscR
  • 167
  • 2
  • 11
  • And, along with this, don’t forget to add 1. Below permission
 2. And below intent-filter within your BroadcastReceiver declaration in manifest.xml
 – Akki Oct 17 '21 at 18:35
  • phone state listener is now deprecated. what is other solution – Dhananjay Gavali Jul 26 '22 at 12:24
  • this android 12 version solution..[Solution](https://stackoverflow.com/questions/69571012/telephonymanager-deprecated-listen-call-state-ringing-on-android-12) – BroscR Jul 26 '22 at 17:34