Obtenir l’indicatif local US avec Android

Je voudrais savoir comment puis-je obtenir le code de zone périphérique / utilisateur à partir de mon application Android Je sais qu’il existe une librairie nommée TelephonyManager, mais je n’ai pas pu trouver la fonctionnalité de code de pays

Pour me rendre clair: j’ai une activité qui demande à l’utilisateur d’entrer son numéro de téléphone et je veux que le code de zone soit pris de l’appareil (de son opérateur?) Si j’ouvrais mon application à New York je recevrais +212 comme le code et une zone de texte pour entrer mon propre numéro

1- Ajouter ce tableau au fichier Ssortingngs.xml

 93,AF 355,AL 213,DZ 376,AD 244,AO 672,AQ 54,AR 374,AM 297,AW 61,AU 43,AT 994,AZ 973,BH 880,BD 375,BY 32,BE 501,BZ 229,BJ 975,BT 591,BO 387,BA 267,BW 55,BR 673,BN 359,BG 226,BF 95,MM 257,BI 855,KH 237,CM 1,CA 238,CV 236,CF 235,TD 56,CL 86,CN 61,CX 61,CC 57,CO 269,KM 242,CG 243,CD 682,CK 506,CR 385,HR 53,CU 357,CY 420,CZ 45,DK 253,DJ 670,TL 593,EC 20,EG 503,SV 240,GQ 291,ER 372,EE 251,ET 500,FK 298,FO 679,FJ 358,FI 33,FR 689,PF 241,GA 220,GM 995,GE 49,DE 233,GH 350,GI 30,GR 299,GL 502,GT 224,GN 245,GW 592,GY 509,HT 504,HN 852,HK 36,HU 91,IN 62,ID 98,IR 964,IQ 353,IE 44,IM 972,IL 39,IT 225,CI 81,JP 962,JO 7,KZ 254,KE 686,KI 965,KW 996,KG 856,LA 371,LV 961,LB 266,LS 231,LR 218,LY 423,LI 370,LT 352,LU 853,MO 389,MK 261,MG 265,MW 60,MY 960,MV 223,ML 356,MT 692,MH 222,MR 230,MU 262,YT 52,MX 691,FM 373,MD 377,MC 976,MN 382,ME 212,MA 258,MZ 264,NA 674,NR 977,NP 31,NL 599,AN 687,NC 64,NZ 505,NI 227,NE 234,NG 683,NU 850,KP 47,NO 968,OM 92,PK 680,PW 507,PA 675,PG 595,PY 51,PE 63,PH 870,PN 48,PL 351,PT 1,PR 974,QA 40,RO 7,RU 250,RW 590,BL 685,WS 378,SM 239,ST 966,SA 221,SN 381,RS 248,SC 232,SL 65,SG 421,SK 386,SI 677,SB 252,SO 27,ZA 82,KR 34,ES 94,LK 290,SH 508,PM 249,SD 597,SR 268,SZ 46,SE 41,CH 963,SY 886,TW 992,TJ 255,TZ 66,TH 228,TG 690,TK 676,TO 216,TN 90,TR 993,TM 688,TV 971,AE 256,UG 44,GB 380,UA 598,UY 1,US 998,UZ 678,VU 39,VA 58,VE 84,VN 681,WF 967,YE 260,ZM 263,ZW  

2-CopyThis Fonction à votre classe

 public Ssortingng GetCountryZipCode(){ Ssortingng CountryID=""; Ssortingng CountryZipCode=""; TelephonyManager manager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE); //getNetworkCountryIso CountryID= manager.getSimCountryIso().toUpperCase(); Ssortingng[] rl=this.getResources().getSsortingngArray(R.array.CountryCodes); for(int i=0;i 

Fonction 3 appels GetCountryZipCode ()

4-écrire Merci Wais.

Désolé de relancer un sujet mort, mais j’ai essayé de résoudre ce problème, alors j’espère que ma réponse aidera quelqu’un d’autre.

