Abhishek
Abhishek

Reputation: 2945

How to handle a running AsyncTask during orientation/configuration change?

I know this question has been discussed several times like here and here.

But my problem is still not solved because most solutions provided are either not suggested or deprecated.

I have an AsyncTask in which I update a TextView text continuously. The execution of the task is started in a toggle button click. Initially I had the AsyncTask as an inner class to the main activity. But I later changed it to an external class.

I am using onSaveInstanceState() and onRestoreInstanceState() methods to store and restore the textview value during an orientation change. What I am not able to achieve is after the orientation, how do I restore the button state and also resume the AsyncTask?

Upvotes: 2

Views: 2537

Answers (3)

s.d
s.d

Reputation: 29436

  1. Use Application class, it's always available, and store the task in a static variable there.

  2. Add a dummy fragment to activity with setRetainInstance(true), use it to store and run AsyncTasks. It will auto-attach on rotation and Activity can find it again by tag.

  3. Use a Service to run background stuff, background services are unaffected by rotation restarts, Activity can bind to it again.

Upvotes: 2

grattmandu03
grattmandu03

Reputation: 1286

According to this page : http://developer.android.com/guide/topics/manifest/activity-element.html#config, if your application targets API level 13 or higher, you should use android:configChanges="orientation|screenSize" to catch the screen rotation into the onConfigurationChanged() method.

By doing this, the onPause and onResume methods are not called, so your TextView will keep its value. And in my mind, it won't stop the running AsyncTask. If it does, try to recall it in the onConfigurationChanged method.

Upvotes: 2

Stochastically
Stochastically

Reputation: 7846

Why can't you just save the button state into the bundle in onSaveInstanceState(...), and restore it during onCreate(...), and hence resume the AsyncTask depending on the button state? Note, my experience is that it's onCreate(..) that normally gets called after an orientation change, rather than onRestoreInstanceState().

Upvotes: 0

Related Questions