lomza
lomza

Reputation: 9716

Android launches an async task on every configuration change

After reading a few articles about Android configuration, I still don't know how to NOT launch an async task when I change the view from portrait to landscape. I load some information from the server, and it will be not wise to load it every time I rotate my phone. I want to load it once. Can I do that without adding 'changeConfig' flag in Manifest file?

Upvotes: 1

Views: 308

Answers (3)

STT LCU
STT LCU

Reputation: 4330

Don't blindly launch an asyncTask. Follow these instructions:

  1. define 'boolean guard = false' in your activity variables declaration
  2. inside "onCreate(...) do:

    if(savedInstanceState!=null){
        guard=(Boolean) savedInstanceState.get(guardkey) //guardkey is the bundle key. (*1)
    } else{
        guard=false;
    }
    if(!guard){
        //launch your asyncTask
        guard=true;
        //other operations if needed
    }
    

    now, add to "onSaveInstanceState(outState)" method you have (if you don't have it, do so now) the following line:

    outState.put(guardkey, guard); //(*1)
    

NOTE: this prevents you to fire tasks every time you change configurations. It presumes that you have already received your info from the server, and you saved it in your activity properly (this means you can retrieve it on activity restart). Otherwise, this solution is not for you.

Upvotes: 0

dmon
dmon

Reputation: 30168

1 Make your AsyncTask a private instance variable of your class (has to be declared as a static inner class or as a separate file).

2 Return your AsyncTask instance in onRetainConfigurationChanges()

  public Object onRetainNonConfigurationInstance() {
      return yourAsyncTask;
  }

3 Retrieve it in oResume():

 public void onResume() {
   Object data = getLastNonConfigurationInstance();
   if (data != null) {
     ... // pass in your activity to the AsyncTask so it can update your views
   } else {
     ... // create new AsyncTask and spin it up.
   }
 }

Upvotes: 3

the100rabh
the100rabh

Reputation: 4147

You need to look at this http://developer.android.com/resources/articles/faster-screen-orientation-change.html

This will solve all the issues ur mentioning

Basically u need to implement

public Object onRetainNonConfigurationInstance()

which returns the data you want

and then you need to call getLastNonConfigurationInstance and if the value is there, not get it from server :-)

Upvotes: 1

Related Questions