如何从AsyncTask的调用父活动的功能? [英] How to call parent activity function from ASyncTask?

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

问题描述

setAccountAuthenticatorResult 可以被称为从活动,延伸 AccountAuthenticatorActivity 。我的活动扩展了,但启动AsyncTask的,因此这种 setAccountAuthenticatorResult 应的AsyncTask(或AsyncTask的结果应该被传递回主线程)。被称为

怎么办呢?

什么是错在下面的code?

 的AsyncTask<开放的,无效的,捆绑>任务=新RetrieveAccessTokenTask(这一点,消费者,供应商,preFS).execute(URI);

公共类RetrieveAccessTokenTask扩展的AsyncTask<开放的,无效的,捆绑> {
    私人上下文的背景下;

    公共RetrieveAccessTokenTask(上下文的背景下,OAuthConsumer消费,
            OAuthProvider提供商,共享preferences preFS){
        this.context =背景;
    }

    @覆盖
    保护无效onPostExecute(捆绑结果){
        context.setAccountAuthenticatorResult(); //不起作用

    }
 

解决方案

在创建的AsyncTask,您可以添加一个新的构造它,并传递一个参考的活动:

 的AsyncTask MyTask的=新MyTask的(这一点);
 

再从onPostExecute()方法中的AsyncTask的,你可以调用活动的方法。

 公共类MyTask的扩展AsyncTask的<字符串,字符串,字符串>
{
    公共MyActivity活动;

    公共MyTask的(MyActivity一)
    {
        this.activity =一个;
    }

    // ......

    保护无效onPostExecute(字符串结果)
    {
        activity.myMethod();
    }
}
 

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

    }

解决方案

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

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

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