Telefonare al prefisso locale degli Stati Uniti con Android

Mi piacerebbe sapere come posso ottenere il codice utente del dispositivo / utente dall’app per Android. So che esiste una libreria di nome TelephonyManager ma non sono riuscito a trovare la funzionalità del codice paese

Per farmi capire: ho un’attività che chiede all’utente di inserire il suo numero di telefono e voglio che il codice di zona venga preso dal dispositivo (dalla sua compagnia aerea?) Se aprissi la mia app a New York, otterrei +212 come il codice e una casella di testo per inserire il mio numero

1- Aggiungi questa matrice al file Strings.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-CopiaQuesta funzione Alla tua class

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

Funzione 3-Call GetCountryZipCode ()

4-scrivi Grazie, Wais.

Mi dispiace di rianimare un thread morto, ma ho passato un po ‘di tempo cercando di risolvere questo problema, quindi spero che la mia risposta aiuti qualcun altro.

L’esempio nella domanda originale è confuso, tu dici di voler aggiungere il codice del paese, ma fornisci il codice dell’area di New York 212 come esempio; Quello non è un codice di paese, è un prefisso locale. Il prefisso internazionale per USA è 1. Quindi il numero finale dovrebbe essere come “1-212-xxx-xxxx”. La mia risposta di seguito spiega come determinare il codice del paese, non il prefisso locale.

Per ottenere il prefisso telefonico nazionale per il tuo numero, usa getSimCountryIso (). Non utilizzare getNetworkCountryIso (); getNetworkCountryIso restituirà il Paese in cui ti trovi attualmente, ma se viaggi, restituirai il Paese sbagliato. Ad esempio se vieni dall’Albania ma viaggi a New York getSimCountryIso restituirà “al”, ma getNetworkCountryIso restituirà “noi”. Ovviamente se si utilizza il prefisso internazionale per gli Stati Uniti, si ha il numero sbagliato.

