accessing MainActivity from long running async task safe way (eg after conguration change)

36 Views Asked by At

I have a long running (really long, more than 60 seconds or more) async task. Sometimes this task has to access the MainActivity (mostly UI updates, but sometimes accessing Shared Preferences and other functions where the tasks expects results). Of course during this long async task anything can happen with the phone, so it needs to be prepared for configuration changes and times when the MainActivity does not exist or changed. Therefore passing the activity is definitely wrong idea.

The other solution is using Handlers, but if I post a Runnable, sometimes it also needs the MainActivity (eg "() -> mainActivity.doSomething()") so this is also not a good solution.

I can send message with the handler, but in this case the async task needs to have the Handler created in the MainActivity (creating a new one ("new Handler(Looper.getMainLooper())") does not work because it has another message queue).

So my question is, what is the difference between passing the activity itself, or passing a Handler instance that is created in the activity? (is there any?) What is the way when the async task needs a result?

Or what is the proper safe way of calling MainActivity functionalities from an AsyncTask?

0

There are 0 best solutions below