androidandroid-asynctaskaccountmanager

How to call parent activity function from ASyncTask?


setAccountAuthenticatorResult can be called from the Activity, which extends AccountAuthenticatorActivity. My activity extends that, but launches ASyncTask and hence this setAccountAuthenticatorResult should be called from ASyncTask (or, the result of ASyncTask should be passed back to the main thread).

How to do it?

What is wrong in the code below?

AsyncTask<Uri, Void, Bundle> task = new RetrieveAccessTokenTask(this, consumer, provider, prefs).execute(uri);

public class RetrieveAccessTokenTask extends AsyncTask<Uri, Void, Bundle> {
    private Context context;

    public RetrieveAccessTokenTask(Context context, OAuthConsumer consumer,
            OAuthProvider provider, SharedPreferences prefs) {
        this.context = context;
    }

    @Override
    protected void onPostExecute(Bundle result) {
        context.setAccountAuthenticatorResult(); // doesn't work

    }

Solution

  • When you create the AsyncTask, you can add a new constructor to it, and pass in a reference to the Activity:

    AsyncTask myTask = new MyTask(this);
    

    And then from the onPostExecute() method in the AsyncTask you can call the method on the Activity.

    public class MyTask extends AsyncTask<String, String, String>
    {
        public MyActivity activity;
    
        public MyTask(MyActivity a)
        {
            this.activity = a;
        }
    
        //  ......
    
        protected void onPostExecute(String result)
        {
            activity.myMethod();
        }
    }