这是我请求用户权限的方式。
在AndroidManifest.xml中的应用程序标记外添加这些权限请求。
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
然后在App Gradle文件中添加Google的位置依赖项。
implementation 'com.google.android.gms:play-services-location:15.0.0'
现在声明一些全局变量。
private lateinit var mFusedLocationProvider:FusedLocationProviderClient
private lateinit var mLocationCallback: LocationCallback
private lateinit var mLocationRequest: LocationRequest
private var mLocationPermissionGranted:Boolean = false
在活动的OnCreate方法中(我无法正确格式化代码,对此深表歉意)
mFusedLocationProvider = LocationServices.getFusedLocationProviderClient(this)
//Location Callback
mLocationCallback = object: LocationCallback(){
override fun onLocationResult(p0: LocationResult?) {
if(p0==null){
//todo(request user to enable location from settings then remove return)
return
}else{
getDeviceLocation()
}
}
}
//Location Request
mLocationRequest = LocationRequest.create()
mLocationRequest.priority = LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY
//Set the Interval for Latest Interval Update
mLocationRequest.interval = 5000
//Set How Many Location Updated you Want
mLocationRequest.numUpdates = 1
getLocationPermission()
getDeviceLocation()
现在创建这两个函数。
private fun getLocationPermission() {
val permission:Array<String> = arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION,android.Manifest.permission.ACCESS_COARSE_LOCATION)
if(ContextCompat.checkSelfPermission(applicationContext,Constant.FINE_LOCATION)== PermissionChecker.PERMISSION_GRANTED){
if(ContextCompat.checkSelfPermission(applicationContext,Constant.COARSE_LOCATION)== PermissionChecker.PERMISSION_GRANTED){
mLocationPermissionGranted = true
}
}else{
ActivityCompat.requestPermissions(this,permission,Constant.LOCATION_REQUEST_CODE)
}
}
第二种方法
private fun getDeviceLocation() {
try{
if(mLocationPermissionGranted){
mFusedLocationProvider.lastLocation.addOnCompleteListener(this,{task: Task<Location> ->
if(task.isSuccessful){
var currentLocation: Location? = task.result
if(currentLocation!=null){
Log.i("Location","Latitude is ${currentLocation.latitude} and Longitude" +
"${currentLocation.longitude}")
}
else
mFusedLocationProvider.requestLocationUpdates(mLocationRequest,mLocationCallback,null)
}
})
}
}catch (e:SecurityException){
Log.e("Error", "Security Exception ${e.message}")
}
}
对于常量.kt
class Constant{
companion object {
//Location Request Settings
const val SET_INTERVAL:Long = 2000
const val NUM_UPDATES:Int = 1
//Location Permission
const val FINE_LOCATION:String = android.Manifest.permission.ACCESS_FINE_LOCATION
const val COARSE_LOCATION:String = android.Manifest.permission.ACCESS_COARSE_LOCATION
}
}