ภาพรวม
บทความนี้สาธิตการดึงชื่อประเทศ (Country Name) จากตำแหน่งที่ตั้งผ่าน Network Provider ใช้ Geocoder แปลงพิกัดเป็นที่อยู่ แล้วดึง address.getCountryName()
โค้ดหลัก (สรุปจากบทความก่อนหน้า)
private void updateCountryName() {
try {
List addresses = geocoder.getFromLocation(
location.getLatitude(), location.getLongitude(), 1);
if (!addresses.isEmpty()) {
Address address = addresses.get(0);
String countryName = address.getCountryName(); // "Thailand"
textView.setText(countryName != null ? countryName : "Unknown");
}
} catch (IOException e) {
textView.setText("Error: " + e.getMessage());
}
}
Network Provider สำหรับ Country Detection
Network Provider (Wi-Fi/Cell Tower) ให้ตำแหน่งประมาณ 100-1000 เมตร เพียงพอสำหรับระบุประเทศส่วนใหญ่ ยกเว้นพื้นที่ชายแดน
วิธีอื่นในการได้ Country Code/Name
| วิธี | Permission | ความแม่นยำ | หมายเหตุ |
|---|---|---|---|
| Geocoder + Network Location | ACCESS_COARSE_LOCATION + INTERNET | ระดับประเทศ/จังหวัด | ต้องการเน็ต, Rate limited |
| TelephonyManager.getNetworkCountryIso() | READ_PHONE_STATE | ประเทศของเครือข่าย SIM | ทำงานออฟไลน์ได้, ไม่ต้อง GPS |
| TelephonyManager.getSimCountryIso() | READ_PHONE_STATE | ประเทศที่ SIM ออก | คงที่ ไม่เปลี่ยนตามตำแหน่ง |
| Locale.getDefault().getCountry() | ไม่ต้อง Permission | ตั้งค่าภาษา/ภูมิภาคของผู้ใช้ | ผู้ใช้ตั้งค่าเอง อาจไม่ตรงตำแหน่งจริง |
| FusedLocationProvider + Geocoder | ACCESS_FINE_LOCATION + INTERNET | แม่นยำที่สุด | แนะนำสำหรับแอปสมัยใหม่ |
TelephonyManager Approach (เร็วกว่า ไม่ต้องเน็ต)
TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
String networkCountry = tm.getNetworkCountryIso(); // "th" (lowercase)
String simCountry = tm.getSimCountryIso(); // "th"
// แปลงเป็นชื่อประเทศเต็ม
Locale locale = new Locale("", networkCountry);
String countryName = locale.getDisplayCountry(Locale.ENGLISH); // "Thailand"
String countryNameThai = locale.getDisplayCountry(new Locale("th")); // "ไทย"
ข้อควรระวัง Geocoder
- ต้องการ Backend Service (Google/OS) -> อาจไม่ทำงานบนอุปกรณ์บางเครื่อง (China ROM, Custom ROM)
- Rate Limit: ~1-2 requests/second
- ไม่ทำงานออฟไลน์
- Android 10+ ต้องขอ Permission ขณะรัน (Runtime)
แนะนำ: ใช้ FusedLocationProviderClient
// build.gradle
implementation 'com.google.android.gms:play-services-location:21.0.1'
// Code
FusedLocationProviderClient fused = LocationServices.getFusedLocationProviderClient(this);
fused.getLastLocation().addOnSuccessListener(location -> {
if (location != null) {
Geocoder geocoder = new Geocoder(this);
// ... get country name
}
});