无能为力的AsyncTask回调函数返回多个值? [英] Implent an AsyncTask callback function returning multiple values?

查看:133
本文介绍了无能为力的AsyncTask回调函数返回多个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解AsyncTask回调如何工作.到目前为止,这是我的MainActivity外观:

I'm trying to understand how AsyncTask callbacks work. This is how my MainActivity looks so far:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    MyAsyncTask AsyncTask = new MyAsyncTask(arg1,arg2,arg3).execute();
}

这是我的AsyncTask类:

And this is my AsyncTask class:

public class MyAsyncTask extends AsyncTask<String, Void, Result> {
    private AsyncListener listener;

    public MyAsyncTask(AsyncListener listener) {
        this.listener = listener;
    }

    public MyAsyncTask() {

    }

    @Override
    protected Result doInBackground(String... strings) {
        return null;
    }

    @Override
    public void onPostExecute(Result result) {
        listener.onTaskCompleted();
    }

    public interface AsyncListener{
        void onTaskCompleted();
    }
}

这只是我想出的骨架结构.我想实现在AsyncTask中调用多个函数的功能,例如使用SharedPreference设置应用启动计数器或初始化AdMob Ads.实施该方法的最佳方法是什么?

This is just the skeleton structure I came up with. I want to implement that I call multiple functions inside the AsyncTask like setting an app launch counter with SharedPreference or initializing AdMob Ads. What would be the best way to implement that?

推荐答案

您的结构不完全正确,因为在Activity用法中有3个参数,但是您的AsyncTask应该回调"给接口侦听器并产生一些结果.

Your structure is not completely correct because you have 3 parameters in the Activity usage, but your AsyncTask should be "calling back" to the interface listener with some result.

例如

@Override
public void onPostExecute(Result result) {
    if (listener != null) {
        listener.onTaskCompleted(result);
    } 
}

因此,您需要更新接口方法以接受参数.

So, you need to update the interface method to accept a parameter.

然后,您需要传递该接口的实现&方法(或匿名类)添加到AsyncTask,那么您就有了一个回调.

Then you need to pass in an implementation of that interface & method (or anonymous class) to the AsyncTask, then you have a callback.

关于调用多个方法,可以将多个回调用于不同的任务,但这实际上取决于最终目标.

Regarding the calling of multiple methods, you can use multiple callbacks for different tasks, but it really depends on your end goal.

这篇关于无能为力的AsyncTask回调函数返回多个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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