在Android Kotlin中,即使在手机设置中授予了定位权限,但定位服务仍未启用。解决方法是在代码中检查并要求用户启用定位服务。
在代码中检查定位服务是否启用如下所示:
val locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { //定位服务未启用 }
要求用户启用定位服务的方法如下所示:
val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS) startActivity(intent)
注意:在使用该代码之前应先检查定位权限是否授予。