Ora hai un codice paese a due caratteri; per esempio il Canada sarà “ca”. È quindi ansible utilizzare questo come chiave di ricerca per la tabella seguente (ottenuta da http://www.sikosoft.com/item/international_telephone_country_codes_in_xml_format_using_iso_639-1 ).

Poiché i codici paese non cambiano mai, è accettabile codificare in modo rigido una tabella di ricerca nell’applicazione. Sfortunatamente non sembra essere un modo diretto per ottenere il codice paese attuale dell’utente.

 < ?xml version='1.0' encoding='UTF-8'?>  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

    Questa domanda mi ha aiutato molto, voglio darti tutti una class che fornisca il prefisso internazionale dal codice del telefono e viceversa.

    Uso:

    • CountryCodes.getCode(String country) restituisce il codice internazionale dal segno di paese
    • CountryCodes.getCountry(String code) restituisce i segni di paese dal codice internazionale

    Un’istanza di questa class può essere fornita come adattatore per le viste, ad esempio in 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 ); } } 

    Quello che segue è il codice di class

    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( String code ) to get matching country sign. * Call getCode( String 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 String[] m_Countries = { "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 String[] 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 string of matching phone code ("1", "39", "44", ...). null if none matches. */ public static String getCode( String 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 String getCode( int index ) { return m_Codes[index]; } /** * Get country signs from phone code. * More countries 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( String 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( String code, ArrayList matches ) { matches.clear(); for( int i=0; i 

    Lo sto usando e sembra funzionare ma, sai, solo la morte e le tasse sono certe. Sentiti libero di personalizzarlo e suggerire soluzioni.

    HTH

    Utilizza la dipendenza di compile 'com.googlecode.libphonenumber:libphonenumber:8.0.1' . Ciò semplifica l’attività e fornisce risultati accurati perché è su Google.

    Qui puoi saperne di più.

    L’output che sto ottenendo è qualcosa del genere:

    inserisci la descrizione dell'immagine qui

    Qui sto usando lo spinner.

    1) Ho creato un adattatore personalizzato CountryCodesAdapter:

     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 String regionCode; public int countryCode; public String regionName; @Override public int compareTo(String 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 String toString() { 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(String 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< ? super CountryCode> 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); StringBuilder text = new StringBuilder(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); StringBuilder text = new StringBuilder(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 String getRegionDisplayName(String regionCode, Locale language) { return (regionCode == null || regionCode.equals("ZZ") || regionCode.equals(PhoneNumberUtil.REGION_CODE_FOR_NON_GEO_ENTITY)) ? "" : new Locale("", regionCode).getDisplayCountry(language); } } 

    2) Ora il layout della mia attività in cui sto visualizzando lo spinner del codice del paese è:

     < ?xml version="1.0" encoding="utf-8"?>           

    3) il codice attività Java è di seguito:

     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, getSupportedCountries 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("getSupportedCountries") .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 (String 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(String.valueOf(myNum.getNationalNumber())); } else { final TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); final String 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 String regionCode = tm.getSimCountryIso().toUpperCase(Locale.US); return PhoneNumberUtil.getInstance().parse(tm.getLine1Number(), regionCode); } catch (Exception e) { return null; } } } 

    Poche caratteristiche extra:

    a) Il tuo paese verrà automaticamente selezionato nella casella di selezione.

    Per raggiungere ho usato questo:

      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(String.valueOf(myNum.getNationalNumber())); } else { final TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); final String regionCode = tm.getSimCountryIso().toUpperCase(Locale.US); CountryCode cc = new CountryCode(); cc.regionCode = regionCode; cc.countryCode = util.getCountryCodeForRegion(regionCode); mCountryCode.setSelection(ccList.getPositionForId(cc)); } 

    Penso che questo metodo sia leggermente migliore rispetto ad altri modi elencati qui. Così ho postato questo. Spero che qualcuno possa trovarlo utile 🙂

    Questo progetto su GitHub è qui

    in questo caso questo sarebbe simile a:

      /** * 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(); 

    Quindi nessuno deve guardare e ricontrollare (il contesto è una variabile locale di un object Contesto valido). Costanti.DEVICE_COUNTRY è di tipo String 🙂 (solo una variabile)

    aggiungi questi alla stringa.xml Divertiti 🙂

        +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 Austria 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  

    Se si utilizza comunque il libphonenumber di Google, e se si lavora con i numeri di telefono, è probabile che lo si faccia, è ansible utilizzare i dati interni che descrivono lo stesso. Non è pubblico, quindi devi usare la riflessione per raggiungerlo:

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

    Quindi puoi cercare o elaborare quella mappa per ottenere i dati che desideri.

    Lo so troppo tardi. Ma ho una soluzione pastella di esso. Dal momento che farlo con l’elenco di String e il suo looping potrebbe rallentarlo. Usando Hashmap sarebbe una soluzione di pastella per questo. Ho scritto una class PhoneUtil per questo. Ecco il codice (ho solo 20 paesi, ma è ansible aggiungerne altri)

     import android.content.Context; import android.telephony.TelephonyManager; import java.util.HashMap; /** * Created by Dell on 1/19/2017. */ public class PhoneUtil { public static String getCountryCode(Context context) { TelephonyManager manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); if (manager != null) { return getCountryCodeFromMap(manager.getSimCountryIso().toUpperCase()); } else { return null; } } private static String getCountryCodeFromMap(String 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); } } 

    In class TelephonyManager, I find a method public String getNetworkCountryIso () , this may be what you want. Also, there are some other method which can return more info about the phone. You may read http://en.wikipedia.org/wiki/List_of_mobile_country_codes to see which country is represented by a MCC.

    This is code to put in your Main Activity to replace the code that Wais posted near the top of this page. Take the array that Wais posted and add that to your app in the resources. I might have slightly changed the name of the array to be stored in resources, other than that, this code should work well and be easier to read if you are learning:

     public String getCountryCode() { String my_country_code_letters = getMyLocale().getCountry(); String[] country_codes = this.getResources().getStringArray(R.array.country_codes); String 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; }