給定一個電話號碼作爲字符串,如何找到存儲在聯繫人中的正確值?android找到正確的電話號碼
實施例:
給定電話號碼:在接觸9743343954
電話號碼:919743343954
編輯:數字的長度不是固定的。
謝謝。
給定一個電話號碼作爲字符串,如何找到存儲在聯繫人中的正確值?android找到正確的電話號碼
實施例:
給定電話號碼:在接觸9743343954
電話號碼:919743343954
編輯:數字的長度不是固定的。
謝謝。
我不知道我明白你的意思,但也許這將幫助你:
//Find contact by given number
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode("9743343954"));
String[] projection = new String[] { PhoneLookup.NUMBER, PhoneLookup.NORMALIZED_NUMBER };
Cursor c = getContentResolver().query(uri, projection, null, null, null);
if (c.moveToFirst()) {// while(c.moveToNext()){
//get number assigned by user to given contact, in this case 9743343954
String number = c.getString(c.getColumnIndexOrThrow(PhoneLookup.NUMBER));
//get normalized E164 number, in this case +919743343954
String normalized = c.getString(c.getColumnIndexOrThrow(PhoneLookup.NORMALIZED_NUMBER));
Toast.makeText(getApplicationContext(), "Number: " + number + "; normalized: " + normalized,
Toast.LENGTH_LONG).show();
}
c.close();
爲了使這個作品添加權限清單項目:
<uses-permission android:name="android.permission.READ_CONTACTS" />
以您的示例爲例,電話號碼長度爲10個字符,聯繫人爲13個,您希望最後10個匹配。所以,像這樣:
// I am assuming that you've removed all spaces, full stops,
// dashes etc from the two input variables
public boolean numbersMatch(String numberToMatch, String numberFromContacts) {
// Ensure that the both numbers are of a reasonable length
if (numberToMatch.length() < 9) return false;
if (numberFromContacts.length() < 9) return false;
// Is the number to match hidden in the contacts number
if (numberFromContacts.lastIndexOf(numberToMatch) != -1) return true;
// Or is the contact number hidden in the number to macth
if (numberToMatch.lastIndexOf(numberFromContacts) != -1) return true;
// No match, so return false
return false;
}
第一步是去除所有多餘的空格和多餘的字符:
//Removes the extra characters from the incoming number
private String removeExtraCharacters(String phoneNumber){
try
{
phoneNumber = phoneNumber.replace("(", "");
phoneNumber = phoneNumber.replace(")", "");
phoneNumber = phoneNumber.replace("-", "");
phoneNumber = phoneNumber.replace(" ", "");
phoneNumber = phoneNumber.replace("+", "");
}
catch (Exception e)
{
Log.e("Cal Reciever_R", e.toString());
}
return phoneNumber;
}
現在你可以使用的子方法得到的10位數字和ignorin的+91從前面如下:
phoneNumber =phoneNumber .substring(phoneNumber .length()-10);
你爲什麼不這樣做
假設手機麻木呃給出的是
String a = "9123456789";
而且一個觸點是
String b = "+91-9123456789";
然後,你可以很容易地檢查這種方式
if(b.contains(a))
{
//Do what you want!
}
如果我有一個數字「+ 91-9123456789」和一個短的本地「234567」?他們必須有所不同。 – Gaket 2018-02-07 01:47:37
從@Lecho答案似乎是好,如果你想獲得相關的接觸(或相關信息)。從Android的文檔此頁面上的更多信息http://developer.android.com/reference/android/provider/ContactsContract.PhoneLookup.html
據我所知,PhoneLookup.NORMALIZED_NUMBER是因爲API 16
另一方面可用,如果要比較兩個數字,看看他們是相同,但兩種不同的方式,你可以使用格式化:
PhoneNumberUtils.compare(phoneNumber1, phoneNumber2)
最佳,
如果你很高興與下面的答案之一,請千萬記得要接受它!它鼓勵人們提供答案:-) – 2013-03-02 16:46:45