这是一个代码片段,您可以在 BroadcastReceiver 中使用它来使用libphonenumber库提取国家/地区代码。
@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());
}
}
}