Background task, progress dialog, orientation chan

2018-12-31 08:14发布

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"?

8条回答
只若初见
2楼-- · 2018-12-31 08:35

After 4 years Google solved the problem just calling setRetainInstance(true) in Activity onCreate. It will preserve your activity instance during device rotation. I have also a simple solution for older Android.

查看更多
怪性笑人.
3楼-- · 2018-12-31 08:36

The accepted answer was very helpful, but it doesn't have a progress dialog.

Fortunately for you, reader, I have created an extremely comprehensive and working example of an AsyncTask with a progress dialog!

  1. Rotation works, and the dialog survives.
  2. You can cancel the task and dialog by pressing the back button (if you want this behaviour).
  3. It uses fragments.
  4. The layout of the fragment underneath the activity changes properly when the device rotates.
查看更多
登录 后发表回答