要从多个类调用的公共 AsyncTask [英] public AsyncTask to be called from several classes

查看:18
本文介绍了要从多个类调用的公共 AsyncTask的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Android 新手.我开始在这个项目中工作已经有几个星期了.阅读已经制作的代码,我看到很多私有异步任务基本上都在做相同的事情(调用 API)所以我想知道是否有更好的解决方案,我的想法是创建一个名为 ApiCaller 的公共异步任务,它将返回一个 JSONObject 和负责解析 JSON 的类将是调用 ApiCaller 的类:

public class ApiCaller extends AsyncTask{私有静态最终字符串标记 = "ApiCall";私有最终字符串 apiVersion = "v1";private final String baseURL = "http://my.api.com/";私有字符串 URL = null;/*** 生成用于调用 API 的 URL.** @param params 列出调用API 的参数.*/公共 ApiCaller(ArrayList params){String apiURL = this.baseURL + this.apiVersion + "/?";String paramsList = URLEncodedUtils.format(params, "utf-8");this.URL = apiURL + paramsList;}@覆盖受保护的 JSONObject doInBackground(String ... params) {Log.i(TAG, "API:");Log.i(TAG, this.URL);JSONManager jParser = new JSONManager();JSONObject jsonObject = jParser.getJSONFromUrl(this.URL);返回 json 对象;}

有没有办法在类之外返回该 JSONObject,以便我可以执行以下操作:

JSONObject js = apiCaller.execute();

或者任何其他解决方案可以避免每次我需要调用 API 时创建新的异步任务?使用我当前的代码我无法获得它,但我不知道缺少什么?也许在 onPostExecute 中返回它?

解决方案

前段时间我也问过类似的问题

一个 AsyncTask 用于多个活动

我找到的解决方案在另一个问题中得到了回答:

Android 中 AsyncTask 的通用类?>

基本上,您需要的是一个接口.

我将解释基础知识,但您应该通过 @SirDarius 查看原始答案.

你可以创建一个这样的界面:

interface AsyncTaskCompleteListener;{public void onTaskComplete(T 结果);}

并在您需要使用 AsynTask 的所有类中实现该接口,然后,在您的通用 Asynstask 中,您需要有一个回调 AsyncTaskCompleteListener> 并从您的 onPostExecute

调用它

B 类实现 AsyncTaskCompleteListener{public void onTaskComplete(JSONObject 结果){//做任何你需要的}公共无效启动任务(字符串网址){ApiCaller a = new ApiCaller(context, ArrayList params, this);ApiCaller.execute(url);}}ApiCaller 类扩展了 AsyncTask{私有 AsyncTaskCompleteListener打回来;public ApiCaller(上下文上下文,ArrayList params,AsyncTaskCompleteListener cb){this.context = 上下文;this.callback = cb;}protected void onPostExecute(String result) {finalResult = 结果;progressDialog.dismiss();System.out.println("在执行后调用");callback.onTaskComplete(result);}}

I'm new in Android. It's been a few weeks since I started working in this project. Reading the code already made I see a lot of private async tasks doing basically the same (call an API) So I wonder if there is a better solution, my idea would be create a public async task called ApiCaller which will return a JSONObject and the responsible for parsing the JSON would be the class calling the ApiCaller:

public class ApiCaller extends AsyncTask<String, String, JSONObject> {
    private static final String TAG = "ApiCall";
    private final String apiVersion = "v1";
    private final String baseURL = "http://my.api.com/";
    private String URL = null;

    /**
     * Generates the URL to call the API.
     *
     * @param params List with the params to call the API.
     */
    public ApiCaller(ArrayList<NameValuePair> params){
        String apiURL = this.baseURL + this.apiVersion + "/?";
        String paramsList = URLEncodedUtils.format(params, "utf-8");
        this.URL = apiURL + paramsList;
    }

    @Override
    protected JSONObject doInBackground(String ... params) {
        Log.i(TAG, "API:");
        Log.i(TAG, this.URL);
        JSONManager jParser = new JSONManager();
        JSONObject jsonObject = jParser.getJSONFromUrl(this.URL);
        return jsonObject;
}

Is there a way to return that JSONObject outside of the class so I can do something like:

JSONObject js = apiCaller.execute();

Or any other solution to avoid creating new asynctasks every time I need to call the API? With my current code I can't get it but I don't know what is missing? maybe returning it in onPostExecute?

解决方案

Some time ago I've asked a similar question

One AsyncTask for multiple Activities

and the solution I found was answered in another question:

Common class for AsyncTask in Android?

Basically, what you need is an interface.

I've going to explain the basics, although you should check the original answer by @SirDarius.

You could create an interface like this:

interface AsyncTaskCompleteListener<T> {
   public void onTaskComplete(T result);
}

And implements that interface in all classes you need to use the AsynTask, then, in your generic Asynstask you need to have a callback AsyncTaskCompleteListener and call it from your onPostExecute

class B implements AsyncTaskCompleteListener<JSONObject> {

    public void onTaskComplete(JSONObject result) {
        // do whatever you need
    }

    public void launchTask(String url) {
        ApiCaller a = new ApiCaller(context, ArrayList<NameValuePair> params, this);
        ApiCaller.execute(url);
    }
}


class ApiCaller extends AsyncTask<String, Void, String> {
    private AsyncTaskCompleteListener<String> callback;

    public ApiCaller(Context context, ArrayList<NameValuePair> params, AsyncTaskCompleteListener<String> cb) {
        this.context = context;
        this.callback = cb;
    }

    protected void onPostExecute(String result) {
       finalResult = result;
       progressDialog.dismiss();
       System.out.println("on Post execute called");
       callback.onTaskComplete(result);
   }  
}

这篇关于要从多个类调用的公共 AsyncTask的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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