如何从AsyncTask的调用父活动的功能?功能、AsyncTask

由网友(从此深情都喂风)分享简介:setAccountAuthenticatorResult 可以被称为从活动,延伸 AccountAuthenticatorActivity 。我的活动扩展了,但启动AsyncTask的,因此这种 setAccountAuthenticatorResult 应的AsyncTask(或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的(这一点);
 
Android之AsyncTask机制篇

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

阅读全文

相关推荐

最新文章