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

วิธีดึงชื่อประเทศปัจจุบันจาก Network Provider ใน Android

ภาพรวม

บทความนี้สาธิตการดึงชื่อประเทศ (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 LocationACCESS_COARSE_LOCATION + INTERNETระดับประเทศ/จังหวัดต้องการเน็ต, Rate limited
TelephonyManager.getNetworkCountryIso()READ_PHONE_STATEประเทศของเครือข่าย SIMทำงานออฟไลน์ได้, ไม่ต้อง GPS
TelephonyManager.getSimCountryIso()READ_PHONE_STATEประเทศที่ SIM ออกคงที่ ไม่เปลี่ยนตามตำแหน่ง
Locale.getDefault().getCountry()ไม่ต้อง Permissionตั้งค่าภาษา/ภูมิภาคของผู้ใช้ผู้ใช้ตั้งค่าเอง อาจไม่ตรงตำแหน่งจริง
FusedLocationProvider + GeocoderACCESS_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
    }
});