AsyncTaskLoader restarts when the activity is recreated

482 views Asked by At

Hi I'm implementing a custom asynctaskloader to load data in the background, and I need the loading process to run even if the user navigated out of the application. The problem is, once the user presses the menu button for example the loader onStopLoading() is called and then the loadInbackgroud() is called to restart the loading process.

Any ideas how can I prevent the loader to restart the loading process every time I navigate out of the program or turn of the screen given that during the loading process I acquire a partial wake lock.

P.S: The loader is attached to a fragment and the fragment RetainInstance is set to true.

Thanks in advance.

1

There are 1 answers

0
Steven On

Have you considered using an IntentService instead of an AsyncTask?

An IntentService is a component which runs in the background and is not bound to the lifecycle of an activity, thus will not be affected when a fragment/activity is paused/restarted/destroyed. You can still publish progress/results/failures to activity or fragment-based listeners using a ResultReceiver.

A very basic code sample:

public class MyService extends IntentService
{
    public MyService()
    {
       super("MyService");
    }

    @Override
    protected void onHandleIntent(Intent intent)
    {
        // Perform your loading here ...

        publishOutcome("Success");
    }

    private void publishOutcome(String outcome)
    {
        Bundle outcomeData = new Bundle();
        outcomeData.putString(OUTCOME, outcome);        
        receiver.send(MY_OUTCOME, outcomeData );
    }
} 

For a more detailed discussion on AsyncTask vs IntentService have a look at this StackOverflow question.