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)
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());
}
}
}
您可以使用libphonenumber库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? ?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.