后台任务,进度对话框,方向的变化 - 有没有100%的工作解决方案?对话框、进度、后台、解决方案

2023-09-11 10:40:02 作者:妄念

我从互联网在后台线程下载一些数据(我用的AsyncTask ),并显示一个进度对话框同时下载。方向的变化,活动将重新启动,然后我的AsyncTask完成 - 我想关闭该对话框陆侃并开始新的活动。但调用dismissDialog有时会抛出一个异常(可能是因为活动被摧毁,新的活动还没有开始呢)。

I download some data from internet in background thread (I use AsyncTask) and display a progress dialog while downloading. Orientation changes, Activity is restarted and then my AsyncTask is completed - I want to dismiss the progess dialog and start a new Activity. But calling dismissDialog sometimes throws an exception (probably because the Activity was destroyed and new Activity hasn't been started yet).

什么是处理这种问题(更新从后台线程的用户界面,即使用户改变方向的工作)的最好方法是什么?是不是有人从谷歌提供一些官方的解决方案?

What is the best way to handle this kind of problem (updating UI from background thread that works even if user changes orientation)? Did someone from Google provide some "official solution"?

推荐答案

第1步:使你的的AsyncTask A 静态嵌套类,或者一个完全独立的类,只是没有内(非静态嵌套)类。

Step #1: Make your AsyncTask a static nested class, or an entirely separate class, just not an inner (non-static nested) class.

步骤#2:让的AsyncTask 守住活动通过数据成员,通过构造方法设置和一个引领者。

Step #2: Have the AsyncTask hold onto the Activity via a data member, set via the constructor and a setter.

第三步:创建当的AsyncTask ,提供电流活动来构造

Step #3: When creating the AsyncTask, supply the current Activity to the constructor.

第四步:在 onRetainNonConfigurationInstance(),返回的AsyncTask ,从原来分离的,现在经过-going外卖活动。

Step #4: In onRetainNonConfigurationInstance(), return the AsyncTask, after detaching it from the original, now-going-away activity.

第五步:在的onCreate(),如果 getLastNonConfigurationInstance()不是,将其转换为你的的AsyncTask 类,并打电话给你的二传手到新的活动与任务相关联。

Step #5: In onCreate(), if getLastNonConfigurationInstance() is not null, cast it to your AsyncTask class and call your setter to associate your new activity with the task.

步骤#6:不要从指的是活动数据成员doInBackground()

如果您按照上面的食谱,它将所有的工作。 onProgressUpdate() onPostExecute() onRetainNonConfigurationInstance开始(在被暂停)和结束时,随后的的onCreate()

If you follow the above recipe, it will all work. onProgressUpdate() and onPostExecute() are suspended between the start of onRetainNonConfigurationInstance() and the end of the subsequent onCreate().

这里是展示该技术的示例项目。

Here is a sample project demonstrating the technique.

另一种方法是沟的AsyncTask 移动你的工作到一个 IntentService 。这是特别有用的,如果要做的工作可能是长期的,应该继续下去,无论什么用户执行的活动方面(例如,下载一个大文件)。您可以使用一个有序的广播意图要么有活动,正在做(如果它仍然在前台)的工作作出反应或提出通知让用户知道的工作已经完成。 这里是一个博客帖子有更多的这种模式。

Another approach is to ditch the AsyncTask and move your work into an IntentService. This is particularly useful if the work to be done may be long and should go on regardless of what the user does in terms of activities (e.g., downloading a large file). You can use an ordered broadcast Intent to either have the activity respond to the work being done (if it is still in the foreground) or raise a Notification to let the user know if the work has been done. Here is a blog post with more on this pattern.