android - Kotlin 协程resumeWithException 错误

标签 android kotlin location coroutine continuations

我决定使用 kotlin coriutines 来包装获取设备位置(一次,无需更新),所以最后我得到了以下代码:

@SuppressLint("MissingPermission")
suspend fun LocationManager.getCurrentLocationOnce(): Location {
    return suspendCancellableCoroutine { continuation ->
        try {
            val locationListener = object : SimpleLocationListener {
                override fun onLocationChanged(location: Location?) {
                    if (location == null) {
                        <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="71051918023116140532040303141f053d1e121005181e1f3e1f12145f03141c1e071424011510051402" rel="noreferrer noopener nofollow">[email protected]</a>(this)
                        continuation.resumeWithException(FailedToRetrieveLocationException("Location is NULL"))
                    } else {
                        <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d7a3bfbea497b0b2a394a2a5a5b2b9a39bb8b4b6a3beb8b998b9b4b2f9a5b2bab8a1b282a7b3b6a3b2a4" rel="noreferrer noopener nofollow">[email protected]</a>(this)
                        continuation.resume(location)
                    }
                }

                override fun onProviderEnabled(provider: String?) {}

                override fun onProviderDisabled(provider: String?) {
                    <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8ffbe7e6fccfe8eafbccfafdfdeae1fbc3e0eceefbe6e0e1c0e1eceaa1fdeae2e0f9eadaffebeefbeafc" rel="noreferrer noopener nofollow">[email protected]</a>(this)
                    continuation.resumeWithException(ProviderDisabledException(provider ?: ""))
                }

            }

            this.requestSingleUpdate(
                LocationManager.GPS_PROVIDER,
                locationListener,
                null
            )
        } catch (e : Exception) {
            continuation.resumeWithException(e)
        }
    }
}

当 GPS 打开时,一切正常,但当 GPS 关闭时,程序失败并出现异常 ProviderDisabledException,这是因为:

override fun onProviderDisabled(provider: String?) {
                    <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3d4955544e7d5a58497e484f4f58534971525e5c4954525372535e58134f5850524b58684d595c49584e" rel="noreferrer noopener nofollow">[email protected]</a>(this)
                    continuation.resumeWithException(ProviderDisabledException(provider ?: ""))
                }

但我不知道为什么它失败了,因为在我使用这个函数的地方我得到了:

try {
            val locationManager = (requireActivity().getSystemService(Context.LOCATION_SERVICE) as? LocationManager)
                ?: throw FailedToRetrieveLocationException("Location Service is null")
            val location = locationManager.getCurrentLocationOnce()
            log("[GOOGLE] downloadRestaurantsWithGPSLocationGoogle",
                "Successfully got location={lat:${location.latitude}, long:${location.longitude}}")
            downloadRestaurantsWithLocation(location)
        } catch (ex : FailedToRetrieveLocationException) {
            logError("[GOOGLE] downloadRestaurantsWithGPSLocationGoogle", ex)
            throw ex
        } catch (providerException : ProviderDisabledException) {
            logError("[GOOGLE] downloadRestaurantsWithGPSLocationGoogle", providerException)
            throw providerException
        } catch (e : Exception) {
            logError("[GOOGLE] downloadRestaurantsWithGPSLocationGoogle", e)
            throw e
        }

所以我正在记录异常并将其重新抛出给调用者函数,并且在调用者函数中我捕获了此异常:

            try {
                    log("[GOOGLE] downloadRestaurants", "Starting donwload restaurants for GOOGLE")
                    downloadRestaurantsWithGPSLocationGoogle()
                } catch (e : Exception) {
                    logError("[GOOGLE] error happened while getting location", e)
                    downloadRestaurantsWithFusedLocationGoogle()
                }

在错误堆栈跟踪中我只有这个:

E/[GOOGLE] downloadRestaurantsWithGPSLocationGoogle: my.package.location.exceptions.ProviderDisabledException: Provider gps disabled
        at my.package.common.location.LocationUtilsKt$getCurrentLocationOnce$$inlined$suspendCancellableCoroutine$lambda$1.onProviderDisabled(LocationUtils.kt:45)
        at android.location.LocationManager$ListenerTransport._handleMessage(LocationManager.java:384)
        at android.location.LocationManager$ListenerTransport.access$000(LocationManager.java:300)
        at android.location.LocationManager$ListenerTransport$1.handleMessage(LocationManager.java:316)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:207)
        at android.app.ActivityThread.main(ActivityThread.java:6878)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:876)

我不知道为什么应用程序失败,因为这样的代码工作完美:

lifecycleScope.launch {
    try {
        throwError()
    } catch (e : Exception) {
        e.printStackTrace()
    }
}

