Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธีเปลี่ยนรหัสประเทศ (Country Code) ใน Android (Geocoder)

ภาพรวม

บทความนี้สาธิตการใช้ Address.setCountryCode() เพื่อตั้งค่ารหัสประเทศ (ISO 3166-1 alpha-2) ในออบเจ็กต์ Address เช่น "TH", "US", "KR" เป็นการแก้ไขในหน่วยความจำเท่านั้น

โค้ดสำคัญ

Address address = addresses.get(0);
address.setCountryCode("KR"); // ตั้งค่ารหัสประเทศเป็นเกาหลีใต้
textView.setText("" + address.getCountryCode()); // แสดง "KR"

รหัสประเทศ ISO 3166-1 Alpha-2 ตัวอย่าง

ความแตกต่าง Country Name vs Country Code

รหัสประเทศรหัสประเทศ
THไทยUSสหรัฐอเมริกา
KRเกาหลีใต้JPญี่ปุ่น
CNจีนSGสิงคโปร์
GBสหราชอาณาจักรDEเยอรมนี
AUออสเตรเลียCAแคนาดา
เมธอดรูปแบบตัวอย่างใช้เมื่อไหร่
getCountryName()/setCountryName()ชื่อเต็ม"Thailand"แสดงให้ผู้ใช้เห็น
getCountryCode()/setCountryCode()ISO 2 ตัวอักษร"TH"API, Logic, Database

ข้อจำกัด (เหมือน setCountryName)

⚠️ In-Memory Only - ไม่เปลี่ยน System Locale, SIM Country, หรือ Carrier Settings

การได้ Country Code จริงของอุปกรณ์

// จาก SIM Card (ต้อง READ_PHONE_STATE)
TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
String simCountryIso = tm.getSimCountryIso(); // "th"
String networkCountryIso = tm.getNetworkCountryIso(); // "th"

// จาก Locale ปัจจุบัน
Locale current = getResources().getConfiguration().locale;
String countryCode = current.getCountry(); // "TH"

// จาก Geocoder (ตำแหน่งปัจจุบัน)
Address address = geocoder.getFromLocation(lat, lng, 1).get(0);
String countryCode = address.getCountryCode(); // "TH"

Manifest

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>