简体   繁体   English

android服务中的协程资源什么时候释放?

[英]When to release the coroutine resources in android service?

I am using kotlin coroutines in my JobIntentService , So on onHandleWork i would launch my coroutine, once this tasks ends i need to clean up the resources by cancelling the Job .我在我的JobIntentService中使用 kotlin 协程,所以在onHandleWork我会启动我的协程,一旦这个任务结束,我需要通过取消Job来清理资源。 onDestroy called immediately after starting of the service, Since i am launching the coroutine on the onHandleWork it doesn't block the current thread. onDestroy在服务启动后立即调用,因为我在onHandleWork上启动协程,它不会阻塞当前线程。

is it mandatory to cancel the coroutine after finishing the task?完成任务后必须取消协程吗?

If so, When to release the coroutine resources in the android Service lifecycle如果是,android Service生命周期内的协程资源何时释放

Can anyone help me with this?谁能帮我这个?

is it mandatory to cancel the coroutine after finishing the task?完成任务后必须取消协程吗?

No, it is not mandatory.不,这不是强制性的。 Usually coroutines are launched in a context of some CoroutineScope and CoroutineScope is tied to some lifecycle, usually Activity or Fragment .通常协程在某个CoroutineScope的上下文中启动的,而CoroutineScope与某个生命周期相关联,通常是ActivityFragment Coroutines are used to execute some task in a background thread in a sequential manner.协程用于以顺序方式在后台线程中执行某些任务。

Method onHandleWork of JobIntentService class is called on a background thread , so you can do long blocking operations here. onHandleWorkJobIntentService方法是在后台线程调用的,所以这里可以做长阻塞操作。 I don't see the reason why you should launch a coroutine in this method.我看不出你应该在这种方法中启动协程的原因。 Just execute your task without launching the coroutine.只需执行您的任务而不启动协程。

Since i am launching the coroutine on the onHandleWork it doesn't block the current thread.由于我在onHandleWork上启动协程,它不会阻塞当前线程。

Method onHandleWork is called on a background thread so you don't need to launch a coroutine there.方法onHandleWork在后台线程上调用,因此您无需在那里启动协程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM