Question

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)

Was it helpful?

Solution

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

OTHER TIPS

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

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? ?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top