获取位置 android 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()
}

原文由 Nour Medhat 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.1k
2 个回答

GetUserLocation 返回时, locationManager 超出范围并可能被销毁,从而防止 onLocationChanged 被调用并提供更新。

此外,您已经在 mylocation 内部定义了 GetUserLocation 所以它也超出了范围并进一步扼杀了任何机会或您获得更新。

您还没有显示外部 mylocation 的声明位置和方式(在 GetUserLocation 之外),但是无论它是如何声明的,它都被 GetUserLocation 的内部所掩盖 --- .所以你得到的不多。

这是一个示例,说明您可以如何做到这一点。 (变量 thetext 在布局 xml 中定义并通过 Kotlin 扩展访问。)

 // in the android manifest
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
// allow these through Appliation Manager if necessary

// inside a basic activity
private var locationManager : LocationManager? = null

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    setSupportActionBar(toolbar)

    // Create persistent LocationManager reference
    locationManager = getSystemService(LOCATION_SERVICE) as LocationManager?

    fab.setOnClickListener { view ->
        try {
            // Request location updates
            locationManager?.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0L, 0f, locationListener)
        } catch(ex: SecurityException) {
            Log.d("myTag", "Security Exception, no location available")
        }
    }
}

//define the listener
private val locationListener: LocationListener = object : LocationListener {
    override fun onLocationChanged(location: Location) {
        thetext.text = ("" + location.longitude + ":" + location.latitude)
    }
    override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {}
    override fun onProviderEnabled(provider: String) {}
    override fun onProviderDisabled(provider: String) {}
}

原文由 Les 发布,翻译遵循 CC BY-SA 4.0 许可协议

我阅读了很多答案,但问题是只获得最后一个已知位置。使用接收器,它会不断发送纬度和经度,我在 kotlin 中有解决方案.. 授予权限

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

    public fun getLastKnownLocation(context: Context) {
        val locationManager: LocationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
        val providers: List<String> = locationManager.getProviders(true)
        var location: Location? = null
        for (i in providers.size - 1 downTo 0) {
            location= locationManager.getLastKnownLocation(providers[i])
            if (location != null)
                break
        }
        val gps = DoubleArray(2)
        if (location != null) {
            gps[0] = location.getLatitude()
            gps[1] = location.getLongitude()
            Log.e("gpsLat",gps[0].toString())
            Log.e("gpsLong",gps[1].toString())

        }

    }

原文由 RanaUmer 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题