如何删除国家代码,当从联系人中选择电话号码

在这里输入图像描述

我对这一部分有怀疑。 当我从联系人列表中选择电话号码时如何删除国家/地区代码?

例如:+91 999999999而不是9999999999或+020 9696854549而不是9696854549任何人都可以知道我的问题的答案。 请解决这个问题

我在这里附上我的代码和图片。

private void contactPicked(Intent data) { Cursor cursor = null; try { String phoneNo = null ; // getData() method will have the Content Uri of the selected contact Uri uri = data.getData(); //Query the content uri cursor = getContentResolver().query(uri, null, null, null, null); cursor.moveToFirst(); // column index of the phone number int phoneIndex =cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER phoneNo = cursor.getString(phoneIndex); String phoneNumber = phoneNo.replaceAll(" ",""); mobile_et.setText(phoneNumber); } catch (Exception e) { e.printStackTrace(); } } 

使用这个函数希望它能帮助你:

 public String phoeNumberWithOutCountryCode(String phoneNumberWithCountryCode) { Pattern complie = Pattern.compile(" "); String[] phonenUmber = complie.split(phoneNumberWithCountryCode); Log.e("number is", phonenUmber[1]); return phonenUmber[1]; } 

它将适用于所有情况。 您不必关心国家代码的多少数字

 String get_Mo = phoneNumber.substring(phoneNumber.lastIndexOf(' ')+1)); 

你可以使用startsWith()

这个方法有两个变体,并测试一个字符串是以指定的前缀开始一个指定的索引开始还是默认开始。

 if(phoneNumber.startsWith("+")) { if(phoneNumber.length()==13) { String str_getMOBILE=phoneNumber.substring(3); mobile_et.setText(str_getMOBILE); } else if(phoneNumber.length()==14) { String str_getMOBILE=phoneNumber.substring(4); mobile_et.setText(str_getMOBILE); } } else { mobile_et.setText(phoneNumber); } 

我的英文很差,但我会尽我所能来回答你的问题。

首先,将这一行添加到您的build.gradle

 compile 'com.googlecode.libphonenumber:libphonenumber:8.7.0' 

下面是kotlin写的一个示例

 fun deleteCountry(phone: String) : String{ val phoneInstance = PhoneNumberUtil.getInstance() try { val phoneNumber = phoneInstance.parse(phone, null) return phoneNumber?.nationalNumber?.toString()?:phone }catch (_ : Exception) { } return phone } 

如果电话号码不是以“+”开头,然后是国家代码,那么您应该传递地区信息,例如:

val phoneNumber = phoneInstance.parse(phone,“CN”)

Interesting Posts