如何用 Kotlin 在 Android 手机开发一个应用程序获取国家或地区信息

使用 Kotlin 开发 Android 应用获取国家/地区信息

获取设备国家/地区代码

通过 Locale 类可以直接获取设备当前设置的国家/地区代码:

kotlin 复制代码
val countryCode = Locale.getDefault().country

此方法返回 ISO 3166-1 标准的两位字母国家代码(如 "US" 表示美国)。

使用 TelephonyManager 获取 SIM 卡信息

对于需要获取 SIM 卡所属国家信息的情况:

kotlin 复制代码
val telephonyManager = getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
val simCountry = telephonyManager.simCountryIso?.toUpperCase()

注意:需要添加权限到 AndroidManifest.xml:

XML 复制代码
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
通过网络 IP 地址定位

可以使用第三方 API 获取基于 IP 的国家信息:

kotlin 复制代码
suspend fun getCountryByIP(): String? {
    val url = "https://ipapi.co/json/"
    return try {
        val response = withContext(Dispatchers.IO) {
            URL(url).readText()
        }
        val jsonObject = JSONObject(response)
        jsonObject.getString("country_name")
    } catch (e: Exception) {
        null
    }
}
使用 Android 位置服务

结合 LocationManager 获取地理位置信息:

kotlin 复制代码
val locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
val locations = locationManager.getProviders(true)
var country: String? = null

locations.forEach { provider ->
    val location = locationManager.getLastKnownLocation(provider)
    location?.let {
        val geocoder = Geocoder(this, Locale.getDefault())
        val addresses = geocoder.getFromLocation(it.latitude, it.longitude, 1)
        addresses?.firstOrNull()?.countryName?.let { name ->
            country = name
        }
    }
}

需要添加以下权限:

XML 复制代码
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
显示国家信息

将获取到的国家信息显示在 UI 上:

kotlin 复制代码
binding.countryTextView.text = when {
    !countryCode.isNullOrEmpty() -> "Device Country: $countryCode"
    !simCountry.isNullOrEmpty() -> "SIM Country: $simCountry"
    else -> "Country not detected"
}
处理运行时权限

对于需要权限的方法,需要检查并请求权限:

kotlin 复制代码
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) 
    != PackageManager.PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions(
        this,
        arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
        LOCATION_PERMISSION_REQUEST_CODE
    )
}
多方法组合策略

建议采用组合策略提高准确性:

  1. 优先尝试从 SIM 卡获取
  2. 回退到设备区域设置
  3. 最后尝试网络定位
  4. 可添加用户手动选择功能作为备用方案
相关推荐
用户20187928316717 小时前
ANR之RenderThread不可中断睡眠state=D
android
煤球王子17 小时前
简单学:Android14中的Bluetooth—PBAP下载
android
phoneixsky17 小时前
Kotlin的各种上下文Receiver,到底怎么个事
kotlin
小趴菜822717 小时前
安卓接入Max广告源
android
齊家治國平天下17 小时前
Android 14 系统 ANR (Application Not Responding) 深度分析与解决指南
android·anr
ZHANG13HAO17 小时前
Android 13.0 Framework 实现应用通知使用权默认开启的技术指南
android
heeheeai17 小时前
okhttp使用指南
okhttp·kotlin·教程
【ql君】qlexcel17 小时前
Android 安卓RIL介绍
android·安卓·ril
写点啥呢18 小时前
android12解决非CarProperty接口深色模式设置后开机无法保持
android·车机·aosp·深色模式·座舱
IT酷盖18 小时前
Android解决隐藏依赖冲突
android·前端·vue.js