当前位置: 首页 > article >正文

Android 定位 获取当前位置 (Kotlin)

导入:

implementation 'com.google.android.gms:play-services-location:21.3.0'

头文件:

import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationCallback
import com.google.android.gms.location.LocationRequest
import com.google.android.gms.location.LocationResult
import com.google.android.gms.location.LocationServices
import com.google.android.gms.location.Priority
import com.google.android.gms.tasks.CancellationTokenSource
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.GoogleApiAvailability
import android.os.Looper
import androidx.core.app.ActivityCompat

代码实现:

private val PLAY_SERVICES_RESOLUTION_REQUEST = 9000
private var fusedLocationClient: FusedLocationProviderClient? = null

1.requestLocationUpdates:持续获取定位,根据更新间隔和最快频率

fusedLocationClient = LocationServices.getFusedLocationProviderClient(thisContext!!)
if (ActivityCompat.checkSelfPermission(
        thisContext!!,
        Manifest.permission.ACCESS_FINE_LOCATION
    ) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
        thisContext!!,
        Manifest.permission.ACCESS_COARSE_LOCATION
    ) == PackageManager.PERMISSION_GRANTED
) {
    val locationRequest: LocationRequest = LocationRequest.create()
    locationRequest.interval = 2000 // 更新间隔,例如10秒
    locationRequest.fastestInterval = 5000 // 最快频率,例如5秒
    locationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
    fusedLocationClient!!.requestLocationUpdates(
        locationRequest,
        object : LocationCallback() {
            override fun onLocationResult(locationResult: LocationResult) {
                if (locationResult == null) {
                    LogUtils.d("requestLocationUpdates locationResult == null")
                    return
                }
                for (location in locationResult.locations) {
                    var latitude = location.latitude.toString()
                    var longitude = location.longitude.toString()
                    if (latitude.contains(".")) {
                        latitude = subString(latitude)
                    }
                    if (longitude.contains(".")) {
                        longitude = subString(longitude)
                    }
                    LogUtils.d("requestLocationUpdates onLocationResult latitude = $latitude  longitude = $longitude")
                }
            }
        },
        Looper.myLooper()
    )
}

2.getCurrentLocation:获取一次定位

private fun startLocation() {
    fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
    if (ActivityCompat.checkSelfPermission(
            this,
            Manifest.permission.ACCESS_FINE_LOCATION
        ) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
            this,
            Manifest.permission.ACCESS_COARSE_LOCATION
        ) == PackageManager.PERMISSION_GRANTED
    ) {
        LogUtils.d("fusedLocationClient Ok")
        val priority = Priority.PRIORITY_BALANCED_POWER_ACCURACY
        val cancellationTokenSource = CancellationTokenSource()
        val cancellationToken = cancellationTokenSource.token
        fusedLocationClient.getCurrentLocation(
            priority,
            cancellationToken
        )
            .addOnSuccessListener(
                this
            ) { location ->
                if (location != null) {
                    val latitude = location.latitude
                    val longitude = location.longitude
                    LogUtils.d("fusedLocationClient latitude = $latitude  longitude = $longitude")
                } else {
                    LogUtils.d("fusedLocationClient location = null")
                }
            }
            .addOnFailureListener { exception ->
                LogUtils.d("fusedLocationClient exception = $exception")

            }
    }
}
//上面方法中 addOnFailureListener 报错如下:
//com.google.android.gms.common.api.ApiException: 17: API: LocationServices.API is not available on this device. Connection failed with: ConnectionResult{statusCode=SERVICE_INVALID, resolution=null, message=null}
//如发生这个错误,可能是当前手机设备没有安装Google Play 服务,可以用如下两个方法检查当前设备是否安装Google Play 服务,再调用获取上面定位方法
private fun checkPlayServices(): Boolean {
    val apiAvailability = GoogleApiAvailability.getInstance()
    val resultCode = apiAvailability.isGooglePlayServicesAvailable(this)
    if (resultCode != ConnectionResult.SUCCESS) {
        if (apiAvailability.isUserResolvableError(resultCode)) {
            LogUtils.d("GoogleApiAvailability NO")
            apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST)
                ?.show()
        } else {
            LogUtils.d("GoogleApiAvailability Google Play")
            finish()
        }
        return false
    }
    return true
}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    if (requestCode == PLAY_SERVICES_RESOLUTION_REQUEST) {
        if (resultCode == Activity.RESULT_OK) {
            if (checkPlayServices()) {
                startLocation()
            }
        } else {
            LogUtils.d("无法使用 Google Play 服务")
            finish()
        }
    }
}

http://www.kler.cn/a/518853.html

相关文章:

  • vite环境变量处理
  • 【数据结构】_以SLTPushBack(尾插)为例理解单链表的二级指针传参
  • arm-linux平台、rk3288 SDL移植
  • 基于 Node.js 的天气查询系统实现(附源码)
  • 全面评测 DOCA 开发环境下的 DPU:性能表现、机器学习与金融高频交易下的计算能力分析
  • 编码器和扩散模型
  • 企业信息化4:集团化企业的财务管理系统
  • 2025牛客寒假算法基础集训营1
  • C++异步future
  • hexo + Butterfly搭建博客
  • 【Django DRF Apps】从零搭建一个导出 Excel 和 PDF的app应用
  • 电力场效应晶体管(电力 MOSFET),全控型器件
  • 【ComfyUI专栏】ComfyUI 部署Kolors
  • 【实践】Python使用Pandas处理气象数据
  • 【数据分享】1929-2024年全球站点的逐日平均能见度(Shp\Excel\免费获取)
  • github配置SSH公钥后需要输入密码
  • VUE3 如何快速使用pinia
  • nacos(基于docker最详细安装)
  • 工业相机 SDK 二次开发-Sherlock插件
  • Spring Boot是什么及其优点
  • SpringBoot引入第三方jar包
  • redis实现lamp架构缓存
  • 将Deepseek接入本地Vscode
  • 对于Docker的初步了解
  • 夸父计步器0.02
  • 记一次Linux共享内存段排除Bug:key值为0x0000000的共享内存段删除不了