如何从 ASyncTask 调用父活动函数? [英] How to call parent activity function from ASyncTask?

查看:34
本文介绍了如何从 ASyncTask 调用父活动函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

setAccountAuthenticatorResult 可以从 Activity 中调用,它扩展了 AccountAuthenticatorActivity.我的活动扩展了它,但启动了 ASyncTask,因此这个 setAccountAuthenticatorResult 应该从 ASyncTask 调用(或者,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).

怎么做?

下面的代码有什么问题?

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

    }

推荐答案

当你创建 AsyncTask 时,你可以给它添加一个新的构造函数,并传入一个对 Activity 的引用:

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);

然后您可以从 AsyncTask 中的 onPostExecute() 方法调用 Activity 上的方法.

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();
    }
}

这篇关于如何从 ASyncTask 调用父活动函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