Implent an AsyncTask callback function returning multiple values?

ぃ、小莉子 提交于 2020-01-07 09:50:09

问题


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

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

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?


回答1:


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.

For example

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

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

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.



来源:https://stackoverflow.com/questions/37980774/implent-an-asynctask-callback-function-returning-multiple-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!