如何在 Android 中自动预置 select 国家代码

How to pre-select country code automatically in Android

这是我通过输入接收国家代码的代码(在 onCreate() 方法中):

        countryCodeEdt = (EditText)findViewById(R.id.register_country_code_tv);
        countryCodeEdt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String newCode = s.toString();

                System.out.println("this is new code value "+newCode);
                if (newCode == null || newCode.length() < 1){
                    pickupCountryTv.setText("Choose a country");
                }
                else {
                    if (countryMaps.containsKey(newCode)){
                        countryCode = newCode;
                        countryName = countryMaps.get(newCode);
                        pickupCountryTv.setText(countryName);
                    }
                    else{
                        countryCode = "";
                        countryName = "";
                        pickupCountryTv.setText("Wrong country code");
                    }
                }
            }
        });

现在我想自动预先select国家代码而不需要人工输入。我使用 TelephonyManager 找到了答案。但是我对如何设置我的 countryCodeEdt 变量以从此方法获取值感到困惑:

public static String getUserCountry(Context context) {
    try {
        final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        final String simCountry = tm.getSimCountryIso();
        if (simCountry != null && simCountry.length() == 2) { // SIM country code is available
            return simCountry.toLowerCase(Locale.US);
        }
        else if (tm.getPhoneType() != TelephonyManager.PHONE_TYPE_CDMA) { // device is not 3G (would be unreliable)
            String networkCountry = tm.getNetworkCountryIso();
            if (networkCountry != null && networkCountry.length() == 2) { // network country code is available
                return networkCountry.toLowerCase(Locale.US);
            }
        }
    }
    catch (Exception e) { }
    return null;
}

有人可以给我一些建议吗?提前致谢。

只需将 getUserCountry 方法放在您的 MainActivity 中,定义一个 String 变量,然后调用 -

String countryCode = getUserCountry(getApplicationContext());

现在您可以将它用于 TextView -

if (countryCode != null) {
   countryCodeEdt.setText(countryName);
} else {
//some error?
}

注意getUserCountry returns国家代码,而不是国家名称,即GB而不是Great英国.
您还应该处理 SIM 卡未出现在设备中的情况。