如何使用片段的位置精度不断更新文本视图

How to keep updating textview with the location accuracy from a fragment

我想每 2 秒更新一次用户的位置精度。

我创建了这个函数 getAccuracy(activity, currentAccuracy),它会在调用时用当前位置更新 textView。

我希望它每 2 秒调用一次。这是我当前的代码,但它不起作用 - 文本甚至一次都没有获得值并保持空白,如果我在没有 runOnUiThread 的情况下使用该函数,它将至少显示一次。

    val activity = activity as CameraActivity


    val handler = Handler()
    val delay: Long = 2000 //milliseconds

    handler.postDelayed(object : Runnable {
        override fun run() {

            activity.runOnUiThread {
                object : Runnable {
                    override fun run() {
                        getAccuracy(activity, currentAccuracy)
                    }
                }
            }

            handler.postDelayed(this, delay)
        }
    }, delay)

这是函数,使用了AirLocation

fun getAccuracy(activity: Activity, currentAccuracy: TextView) {

    airLocation = AirLocation(activity, true, true, object : AirLocation.Callbacks {
        override fun onSuccess(location: Location) {
            currentAccuracy.text = location.accuracy.toString()
            Log.d("locationAccuracy","Success")
        }

        override fun onFailed(locationFailedEnum: AirLocation.LocationFailedEnum) {
            Log.d("locationAccuracy","Fail")

        }

    })

}

您每 2 秒重新创建一次 AirLocation 实例,这并不好,因为它可能没有足够的时间甚至获取位置数据。您应该使用相同的实例。要解决此问题...

你应该让airLocation变量成为class的私有成员变量。我想你已经做到了...

class YourActivity : AppCompatActivity() {

    private var airLocation: AirLocation? = null
}

然后在onCreate

中初始化那个变量
override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.main_activity)

        airLocation = AirLocation(this, true, true, object: AirLocation.Callbacks {
                override fun onSuccess(location: Location) {
                    if(location != null){
                        currentAccuracy.text = location.accuracy.toString()
                    }
                }

                override fun onFailed(locationFailedEnum: AirLocation.LocationFailedEnum) {
                }

            })
}

然后覆盖 onActivityResult 并调用 AirLocationonActivityResult

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        airLocation?.onActivityResult(requestCode, resultCode, data)
        super.onActivityResult(requestCode, resultCode, data)
    }

假设您正在处理所需的权限并且位置设置已打开,那应该可以工作。 不幸的是,这个库不允许你设置位置请求之间的间隔,间隔设置为 10 秒,最快间隔为 2 秒,你不能改变它。这是源代码的片段...

val locationRequest = LocationRequest().apply {
        interval = 10000
        fastestInterval = 2000
        priority = LocationRequest.PRIORITY_HIGH_ACCURACY
        numUpdates = 1
    }

但是,如果控制间隔对您来说至关重要,您可以构建自己的实现。这并不难。祝你好运