这是我的代码,按输入(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;
}
有人可以给我一些建议吗?提前谢谢。
答案 0 :(得分:1)
只需将getUserCountry
方法放在MainActivity
上,定义一个String
变量,然后调用 -
String countryCode = getUserCountry(getApplicationContext());
现在您可以将它用于TextView
-
if (countryCode != null) {
countryCodeEdt.setText(countryName);
} else {
//some error?
}
请注意getUserCountry
返回国家/地区代码,而不是国家/地区的名称,即GB,而不是英国。
您还应该处理SIM卡未出现在设备内的情况。