如何在Android中自动预选国家/地区代码

时间:2015-08-30 15:01:47

标签: android telephonymanager

这是我的代码,按输入(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");
                    }
                }
            }
        });

现在我想在没有人输入的情况下自动预先选择国家/地区代码。我使用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;
}

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

1 个答案:

答案 0 :(得分:1)

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

String countryCode = getUserCountry(getApplicationContext());

现在您可以将它用于TextView -

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

请注意getUserCountry返回国家/地区代码,而不是国家/地区的名称,即GB,而不是英国。
您还应该处理SIM卡未出现在设备内的情况。