L’exemple de la question initiale porte à confusion, vous dites que vous voulez append le code du pays, mais donnez l’exemple de l’indicatif régional de New York 212; Ce n’est pas un code de pays, c’est un indicatif régional. Le code de pays pour les États-Unis est 1. Vous voulez donc que le numéro final ressemble à “1-212-xxx-xxxx”. Ma réponse ci-dessous explique comment déterminer le code du pays et non l’indicatif local.

Pour obtenir le code d’appel du pays pour votre propre numéro, utilisez getSimCountryIso (). N’utilisez pas getNetworkCountryIso (); getNetworkCountryIso retournera le pays dans lequel vous vous trouvez actuellement, mais si vous voyagez, le pays retournera dans le mauvais pays. Par exemple, si vous êtes d’Albanie mais que vous voyagez à New York, getSimCountryIso renverra “al”, mais getNetworkCountryIso renverra “nous”. Évidemment, si vous utilisez le code de pays pour les États-Unis, vous avez le mauvais numéro.

Vous avez maintenant un code de pays à deux caractères; Par exemple, le Canada sera “ca”. Vous pouvez ensuite l’utiliser comme clé de recherche pour le tableau ci-dessous (disponible à l’ adresse http://www.sikosoft.com/item/international_telephone_country_codes_in_xml_format_using_iso_639-1 ).

Comme les codes de pays ne changent jamais, il est acceptable de coder une table de consultation dans votre application. Malheureusement, il ne semble pas y avoir de moyen direct pour obtenir le code pays actuel de l’utilisateur.

   93 355 213 376 244 672 54 374 297 61 43 994 973 880 375 32 501 229 975 591 387 267 
55 673 359 226 95 257 855 237 1 238 236 235 56 86 61 61 57 269 242 243 682 506
385 53 357 420 45 253 670 593 20 503 240 291 372 251 500 298 679 358 33 689 241 220 995 49 233 350 30 299 502 224 245 592 509 504 852 36 91 62 98 964 353 44 972 39 225 81 962 7 254 686 965 996 856 371 961 266 231 218
  • 423
  • 370 352 853 389 261 265 60 960 223 356 692 222 230 262 52 691 373 377 976 382 212 258 264 674 977 31 599 687 64 505 227 234 683 850 47 968 92 680 507 675 595 51 63 870 48 351 1 974 40 7 250 590 685 378 239 966 221 381 248 232 65 421 386 677 252 27 82 34 94 290 508 249 597 268 46 41 963 886 992 255 66 228 690 676 216 90 993 688 971 256 44 380 598 1 998 678 39 58 84 681 967 260 263

    Cette question m’a beaucoup aidé, je veux vous donner un cours qui fournit le code du pays à partir du code de téléphone et vice versa.

    Usage:

    • CountryCodes.getCode(Ssortingng country) renvoie le code international du signe du pays
    • CountryCodes.getCountry(Ssortingng code) renvoie les signes de pays à partir du code international

    Une instance de cette classe peut être fournie en tant qu’adaptateur pour les vues, par exemple dans Activity onCreate:

     protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_layout); // your layout xml Spinner s = ( Spinner )findViewById( R.id.spinner1 ); // id of your spinner CountryCodes cc = new CountryCodes( this ); s.setAdapter( cc ); TelephonyManager man = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE); int index = CountryCodes.getIndex( man.getSimCountryIso() ); if( index > -1 ) { s.setSelection( index ); } } 

    Ce qui suit est le code de classe

    CountryCodes.java

     import java.util.ArrayList; import java.util.Locale; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; /** * Call getCountry( Ssortingng code ) to get matching country sign. * Call getCode( Ssortingng country ) to get matching phone code. * It has been extended from BaseAdapter in order to make it compatible with Spinner, * ListView and so on (just instance it and give it as adapter). * * This class is provided AS IS without any warranty. * * @author Niki Romagnoli * */ public class CountryCodes extends BaseAdapter{ private static final Ssortingng[] m_Counsortinges = { "AD", "AE", "AF", "AL", "AM", "AN", "AO", "AQ", "AR", "AT", "AU", "AW", "AZ", "BA", "BD", "BE", "BF", "BG", "BH", "BI", "BJ", "BL", "BN", "BO", "BR", "BT", "BW", "BY", "BZ", "CA", "CC", "CD", "CF", "CG", "CH", "CI", "CK", "CL", "CM", "CN", "CO", "CR", "CU", "CV", "CX", "CY", "CZ", "DE", "DJ", "DK", "DZ", "EC", "EE", "EG", "ER", "ES", "ET", "FI", "FJ", "FK", "FM", "FO", "FR", "GA", "GB", "GE", "GH", "GI", "GL", "GM", "GN", "GQ", "GR", "GT", "GW", "GY", "HK", "HN", "HR", "HT", "HU", "ID", "IE", "IL", "IM", "IN", "IQ", "IR", "IT", "JO", "JP", "KE", "KG", "KH", "KI", "KM", "KP", "KR", "KW", "KZ", "LA", "LB", "LI", "LK", "LR", "LS", "LT", "LU", "LV", "LY", "MA", "MC", "MD", "ME", "MG", "MH", "MK", "ML", "MM", "MN", "MO", "MR", "MT", "MU", "MV", "MW", "MX", "MY", "MZ", "NA", "NC", "NE", "NG", "NI", "NL", "NO", "NP", "NR", "NU", "NZ", "OM", "PA", "PE", "PF", "PG", "PH", "PK", "PL", "PM", "PN", "PR", "PT", "PW", "PY", "QA", "RO", "RS", "RU", "RW", "SA", "SB", "SC", "SD", "SE", "SG", "SH", "SI", "SK", "SL", "SM", "SN", "SO", "SR", "ST", "SV", "SY", "SZ", "TD", "TG", "TH", "TJ", "TK", "TL", "TM", "TN", "TO", "TR", "TV", "TW", "TZ", "UA", "UG", "US", "UY", "UZ", "VA", "VE", "VN", "VU", "WF", "WS", "YE", "YT", "ZA", "ZM", "ZW" }; private static final Ssortingng[] m_Codes = { "376", "971", "93", "355", "374", "599", "244", "672", "54", "43", "61", "297", "994", "387", "880", "32", "226", "359", "973", "257", "229", "590", "673", "591", "55", "975", "267", "375", "501", "1", "61", "243", "236", "242", "41", "225", "682", "56", "237", "86", "57", "506", "53", "238", "61", "357", "420", "49", "253", "45", "213", "593", "372", "20", "291", "34", "251", "358", "679", "500", "691", "298", "33", "241", "44", "995", "233", "350", "299", "220", "224", "240", "30", "502", "245", "592", "852", "504", "385", "509", "36", "62", "353", "972", "44", "91", "964", "98", "39", "962", "81", "254", "996", "855", "686", "269", "850", "82", "965", "7", "856", "961", "423", "94", "231", "266", "370", "352", "371", "218", "212", "377", "373", "382", "261", "692", "389", "223", "95", "976", "853", "222", "356", "230", "960", "265", "52", "60", "258", "264", "687", "227", "234", "505", "31", "47", "977", "674", "683", "64", "968", "507", "51", "689", "675", "63", "92", "48", "508", "870", "1", "351", "680", "595", "974", "40", "381", "7", "250", "966", "677", "248", "249", "46", "65", "290", "386", "421", "232", "378", "221", "252", "597", "239", "503", "963", "268", "235", "228", "66", "992", "690", "670", "993", "216", "676", "90", "688", "886", "255", "380", "256", "1", "598", "998", "39", "58", "84", "678", "681", "685", "967", "262", "27", "260", "263" }; private Context m_Context; public CountryCodes( Context cxt ) { super(); m_Context = cxt; } /** * Get phone code from country sign. * * @param country: two-chars country sign to fetch ("US", "IT", "GB", ...) * @return ssortingng of matching phone code ("1", "39", "44", ...). null if none matches. */ public static Ssortingng getCode( Ssortingng country ) { int index = getIndex( country ); return index == -1? null: getCode(index); } /** * Get international code at provided index. * * @param index: array index * @return international code */ public static Ssortingng getCode( int index ) { return m_Codes[index]; } /** * Get country signs from phone code. * More counsortinges may match the same code. * * @param code: phone code to fetch ("1", "39", "44", ...) * @return list of uppercase country signs (["US","PR","CA"], ["IT","VA"], ["GB","IM"], ...) * Empty list if none matches. */ public static ArrayList getCountry( Ssortingng code ) { ArrayList matches = new ArrayList(); getCountry(code, matches); return matches; } /** * Memory cheap version of country fetching: uses user provided list as output which outside * could be recycled on desire. * * @param code: country sign to fetch * @param matches: list to fill with matches, used as output */ public static void getCountry( Ssortingng code, ArrayList matches ) { matches.clear(); for( int i=0; i 

    Je l'utilise et semble fonctionner, mais vous savez, la mort et les impôts sont certains. N'hésitez pas à le personnaliser et à proposer des correctifs.

    HTH

    Utilisez comstack 'com.googlecode.libphonenumber:libphonenumber:8.0.1' dépendance comstack 'com.googlecode.libphonenumber:libphonenumber:8.0.1' . Cela facilite la tâche et fournit des résultats précis, car c’est par google.

    Ici vous pouvez en savoir plus à ce sujet.

    La sortie que j’obtiens est quelque chose comme ceci:

    entrer la description de l'image ici

    Ici, j’utilise spinner.

    1) J’ai créé un adaptateur CountryCodesAdapter personnalisé:

     package com.amitupadhyay.getcountrycode; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.CheckedTextView; import android.widget.TextView; import com.google.i18n.phonenumbers.PhoneNumberUtil; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Locale; /** * Created by aupadhyay on 1/24/17. */ public class CountryCodesAdapter extends BaseAdapter { private final LayoutInflater mInflater; private final List mData; private final int mViewId; private final int mDropdownViewId; private int mSelected; public static final class CountryCode implements Comparable { public Ssortingng regionCode; public int countryCode; public Ssortingng regionName; @Override public int compareTo(Ssortingng another) { return regionCode != null && another != null ? regionCode.compareTo(another) : 1; } @Override public boolean equals(Object o) { if (this == o) return true; if (o != null && o instanceof CountryCode) { CountryCode other = (CountryCode) o; return regionCode != null && regionCode.equals(other.regionCode); } return false; } @Override public Ssortingng toSsortingng() { return regionCode; } } public CountryCodesAdapter(Context context, int viewId, int dropdownViewId) { this(context, new ArrayList(), viewId, dropdownViewId); } public CountryCodesAdapter(Context context, List data, int viewId, int dropdownViewId) { mInflater = LayoutInflater.from(context); mData = data; mViewId = viewId; mDropdownViewId = dropdownViewId; } public void add(CountryCode entry) { mData.add(entry); } public void add(Ssortingng regionCode) { CountryCode cc = new CountryCode(); cc.regionCode = regionCode; cc.countryCode = PhoneNumberUtil.getInstance().getCountryCodeForRegion(regionCode); cc.regionName = getRegionDisplayName(regionCode, Locale.getDefault()); mData.add(cc); } public void clear() { mData.clear(); } public void sort(Comparator comparator) { Collections.sort(mData, comparator); } @Override public int getCount() { return mData.size(); } @Override public Object getItem(int position) { return mData.get(position); } @Override public long getItemId(int position) { CountryCode e = mData.get(position); return (e != null) ? e.countryCode : -1; } public int getPositionForId(CountryCode cc) { return cc != null ? mData.indexOf(cc) : -1; } public void setSelected(int position) { mSelected = position; } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { CheckedTextView textView; View view; if (convertView == null) { view = mInflater.inflate(mDropdownViewId, parent, false); textView = (CheckedTextView) view.findViewById(android.R.id.text1); view.setTag(textView); } else { view = convertView; textView = (CheckedTextView) view.getTag(); } CountryCode e = mData.get(position); SsortingngBuilder text = new SsortingngBuilder(5) .append(e.regionName) .append(" (+") .append(e.countryCode) .append(')'); textView.setText(text); textView.setChecked((mSelected == position)); return view; } @Override public View getView(int position, View convertView, ViewGroup parent) { TextView textView; View view; if (convertView == null) { view = mInflater.inflate(mViewId, parent, false); textView = (TextView) view.findViewById(android.R.id.text1); view.setTag(textView); } else { view = convertView; textView = (TextView) view.getTag(); } CountryCode e = mData.get(position); SsortingngBuilder text = new SsortingngBuilder(3) .append('+') .append(e.countryCode) .append(" (") .append(e.regionName) .append(')'); textView.setText(text); return view; } /** Returns the localized region name for the given region code. */ public Ssortingng getRegionDisplayName(Ssortingng regionCode, Locale language) { return (regionCode == null || regionCode.equals("ZZ") || regionCode.equals(PhoneNumberUtil.REGION_CODE_FOR_NON_GEO_ENTITY)) ? "" : new Locale("", regionCode).getDisplayCountry(language); } } 

    2) Maintenant, la disposition de mon activité où je montre le code du pays est:

                

    3) le code d’activité java est ci-dessous:

     package com.amitupadhyay.getcountrycode; import android.annotation.SuppressLint; import android.content.Context; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.telephony.TelephonyManager; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import com.amitupadhyay.getcountrycode.CountryCodesAdapter.CountryCode; import com.google.i18n.phonenumbers.PhoneNumberUtil; import com.google.i18n.phonenumbers.Phonenumber; import java.util.Comparator; import java.util.HashSet; import java.util.Locale; import java.util.Set; public class NumberValidation extends AppCompatActivity { private Spinner mCountryCode; private EditText mPhone; private Button mValidateButton; /** * Compatibility method for {@link PhoneNumberUtil#getSupportedRegions()}. * This was introduced because crappy Honeycomb has an old version of * libphonenumber, therefore Dalvik will insist on we using it. * In case getSupportedRegions doesn't exist, getSupportedCounsortinges will be * used. */ @SuppressWarnings("unchecked") private Set getSupportedRegions(PhoneNumberUtil util) { try { return (Set) util.getClass() .getMethod("getSupportedRegions") .invoke(util); } catch (NoSuchMethodException e) { try { return (Set) util.getClass() .getMethod("getSupportedCounsortinges") .invoke(util); } catch (Exception helpme) { // ignored } } catch (Exception e) { // ignored } return new HashSet<>(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.number_validation); //setupToolbar(false); mCountryCode = (Spinner) findViewById(R.id.phone_cc); mPhone = (EditText) findViewById(R.id.phone_number); mValidateButton = (Button) findViewById(R.id.button_validate); // populate country codes final CountryCodesAdapter ccList = new CountryCodesAdapter(this, android.R.layout.simple_list_item_1, android.R.layout.simple_spinner_dropdown_item); PhoneNumberUtil util = PhoneNumberUtil.getInstance(); Set ccSet = getSupportedRegions(util); for (Ssortingng cc : ccSet) ccList.add(cc); ccList.sort(new Comparator() { public int compare(CountryCodesAdapter.CountryCode lhs, CountryCodesAdapter.CountryCode rhs) { return lhs.regionName.compareTo(rhs.regionName); } }); mCountryCode.setAdapter(ccList); mCountryCode.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { public void onItemSelected(AdapterView parent, View view, int position, long id) { ccList.setSelected(position); } public void onNothingSelected(AdapterView parent) { // TODO Auto-generated method stub } }); // FIXME this doesn't consider creation because of configuration change Phonenumber.PhoneNumber myNum = getMyNumber(this); if (myNum != null) { CountryCode cc = new CountryCode(); cc.regionCode = util.getRegionCodeForNumber(myNum); if (cc.regionCode == null) cc.regionCode = util.getRegionCodeForCountryCode(myNum.getCountryCode()); mCountryCode.setSelection(ccList.getPositionForId(cc)); mPhone.setText(Ssortingng.valueOf(myNum.getNationalNumber())); } else { final TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); final Ssortingng regionCode = tm.getSimCountryIso().toUpperCase(Locale.US); CountryCode cc = new CountryCode(); cc.regionCode = regionCode; cc.countryCode = util.getCountryCodeForRegion(regionCode); mCountryCode.setSelection(ccList.getPositionForId(cc)); } } /** Returns the (parsed) number stored in this device SIM card. */ @SuppressLint("HardwareIds") public Phonenumber.PhoneNumber getMyNumber(Context context) { try { final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); final Ssortingng regionCode = tm.getSimCountryIso().toUpperCase(Locale.US); return PhoneNumberUtil.getInstance().parse(tm.getLine1Number(), regionCode); } catch (Exception e) { return null; } } } 

    Quelques fonctionnalités supplémentaires:

    a) Votre pays sera automatiquement sélectionné dans le spinner.

    Pour y parvenir j’ai utilisé ceci:

      Phonenumber.PhoneNumber myNum = getMyNumber(this); if (myNum != null) { CountryCode cc = new CountryCode(); cc.regionCode = util.getRegionCodeForNumber(myNum); if (cc.regionCode == null) cc.regionCode = util.getRegionCodeForCountryCode(myNum.getCountryCode()); mCountryCode.setSelection(ccList.getPositionForId(cc)); mPhone.setText(Ssortingng.valueOf(myNum.getNationalNumber())); } else { final TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); final Ssortingng regionCode = tm.getSimCountryIso().toUpperCase(Locale.US); CountryCode cc = new CountryCode(); cc.regionCode = regionCode; cc.countryCode = util.getCountryCodeForRegion(regionCode); mCountryCode.setSelection(ccList.getPositionForId(cc)); } 

    Je pense que cette méthode est un peu mieux que les autres moyens énumérés ici. Alors j’ai posté ça. J’espère que quelqu’un trouvera cela utile 🙂

    Ce projet sur GitHub est ici

    dans ce cas, cela ressemblerait à ceci:

      /** * network iso code: referred and listed at: * http://en.wikipedia.org/wiki/List_of_mobile_country_codes */ TelephonyManager manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); Constants.DEVICE_COUNTRY = manager.getNetworkCountryIso(); 

    Donc, personne n’a à regarder et à vérifier (le contexte est une variable locale d’un object de contexte valide). Constants.DEVICE_COUNTRY est de Type Ssortingng 🙂 (juste une variable)

    ajoutez-les à ssortingng.xml Enjoy 🙂

        +93   +355   +213   +1684   +376   +244   +1264   +672   +1268   +54   +374   +297   +61   +43   +994   +1242   +973   +880   +1246   +375   +32   +501   +229   +1441   +975   +591   +387   +267   +55   +246   +1284   +673   +359   +226   +257   +855   +237   +1   +238   +1345   +236   +235   +56   +86   +61   +61   +57   +269   +682   +506   +385   +53   +599   +357   +420   +243   +45   +253   +1767   +1809   +670   +593   +20   +503   +240   +291   +372   +251   +500   +298   +679   +358   +33   +689   +241   +220   +995   +49   +233   +350   +30   +299   +1473   +1671   +502   +441481   +224   +245   +592   +509   +504   +852   +36   +354   +91   +62   +98   +964   +53   +441624   +972   +39   +225   +1876   +81   +441534   +962   +7   +254   +686   +383   +965   +996   +856   +371   +961   +266   +231   +218   +423   +370   +352   +853   +389   +261   +265   +60   +960   +223   +356   +692   +222   +230   +262   +52   +691   +373   +377   +976   +382   +1664   +212   +258   +95   +264   +674   +977   +31   +599   +687   +64   +505   +227   +234   +683   +850   +1670   +47   +968   +92   +680   +970   +507   +675   +595   +51   +63   +64   +48   +351   +1787   +974   +242   +262   +40   +7   +250   +590   +290   +1869   +1758   +590   +508   +1784   +685   +378   +239   +966   +221   +381   +248   +232   +65   +1721   +421   +386   +677   +252   +27   +82   +211   +34   +94   +249   +597   +47   +268   +46   +41   +963   +886   +992   +255   +66   +228   +690   +676   +1868   +216   +90   +993   +1649   +688   +1340   +256   +380   +971   +44   +1   +598   +998   +678   +379   +58   +84   +681   +212   967   260   263    Code Afghanistan Albania Algeria American Samoa Andorra Angola Anguilla Antarctica Antigua and Barbuda Argentina Armenia Aruba Australia Aussortinga Azerbaijan Bahrain Bangladesh Barbados Belarus Belgium Belize Benin Bermuda Bhutan Bolivia Bosnia and Herzegovina Botswana Bouvet Island Brazil British Indian Ocean Territory British Virgin Islands Brunei Bulgaria Burkina Faso Burundi Cambodia Cameroon Canada Cape Verde Cayman Islands Central African Republic Chad Chile China Christmas Island Cocos (Keeling) Islands Colombia Comoros Congo Cook Islands Costa Rica Cote d\'Ivoire Croatia Cuba Cyprus Czech Republic Democratic Republic of the Congo Denmark Djibouti Dominica Dominican Republic East Timor Ecuador Egypt El Salvador Equatorial Guinea Eritrea Estonia Ethiopia Faeroe Islands Falkland Islands Fiji Finland Former Yugoslav Republic of Macedonia France French Guiana French Polynesia French Southern Territories Gabon Georgia Germany Ghana Gibraltar Greece Greenland Grenada Guadeloupe Guam Guatemala Guinea Guinea-Bissau Guyana Haiti Heard Island and McDonald Islands Honduras Hong Kong Hungary Iceland India Indonesia Iran Iraq Ireland Israel Italy Jamaica Japan Jordan Kazakhstan Kenya Kiribati Kuwait Kyrgyzstan Laos Latvia Lebanon Lesotho Liberia Libya Liechtenstein Lithuania Luxembourg Macau Madagascar Malawi Malaysia Maldives Mali Malta Marshall Islands Martinique Mauritania Mauritius Mayotte Mexico Micronesia Moldova Monaco Mongolia Montenegro Montserrat Morocco Mozambique Myanmar Namibia Nauru Nepal Netherlands Netherlands Antilles New Caledonia New Zealand Nicaragua Niger Nigeria Niue Norfolk Island North Korea Northern Marianas Norway Oman Pakistan Palau Panama Papua New Guinea Paraguay Peru Philippines Pitcairn Islands Poland Portugal Puerto Rico Qatar Reunion Romania Russia Rwanda Sqo Tome and Principe Saint Helena Saint Kitts and Nevis Saint Lucia Saint Pierre and Miquelon Saint Vincent and the Grenadines Samoa San Marino Saudi Arabia Senegal Serbia Seychelles Sierra Leone Singapore Slovakia Slovenia Solomon Islands Somalia South Africa South Georgia and the South Sandwich Islands South Korea South Sudan Spain Sri Lanka Sudan Suriname Svalbard and Jan Mayen Swaziland Sweden Switzerland Syria Taiwan Tajikistan Tanzania Thailand The Bahamas The Gambia Togo Tokelau Tonga Trinidad and Tobago Tunisia Turkey Turkmenistan Turks and Caicos Islands Tuvalu Virgin Islands Uganda Ukraine United Arab Emirates United Kingdom United States United States Minor Outlying Islands Uruguay Uzbekistan Vanuatu Vatican City Venezuela Vietnam Wallis and Futuna Western Sahara Yemen Yugoslavia Zambia Zimbabwe  

    Si vous utilisez de toute façon libphonenumber de Google et si vous travaillez avec des numéros de téléphone, il est fort probable que vous le fassiez, vous pouvez utiliser ses données internes qui les décrivent. Ce n’est pas public, il faut donc utiliser la reflection pour y parvenir:

     Map> CountryCodeToRegionCodeMap_getCountryCodeToRegionCodeMap() { try { Method method = CountryCodeToRegionCodeMap.class.getDeclaredMethod("getCountryCodeToRegionCodeMap"); method.setAccessible(true); return (Map>) method.invoke(null); } catch (Exception e) { Log.e(..., e.toSsortingng()); return null; } } 

    Ensuite, vous pouvez rechercher ou traiter cette carte pour obtenir les données souhaitées.

    Je le sais bien trop tard. Mais j’en ai une solution à pâte. Comme le faire avec la liste de Ssortingng et la parcourir en boucle pourrait le ralentir. L’utilisation de Hashmap serait une solution à ce problème. J’ai écrit un cours PhoneUtil pour cela. Voici le code (je n’ai qu’une vingtaine de pays mais vous pouvez en append)

     import android.content.Context; import android.telephony.TelephonyManager; import java.util.HashMap; /** * Created by Dell on 1/19/2017. */ public class PhoneUtil { public static Ssortingng getCountryCode(Context context) { TelephonyManager manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); if (manager != null) { return getCountryCodeFromMap(manager.getSimCountryIso().toUpperCase()); } else { return null; } } private static Ssortingng getCountryCodeFromMap(Ssortingng countryCode) { HashMap countryCodeMap = new HashMap<>(); countryCodeMap.put("TJ", "+992"); countryCodeMap.put("TZ", "+255"); countryCodeMap.put("TH", "+66"); countryCodeMap.put("TG", "+228"); countryCodeMap.put("TK", "+690"); countryCodeMap.put("TO", "+676"); countryCodeMap.put("TN", "+216"); countryCodeMap.put("TR", "+90"); countryCodeMap.put("TM", "+993"); countryCodeMap.put("TV", "+688"); countryCodeMap.put("AE", "+971"); countryCodeMap.put("UG", "+256"); countryCodeMap.put("GB", "+44"); countryCodeMap.put("UA", "+380"); countryCodeMap.put("UY", "+598"); countryCodeMap.put("US", "+1"); countryCodeMap.put("UZ", "+998"); countryCodeMap.put("VU", "+678"); countryCodeMap.put("VA", "+39"); countryCodeMap.put("VE", "+58"); countryCodeMap.put("VN", "+84"); countryCodeMap.put("WF", "+681"); countryCodeMap.put("YE", "+967"); countryCodeMap.put("ZM", "+260"); countryCodeMap.put("ZW", "+263"); countryCodeMap.put( "MY","+60"); countryCodeMap.put("PK","+92"); return countryCodeMap.get(countryCode); } } 

    Dans la classe TelephonyManager, je trouve une méthode public Ssortingng getNetworkCountryIso () , cela peut être ce que vous voulez. En outre, il existe une autre méthode qui peut renvoyer plus d’informations sur le téléphone. Vous pouvez lire http://en.wikipedia.org/wiki/List_of_mobile_country_codes pour voir quel pays est représenté par un MCC.

    Ceci est le code à mettre dans votre activité principale pour remplacer le code que Wais a posté en haut de cette page. Prenez le tableau que Wais a posté et ajoutez-le à votre application dans les ressources. J’ai peut-être légèrement changé le nom du tableau à stocker dans les ressources, à part cela, ce code devrait bien fonctionner et être plus facile à lire si vous apprenez:

     public Ssortingng getCountryCode() { Ssortingng my_country_code_letters = getMyLocale().getCountry(); Ssortingng[] country_codes = this.getResources().getSsortingngArray(R.array.country_codes); Ssortingng my_country_code_number = null; //------------------------------------------------------------------------------------------ for (int i=0; i < country_codes.length && i != (-1); i++) { /**split_code: * 1) split_code[0] == numbers * 2) split_code[1] == letters**/ String[] split_code = country_codes[i].split(","); //-------------------------------------------------------------------------------------- if (split_code[1].matches(my_country_code_letters)) { my_country_code_number = split_code[0]; break; } //-------------------------------------------------------------------------------------- } //------------------------------------------------------------------------------------------ return my_country_code_number; } public Locale getMyLocale() { Log.i(TAG, "Running getMyLocale()"); Locale myLocale = ""; //------------------------------------------------------------------------------------------ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { myLocale = getBaseContext().getResources().getConfiguration().getLocales().get(0); } else { //noinspection deprecation myLocale = getBaseContext().getResources().getConfiguration().locale; } //------------------------------------------------------------------------------------------ return myLocale; }