0

I've just built an application that detecting incoming calls. I see that in some phones(or in different version of android) incoming call number has country code, some incoming numbers has not. Is there a way to get incoming calls with country codes in any android phone and in any version of android?

I use broadcast receiver and PhoneStateListener, I get the parameter of incomingNumber at onCallStateChanged. So I didn't use telephonymanager.EXTRA_PHONE_NUMBER (In fact I don't what exactly EXTRA_PHONE_NUMBER does)

Kara
  • 6,115
  • 16
  • 50
  • 57
cergun
  • 29
  • 2
  • 5

3 Answers3

2

Here is a code-snippet that you can use in your BroadcastReceiver to extract the country-code using libphonenumber library.

@Override
public void onReceive(Context context, Intent intent) {
  if (intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)) {
    // get phone number from bundle
    String phoneNumber = intent.getExtras().getString(Intent.EXTRA_PHONE_NUMBER);

    // get country-code from the phoneNumber
    PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
    try {
       PhoneNumber numberProto = phoneUtil.parse(phoneNumber, Locale.getDefault().getCountry());
       if (phoneUtil.isValidNumber(numberProto)) {
          log.d("TAG", "Country Code: " + numberProto.getCountryCode());
       } else {
          log.d("TAG", "Invalid number format: " + phoneNumber);
       }
    } catch (NumberParseException e) {
       Log.d(TAG, "Unable to parse phoneNumber " + e.toString());
    }
  }
}
Nitin Jain
  • 86
  • 2
  • How to use : https://mvnrepository.com/artifact/com.googlecode.libphonenumber/libphonenumber/8.9.2 download JAR file and use in android – MilapTank Mar 24 '18 at 16:41
1

You can get this done with libphonenumber library https://code.google.com/p/libphonenumber/

flexdroid
  • 8,437
  • 2
  • 21
  • 27
0

EXTRA_PHONE_NUMBER holds number entered by user

A String holding the phone number originally entered in ACTION_NEW_OUTGOING_CALL, or the actual number to call in a ACTION_CALL.

via http://developer.android.com/reference/android/content/Intent.html#EXTRA_PHONE_NUMBER

Also, have you seen: How to get phone number from an incoming call? ?

Community
  • 1
  • 1
meeDamian
  • 1,143
  • 2
  • 11
  • 24