如果存在android,则将国家代码与手机号码分开

时间:2017-11-07 07:15:58

标签: android android-contentprovider android-contacts mobile-country-code

我有一个代码,使用内容解析器从移动联系人中获取电话号码。我在2个手机上测试了它。在一个中它取出国家代码而在另一个中它没有。有没有办法找出国家代码是出现在手机号码中,如果有,我想将其与号码分开。这是我的代码。请帮助我

ContentResolver cr = getContentResolver();
    Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
            null, null, null, null);

    if ((cur != null ? cur.getCount() : 0) > 0) {
        while (cur != null && cur.moveToNext()) {
            String id = cur.getString(
                    cur.getColumnIndex(ContactsContract.Contacts._ID));
            String name = cur.getString(cur.getColumnIndex(
                    ContactsContract.Contacts.DISPLAY_NAME));
            phoneContactName.add(name);

            if (cur.getInt(cur.getColumnIndex(
                    ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
                Cursor pCur = cr.query(
                        ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                        null,
                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
                        new String[]{id}, null);
                while (pCur.moveToNext()) {
                    String phoneNo = pCur.getString(pCur.getColumnIndex(
                            ContactsContract.CommonDataKinds.Phone.NUMBER));
                    String countryCode = pCur.getString(pCur.getColumnIndex(
                            ContactsContract.CommonDataKinds.Phone.NUMBER));
                    phoneContactNos.add(phoneNo);
                    dup_phoneContactNos.add(phoneNo);
                    /*if (registeredContactNos.contains(phoneNo)) {
                        Toast.makeText(getApplicationContext(), "match found", Toast.LENGTH_SHORT).show();
                        selectedContactName.add(name);
                        selectedContactNos.add(phoneNo);
                        populateList(name, phoneNo);


                    }*/
                    Log.i(TAG, "Name: " + name);
                    Log.i(TAG, "Phone Number: " + phoneNo);
                }


                pCur.close();
            }
        }
        /*for(int i=0;i<selectedContactName.size();i++)
        {
            Toast.makeText(getApplicationContext(),selectedContactName.get(i)+","+selectedContactNos.get(i),Toast.LENGTH_SHORT).show();
        }*/
    }
    if (cur != null) {
        cur.close();
    }

2 个答案:

答案 0 :(得分:1)

您可以使用Android&#39; PhoneNumberUtils.formatNumber

如果您只定位Lollipop及以上设备:

String formattedPhone = PhoneNumberUtils.formatNumber(phone, Locale.getDefault().getCountry()));

如果你也定位旧版本:

String formattedPhone;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    formattedPhone = PhoneNumberUtils.formatNumber(phone, Locale.getDefault().getCountry()));
} else {
    formattedPhone = PhoneNumberUtils.formatNumber(phone));
}

答案 1 :(得分:-1)

Getting telephone country code with Android 这个链接对我有用。我发布了所有那些寻找像我这样的答案的链接