简体   繁体   English

知道活动是否完成的正确方法

[英]proper way to know if an activity has been finished

I've read 我读了

" How to know activity has been finished? " and " Proper way to know whether an Activity has been destroyed " 如何知道活动是否已完成? ”和“ 知道活动是否已被销毁的正确方法

but none of them got real answers 但他们都没有得到真正的答案

I've a background task updating a screen with it's progress 我有一个后台任务正在更新屏幕

The user has a button to cancel the background task at any moment, and if he does that the background task will be stoped and activity will be finished... 用户有一个随时可以取消后台任务的按钮,如果他这样做,后台任务将停止并且活动将完成。

BUT as all of this happen in an asynchronous enviroment the following situation may happen: 但是,由于所有这些都发生在异步环境中,因此可能会发生以下情况:

1- the background task stacks some notification to update progress activity 1-后台任务会堆叠一些通知以更新进度活动
2- the user cancel the background task 2-用户取消后台任务
3- the background task is stopped (i mean, stops having progress) and activity is finished ( activity.finish() ) 3-后台任务停止(我的意思是,停止进度)并且活动完成( activity.finish()
4- the previous stacked updates are delivered to the activity which tries to perform some update on its fields and lead to error 4-先前堆积的更新被传递到活动,该活动尝试对其字段执行一些更新并导致错误

I would like an "oficial android approach" better than having a boolean which is set to true during onDestroy() 我想要一个“官方的android方法”,而不是在onDestroy()期间将其设置为true的布尔值。

Since you're finishing the activity by calling finish() then I think checking isFinishing() before updating the UI would work in your use case. 由于您通过调用finish()活动,因此我认为在更新用户界面之前检查isFinishing()在您的用例中是可行的。

For more advanced use cases I suggest you should look into RxJava for doing asynchronous background tasks that are tightly coupled with activity lifecycle. 对于更高级的用例,建议您使用RxJava来执行与活动生命周期紧密相关的异步后台任务。

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

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