具有Kotlin协程的FusedLocationProviderClient

时间:2019-03-28 15:28:25

标签: android kotlin fusedlocationproviderapi kotlin-coroutines

我正在尝试通过FusedLocationProviderClient和Kotlin Coroutines请求一个新位置。这是我当前的设置:

class LocationProviderImpl(context: Context) : LocationProvider, CoroutineScope {

    private val TAG = this::class.java.simpleName

    private val job = Job()
    override val coroutineContext: CoroutineContext
        get() = job + Dispatchers.IO

    private val fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(context)
    private val locationRequest = LocationRequest().apply {
        numUpdates = 1
        priority = LocationRequest.PRIORITY_HIGH_ACCURACY
    }

    override suspend fun getLocation(): LatLng = suspendCoroutine {
        val locationCallback = object : LocationCallback() {
            override fun onLocationResult(result: LocationResult) {
                result.lastLocation.run {
                    val latLng = latitude at longitude
                    it.resume(latLng)
                }

                fusedLocationProviderClient.removeLocationUpdates(this)
            }
        }

        try {
            fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper())
        } catch (e: SecurityException) {
            throw NoLocationPermissionException()
        }
    }
}

但是当尝试请求新位置时,出现以下异常:

java.lang.IllegalStateException: Can't create handler inside thread that has not called Looper.prepare()

但是,如果我要调用Looper.prepare()(最终要调用Looper.quit()),这不意味着我只能调用一次函数吗?

感谢您的帮助。

3 个答案:

答案 0 :(得分:3)

private val locationRequestGPS by lazy {
    LocationRequest.create()
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
            .setNumUpdates(1)
            .setExpirationDuration(1000)
}

private val locationRequestNETWORK by lazy {
    LocationRequest.create()
            .setPriority(LocationRequest.PRIORITY_LOW_POWER)
            .setNumUpdates(1)
            .setExpirationDuration(1000)
}



suspend fun getLocation(context: Context, offsetMinutes: Int = 15): Location? = suspendCoroutine { task ->
    val ctx = context.applicationContext
    if (!ctx.isPermissionValid(Manifest.permission.ACCESS_COARSE_LOCATION)
            && !ctx.isPermissionValid(Manifest.permission.ACCESS_FINE_LOCATION)) {
        task.resume(null)
    } else {
        val manager = ctx.getSystemService(Context.LOCATION_SERVICE) as LocationManager
        if (!LocationManagerCompat.isLocationEnabled(manager)) {
            task.resume(null)
        } else {
            val service = LocationServices.getFusedLocationProviderClient(ctx)
            service.lastLocation
                    .addOnCompleteListener { locTask ->
                        if (locTask.result == null || System.currentTimeMillis() - locTask.result!!.time > offsetMinutes.minute) {
                            GlobalScope.launch(Dispatchers.Main) {
                                task.resume(locationRequest(manager, service))
                            }
                        } else {
                            task.resume(locTask.result)
                        }

                    }
        }
    }
}

suspend fun getLocationLast(context: Context): Location? = suspendCoroutine { task ->
    val ctx = context.applicationContext
    if (!ctx.isPermissionValid(Manifest.permission.ACCESS_COARSE_LOCATION)
            && !ctx.isPermissionValid(Manifest.permission.ACCESS_FINE_LOCATION)) {
        task.resume(null)
    } else {
        if (!LocationManagerCompat.isLocationEnabled(ctx.getSystemService(Context.LOCATION_SERVICE) as LocationManager)) {
            task.resume(null)
        } else {
            LocationServices.getFusedLocationProviderClient(ctx)
                    .lastLocation
                    .addOnCompleteListener { locTask ->
                        task.resume(locTask.result)
                    }
        }

    }
}

suspend fun locationRequest(locationManager: LocationManager, service: FusedLocationProviderClient): Location? = suspendCoroutine { task ->
    val callback = object : LocationCallback() {
        override fun onLocationResult(p0: LocationResult?) {
            service.removeLocationUpdates(this)
            task.resume(p0?.lastLocation)
        }
    }

    when {
        locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) -> {
            service.requestLocationUpdates(locationRequestGPS, callback, Looper.getMainLooper())
        }
        locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) -> {
            service.requestLocationUpdates(locationRequestNETWORK, callback, Looper.getMainLooper())
        }
        else -> {
            task.resume(null)
        }
    }
}

答案 1 :(得分:1)

通过使用suspendCoroutine,您可以在调度程序上调用提供的代码,该代码在运行时调用了挂起的函数。由于大多数调度程序都不在Looper线程上运行(几乎只有Dispatchers.MAIN才运行),因此对Looper.myLooper()的调用失败。

文档说您可以将Looper.myLooper()替换为null,以在未指定的线程上调用回调。然后,内置的协程分派器将确保将其路由到正确的线程以恢复执行。

编辑:您可能需要调用it.intercepted().resume(latLng)以确保将结果分派到正确的线程。我不确定suspendCoroutine的延续是否默认被拦截。

此外,您无需致电fusedLocationProviderClient.removeLocationUpdates(this),因为您已经将LocationRequest中的更新次数设置为1

答案 2 :(得分:1)

您设置的coroutineContext错误。您应该拥有

override val coroutineContext = Dispatchers.MAIN + job

如果您需要IO调度程序,请明确要求它:

withContext(Dispatchers.IO) { ... blocking IO code ... }

要暂停协程,请致电suspendCancellableCoroutine,否则您将无法从结构化并发中受益。

另一个细节,不要在it.resume块中的suspendCancellableCoroutine之后编写任何代码。如果调度员选择在resume调用内立即恢复协程,则该代码将在协程的所有代码都运行完(或至少直到下一个暂停点)后才执行。

override fun onLocationResult(result: LocationResult) {
    fusedLocationProviderClient.removeLocationUpdates(this)
    it.resume(result.lastLocation.run { latitude at longitude })
}