What to do with AsyncTask in onPause()?

I'm using an AsyncTask in my activity. Looks like:

public class MyActivity {
    private AsyncTask mTask;

    private void doSomethingCool() {
        mTask = new AsyncTask(...);
        mTask.execute();
    }

    @Override
    protected void onPause() { 
        super.onPause();

        // How do I let the task keep running if just rotating?
        if (isFinishing() == false) {
            ... 
        }
    }
}

So if the user is rotating the device, onPause() will get called, but I don't want to cancel the task just because of that. I know there's a way to tell the system to not actually destroy my activity on rotation, but is that recommended for this problem? Should I instead put the AsyncTask in a static global class that won't be bound to the Activity?

Thanks


Asked by: Lana895 | Posted: 24-01-2022






Answer 1

This adds onto Daniel's answer, but is more characters than I can fit in a comment.

More often than not, when I'm using an AsyncTask, I want a dialog spinning, and dealing with that is absurd. You have to do something very much like the solution in the thread that Daniel links to.

The basic principle is, have the Task object keep an explicit reference to its parent. Hold onto the Task object across screen rotations, (using onRetainNonConfigurationInstance), and then in onCreate, make sure that if the Task exists and you're coming from a screen rotation, set the Task's parent activity to the new instance. Inside the task, make sure to call all Activity methods on the explicit parent.

You can see an example of me doing this on a basic ListActivity here: http://github.com/klondike/android-campfire/blob/master/src/com/github/klondike/android/campfire/RoomList.java

One thing I'd do differently than in that example, is that I'd move as much of the Task's onPostExecute into a method on the Activity, just for code cleanliness reasons.

Answered by: Kellan534 | Posted: 25-02-2022



Answer 2

Before diving into the fun that is AsyncTask and orientation changes, let me first ask this - do you need to hold onto the AsyncTask in a variable? There are not many reasons that you need to do this, because AsyncTask has callbacks built-in, so you don't actually need to hold onto your AsyncTask (don't call him, he'll call you). Also, your AsyncTask should continue running even during an orientation change - it's in another thread, after all.

The only time I've had to hold onto AsyncTask was to fix a bug that occurs when you try to show a Dialog while the AsyncTask is running. There's a fix, but it's pretty nasty. There's a lot of discussion of that here, if that's the specific problem you're running into.

Answered by: Melissa417 | Posted: 25-02-2022



Answer 3

Click Here for a great thread posted to the android-developers listserv with some good information on handling screen transitions or incoming calls while running an AsyncTask.

It's written by Mark Murphy from http://commonsware.com/

He includes a link to one of his projects that uses a bus system for handling background threads. https://github.com/commonsguy/cwac-bus/tree

I ended up implementing something that looks a lot like this post in my application and it is working great!

Answered by: Brooke239 | Posted: 25-02-2022



Answer 4

if you really want to run it all of the time: I´m using a Singleton Pattern in my Class extended from AsyncTask and call this in onResume:

@Override
protected void onResume() {
super.onResume();
// connection observer
if (!(AsyncTaskConnectionObserver.getInstance().getStatus() == AsyncTask.Status.RUNNING)) {
    AsyncTaskConnectionObserver.getInstance().execute();
}
}

I simply do nothing in onDestroy (yes, this is called when you´re rotating!) and this task really runs forever...

The Singleton looks like this (only structure, but I think you´ll get it):

public class AsyncTaskConnectionObserver extends AsyncTask<Void, Void, Void> {

private AsyncTaskConnectionObserver(){
super();
}
/**
 * SingletonHolder is loaded on the first execution of
 * Singleton.getInstance() or the first access to SingletonHolder.INSTANCE,
 * not before.
 */
private static class SingletonHolder {
    public static final AsyncTaskConnectionObserver INSTANCE = new AsyncTaskConnectionObserver();
}

public static AsyncTaskConnectionObserver getInstance() {
    return SingletonHolder.INSTANCE;
}

}

Answered by: Vivian360 | Posted: 25-02-2022



Similar questions

android - AsyncTask and SQLite Database

What's the best way to access the database through an async task? I don't think I should pass in a reference to the DbAdapter that the activity is using (could be closed as the activity may be garbage-collected). Also, the db needs a context to be opened and closed, but I don't have that with the async task.


android - How to get XML using AsyncTask and Timer?

In order to get XML data from a server repeatedly, I'm attempting to use AsyncTask and Timer as per Mark Murphy's suggestion. I get the following error: 01-07 16:11:26.705: ERROR/AndroidRuntime(729): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has ...


java - Problem with AsyncTask on rooted Droid

I've got a widget on the Android market called DigiClock widget, and after the last update i've been having some extremely rare and random problems on rooted Motorola Droids ( there may be other handsets with the problem, but the only responses i've had are from rooted droid users ). The problem occurs when an activity is launched that runs an AsyncTask that retrieves all the installed applications from the device while sh...


junit - Android AsyncTask testing with Android Test Framework

I have a very simple AsyncTask implementation example and am having problem in testing it using Android JUnit framework. It works just fine when I instantiate and execute it in normal application. However when it's executed from any of Android Testing framework classes (i.e. AndroidTestCase, ActivityUnitTestCase, ActivityInstrumentationTestCase2...


android - AsyncTask Bug on HTC Sense

Im using HTC Hero with HTS sense. Im experience that sometimes AsyncTask not will run doInBackground method on execute(); Its only on my Hero this appears. Someone have come across same problem? / Martin


java - I have one Activity. In this Activity, I executed a AsyncTask , but it's not working

private class ExecuteLocations extends AsyncTask&lt;String, Void, Void&gt;{ private final ProgressDialog dialog = new ProgressDialog(ListProfiles.this); protected void onPreExecute() { //this.dialog.setMessage("Starting pre-execute..."); //this.dialog.show(); } @Override protected Void doInBackground(String... arg0) { check_profiles_lm=(LocationManager) ListProfiles.thi...


java - When to use a Service or AsyncTask or Handler?

Can someone tell me the TRUE difference?


android - How to cancel AsyncTask when Activity finishes?

In my Activity I use multiple AsyncTask classes. How to cancel AsyncTask when Activity finishes?


android - AsyncTask won't stop even when the Activity has destroyed

I have an AsyncTask object which starts executing when the Activity is created and does stuff in the background (downloads up to 100 images). Everything works fine but there is this peculiar behavior which i'm not able to understand. For eg: when the android screen's orientation changes then the Activity is destroyed and created again. So I override the o...


android - AsyncTask Threading Rule - Can it really only be used once?

In the documentation on AsyncTask it gives the following as a rule related to threading: The task can be executed only once (an exception will be thrown if a second execution is attempted.) All this means is that you have to create a new instance of the class every ti...






Still can't find your answer? Check out these communities...



Android Google Support | Android Community | Android Community (Facebook) | Dev.io Android



top