private suspend fun throwError() {
    return suspendCancellableCoroutine { continuation ->
        continuation.resumeWithException(ProviderDisabledException("TEST"))
    }
}

最佳答案

所以,我终于意识到为什么它会导致应用程序崩溃 =)。协程一切正常。

问题出在这个方法上:

@Throws(ProviderDisabledException::class, FailedToRetrieveLocationException::class)
private fun downloadRestaurantsWithGPSLocationGoogle() = lifecycleScope.launch {
    log("[GOOGLE] downloadRestaurantsWithGPSLocationGoogle", "Trying to get location via GPS")
    try {
        val locationManager = (requireActivity().getSystemService(Context.LOCATION_SERVICE) as? LocationManager)
            ?: throw FailedToRetrieveLocationException("Location Service is null")
        val location = locationManager.getCurrentLocationOnce()
        log("[GOOGLE] downloadRestaurantsWithGPSLocationGoogle",
            "Successfully got location={lat:${location.latitude}, long:${location.longitude}}")
        downloadRestaurantsWithLocation(location)
    } catch (ex : FailedToRetrieveLocationException) {
        ex.printStackTrace()
        logError("[GOOGLE] downloadRestaurantsWithGPSLocationGoogle", ex)
        throw ex
    } catch (providerException : ProviderDisabledException) {
        providerException.printStackTrace()
        logError("[GOOGLE] downloadRestaurantsWithGPSLocationGoogle", providerException)
        throw providerException
    } catch (e : Exception) {
        e.printStackTrace()
        logError("[GOOGLE] downloadRestaurantsWithGPSLocationGoogle", e)
        throw e
    }
}

问题是我从协程中抛出异常,并且不在协程中处理这个异常,所以我启动了我的协程,并且所有的 try-cathces 都被跳过,因为在这里我使用的是“即发即忘”风格。因此,要解决此问题,我需要执行此方法挂起并抛出异常。 try catch 错误的地方:

private fun downloadRestaurants() = lifecycleScope.launch {
        log("downloadRestaurantsWithLocationSort",
            "Requesting Manifest.permission.ACCESS_COARSE_LOCATION & Manifest.permission.ACCESS_FINE_LOCATION permissions")
        val user = requestPermissions(
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION
        )
        if (!user.any { !it.second }) {
            // permission is granted, can download restaurants and sort by nearest
            log("downloadRestaurantsWithLocationSort", "Permissions is granted")
            log("MANUFACTURER", Build.MANUFACTURER)
            if (Build.MANUFACTURER == "Huawei" || Build.MANUFACTURER == "HUAWEI") {
                showToast("HUAWEI")
                try {
                    log("[HUAWEI] downloadRestaurants", "Starting donwload restaurants for HUAWEI")
                    downloadRestaurantsWithGPSLocationHuawei()
                } catch (e : Exception) { // this will not work, because FIRE and FORGET
                    e.printStackTrace()
                    logError("[HUAWEI] error happened while getting location", e)
                    mainViewModel.downloadRestaurantsHeaders(null)
                }
            } else {
                showToast("NOT A HUAWEI")
                try {
                    log("[GOOGLE] downloadRestaurants", "Starting donwload restaurants for GOOGLE")
                    downloadRestaurantsWithGPSLocationGoogle()
                } catch (e : Exception) { // this will not work, because FIRE and FORGET
                    e.printStackTrace()
                    logError("[GOOGLE] error happened while getting location", e)
                    downloadRestaurantsWithFusedLocationGoogle()
                }
            }
        } else {
            // permission is not granted, just download the restaurants
            log("downloadRestaurantsWithLocationSort", "Permissions is NOT granted")
            mainViewModel.downloadRestaurantsHeaders(null)
        }
    }

因此,答案使函数 downloadRestaurantsWithGPSLocationGoogledownloadRestaurantsWithFusedLocationGoogle 暂停,并且不在其中启动单独的协程。 (删除lifecycleScope.launch)

关于android - Kotlin 协程resumeWithException 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62000802/

相关文章:

android - 更改默认下载位置

android - PhoneGap 中 Android Marshmallow 的应用权限

javascript - 什么是自动确定用户位置的好javascript

java - 错误:调用需要API级别23(当前最小值为15):

java - 我想在 android Activity 中显示 json 对象的值

java - 使用 GSON 反序列化通用类型

java - 如何删除连续位置的所有重复项?

java - 我收到以下运行时错误。请帮我找出原因

java - 如何在 Android 的 ListView 中显示解析后的 html

android - 局部委托(delegate)属性和内联属性不支持扩充赋值和增量