kotlin coroutine抛出java.lang.IllegalStateException:已经恢复,但得到了值Location

时间:2018-01-12 13:32:44

标签: android kotlin locationmanager kotlinx.coroutines

我对Kotlin协程和Android开发很新。 在玩弄周围以了解它是如何工作的时候,我遇到了一个我似乎无法解决的错误。

从基本活动开始,我尝试连接到googleApiClient。权限还可以。 我希望使用kotlin协程以直接样式从LocationManager获取位置更新,以便稍后使用此Location对象。 我第一次在模拟器中改变了位置它工作正常,第二次改变我的位置时,它崩溃了 像这样的例外:

FATAL EXCEPTION: main
    Process: com.link_value.eventlv, PID: 32404
    java.lang.IllegalStateException: Already resumed, but got value Location[gps 48.783000,2.516180 acc=20 et=+59m16s372ms alt=0.0 {Bundle[mParcelledData.dataSize=40]}]
    at kotlinx.coroutines.experimental.AbstractContinuation.resumeImpl(AbstractContinuation.kt:79)
    at kotlinx.coroutines.experimental.AbstractContinuation.resume(AbstractContinuation.kt:72)
    at com.link_value.eventlv.View.Create.NewEventLvActivity$await$2$1.onLocationChanged(NewEventLvActivity.kt:100)
    at android.location.LocationManager$ListenerTransport._handleMessage(LocationManager.java:297)
    at android.location.LocationManager$ListenerTransport.-wrap0(LocationManager.java)
    at android.location.LocationManager$ListenerTransport$1.handleMessage(LocationManager.java:242)
     at android.os.Handler.dispatchMessage(Handler.java:102)
     at android.os.Looper.loop(Looper.java:154)
     at android.app.ActivityThread.main(ActivityThread.java:6077)
     at java.lang.reflect.Method.invoke(Native Method)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)



override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_new_event_lv)

    askForUserLocation()
    val locationManager = this.getSystemService(Context.LOCATION_SERVICE) as LocationManager
    val presenter = CreateEventPresenterImpl(this@NewEventLvActivity)

    googleApiClient = GoogleApiClient.Builder(this@NewEventLvActivity)
            .enableAutoManage(this /* FragmentActivity */,
                    this /* OnConnectionFailedListener */)
            .addApi(Places.GEO_DATA_API)
            .addConnectionCallbacks(this)
            .build()
}
override fun onConnected(p0: Bundle?) {
    val locationManager = this.getSystemService(Context.LOCATION_SERVICE) as LocationManager
    input_address.addTextChangedListener(object: TextWatcher{
        override fun afterTextChanged(p0: Editable?) {
        }

        override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
        }

        override fun onTextChanged(query: CharSequence?, p1: Int, p2: Int, p3: Int) {
            if (query.toString().length >= 4) {
                launch(UI) {
                    val locationUpdated = locationManager.await(LocationManager.GPS_PROVIDER)
                    input_name.text = Editable.Factory.getInstance().newEditable(locationUpdated.toString())
                }
            }
        }
    })
}

private suspend fun LocationManager.await(locationProvider: String): Location? = suspendCoroutine { cont ->
    try {
        requestLocationUpdates(locationProvider, 0, 0.toFloat(), object : LocationListener {
            override fun onStatusChanged(p0: String?, p1: Int, p2: Bundle?) {
            }

            override fun onProviderEnabled(p0: String?) {
            }

            override fun onProviderDisabled(p0: String?) {
                cont.resumeWithException(UnknownLocationException())
            }

            override fun onLocationChanged(location: Location?) {
                cont.resume(location)
            }
        })
    } catch (ex: SecurityException) {
        cont.resumeWithException(ex)
    }
}

就像Kotlin使用相同的Continuation一样。我不知道我做错了什么以及为什么第二次崩溃。有人可以开导我。 提前问。

2 个答案:

答案 0 :(得分:3)

根据文档,仅一次可以恢复“继续”。第二个简历将抛出IllegalStateException,并显示“已经恢复,但收到$ proposedUpdate”消息。您可以添加其他检查continuation.isActive以防止出现此异常。最好将Channels用于多个回调,例如位置更新。

答案 1 :(得分:0)

我最近在项目中使用的第三方API之一遇到了此问题。问题仅出在API方面,因为在基础实现中多次调用了回调,并且unsubscribe方法没有立即从API中删除回调。

因此,我选择的方法只是添加一个布尔标志。虽然,用Kotlin的Flow.mapLatest/collectLatest可以用一种更优雅的方式解决它。

suspend fun singularContentUpdate(): Data =
    suspendCancellableCoroutine { continuation ->
        var resumed = false

        val callback = object : Callback {
            override fun onDataReady(d: Data) {
                api.unsubscribe(this)

                if (!resumed) {
                    continuation.resume(d)
                    resumed = true
                }
            }
        }

        continuation.invokeOnCancellation {
            api.unsubscribe(callback)
        }

        api.subscribe(subscriber)

        api.refresh()
    }