android - 获取位置 android Kotlin

标签 android location kotlin

我最近添加了获取位置功能。当我尝试显示经度和纬度时,它返回零。

这是我的 LocationListener 类:

inner class MylocationListener: LocationListener {
    constructor():super(){
        mylocation= Location("me")
        mylocation!!.longitude
        mylocation!!.latitude
    }

    override fun onLocationChanged(location: Location?) {
        mylocation=location
    }

    override fun onStatusChanged(p0: String?, p1: Int, p2: Bundle?) {}

    override fun onProviderEnabled(p0: String?) {}

    override fun onProviderDisabled(p0: String?) {}
}

这是我的 GetUserLocation 函数:

fun GetUserLocation(){
    var mylocation= MylocationListener()
    var locationManager=getSystemService(Context.LOCATION_SERVICE) as LocationManager
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0.1f,mylocation)
}

这是我返回经度和纬度的函数:

fun getLoction (view: View){
    prgDialog!!.show();

    GetUserLocation()

    button.setTextColor(getResources().getColor(R.color.green));
    textView.text = mylocation!!.latitude.toFloat().toString()
    Toast.makeText(this, mylocation!!.latitude.toFloat().toString(), Toast.LENGTH_LONG).show()
    Toast.makeText(this, mylocation!!.longitude.toFloat().toString(), Toast.LENGTH_LONG).show()

    prgDialog!!.hide()
} 

最佳答案

2019 年 Kotlin 最佳官方解决方案

Google API 客户端/FusedLocationApi 已被弃用,位置管理器根本没有用处。 因此 Google 更喜欢使用 Google Play 服务位置 API 的 Fused Location Provider "FusedLocationProviderClient" 用于获取位置及其更好的省电和准确性方法

这里是kotlin中的示例代码,用于获取最后一个已知位置/一次性位置(相当于当前位置)

 // declare a global variable of FusedLocationProviderClient
    private lateinit var fusedLocationClient: FusedLocationProviderClient

// in onCreate() initialize FusedLocationProviderClient
    fusedLocationClient = LocationServices.getFusedLocationProviderClient(context!!)

 /**
     * call this method for receive location
     * get location and give callback when successfully retrieve
     * function itself check location permission before access related methods
     *
     */
    fun getLastKnownLocation() {
            fusedLocationClient.lastLocation
                .addOnSuccessListener { location->
                    if (location != null) {
                       // use your location object
                        // get latitude , longitude and other info from this
                    }

                }

    }

如果您的应用可以持续跟踪位置,那么您必须接收接收位置更新

检查 kotlin 中的示例

// declare a global variable FusedLocationProviderClient
        private lateinit var fusedLocationClient: FusedLocationProviderClient

    // in onCreate() initialize FusedLocationProviderClient
        fusedLocationClient = LocationServices.getFusedLocationProviderClient(context!!)


      // globally declare LocationRequest
        private lateinit var locationRequest: LocationRequest

        // globally declare LocationCallback    
        private lateinit var locationCallback: LocationCallback


        /**
         * call this method in onCreate
         * onLocationResult call when location is changed 
         */
        private fun getLocationUpdates()
        {

                fusedLocationClient = LocationServices.getFusedLocationProviderClient(context!!)
                locationRequest = LocationRequest()
                locationRequest.interval = 50000
                locationRequest.fastestInterval = 50000
                locationRequest.smallestDisplacement = 170f // 170 m = 0.1 mile
                locationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY //set according to your app function
                locationCallback = object : LocationCallback() {
                    override fun onLocationResult(locationResult: LocationResult?) {
                        locationResult ?: return

                        if (locationResult.locations.isNotEmpty()) {
                            // get latest location 
                            val location =
                                locationResult.lastLocation
                            // use your location object
                            // get latitude , longitude and other info from this
                        }


                    }
                }
        }

        //start location updates
        private fun startLocationUpdates() {
            fusedLocationClient.requestLocationUpdates(
                locationRequest,
                locationCallback,
                null /* Looper */
            )
        }

        // stop location updates
        private fun stopLocationUpdates() {
            fusedLocationClient.removeLocationUpdates(locationCallback)
        }

        // stop receiving location update when activity not visible/foreground
        override fun onPause() {
            super.onPause()
            stopLocationUpdates()
        }

        // start receiving location update when activity  visible/foreground
        override fun onResume() {
            super.onResume()
            startLocationUpdates()
        }

确保您注意位置的 Mainfaist 权限和运行时权限

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

为 Gradle 添加这个

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

更多详情请关注官方文档

https://developer.android.com/training/location/retrieve-current

https://developer.android.com/training/location/receive-location-updates

https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderClient

关于android - 获取位置 android Kotlin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45958226/

相关文章:

android - 当我们从顶部状态栏启用位置时,如何关闭 LocationSettingsRequest 对话框?

androidx.navigation 库更新到 2.2.2 版本发布构建问题

java - fragment 设计

android - 从 fragment 调用 startActivityForResult 时出错

c# - WPF - 设置相对于用户控件的对话框窗口位置

android - Recyclerview DiffUtil 项目更新

android - 使用 Fragments 实现 Compose 底部导航

Android Things - 无法使用 Awareness API

java - 如何有效地使用事件总线?

xamarin - 带有位置(纬度和经度)的 Xamarin.Forms (PCL) WebView