1

I'm trying to make an application that uses Asynctask. Particularly, I want to make different http petitions with different JSON in different activities without the activity being frozen while the communication is done.

At first I thought to use asynctask as a private inner class in those activities, but I saw that they share a lot of code. So I thought to make a single class and play with broadcast receivers as I need to monitorize when I receive the result of the http petition, and isn't good to interfere with activity directly in the onPostExecute while in a different class.

What I want to know is, what is more efficient and better practice. Make a class that has the shared code and extends asynctask, then doing inner classes for each activity that extends that one or make a single asynctask that sends broadcast and receive them with each activity when needed.

Excuse my poor english, if needed I'll try to specify more clearly.

Thanks in advance

4

3 回答 3

1

背景

我想知道的是,什么是更有效和更好的做法。创建一个具有共享代码并扩展 asynctask 的类,然后为每个扩展该类的活动执行内部类,或者创建一个发送广播并在需要时与每个活动一起接收它们的单个异步任务。

我不清楚为什么这些是您仅有的两个选择。创建一个AsyncTask,例如JsonPetitionTask,然后推送一个新JsonPetitionTask.Data对象。该对象将包含您的 URL、JSON 以及您需要的任何其他数据。

设置异步任务

像这样的东西:

public class JsonPetitionTask extends AsyncTask<JsonPetitionTask.Data, Integer, Boolean> {
    protected Boolean doInBackground(JsonPetitionTask.Data... args) {
        for (int i = 0; i < args.length; i++) {
            JsonPetitionTask.Data data = args[i];
            // Send your JSON; check for errors, and return false if needed.
            if (isCancelled()) break;
        }
        return true;
    }

    protected void onProgressUpdate(Integer... progress) {
        // Show progress?
    }

    protected void onPostExecute(Boolean result) {
        // result is your success true/false.
    }

    public static class Data {
        public String jsonContent;
        public String petitionUrl;

        public Data(String content, String url) {
            jsonContent = content;
            petitionUrl = url;
        }
    }
}

调用 JsonPetitionTask

然后你可以这样称呼它:

JsonPetitionTask.Data data = new JsonPetitionTask.Data(myJSON, myURL);
new JsonPetitionTask().execute(data);

瞧,您AsyncTask只使用了一个没有接收器的类来执行您的操作。

实现回调

现在,如果您想注册一个回调(特定于调用代码的要执行的东西),那就有点棘手了。如果这是您正在寻找的内容的一部分,我将很高兴编辑这篇文章并解释它。

要添加回调,我们可以使用Runnable该类在作业完成后执行一些代码。

首先,我们需要在Data内部类中添加一个新字段:

public Runnable callback;

接下来,在我们调用之前execute(),我们需要为我们的data对象添加一个新的回调。

data.callback = new Runnable() {
    public void run() {
        // Whatever code you want to run on completion.
    }
};

第三,在JsonPetitionTask课堂上,我们需要一个要运行的东西的列表:

private ArrayList<Runnable> mRunnables = new ArrayList<Runnable>();

确保在循环的每次迭代中doInBackground(),您都执行mRunnables.add(data.callback);.

最后,在 中onPostExecute(),我们需要调用它:

protected void onPostExecute(Boolean result) {
    for (Runnable r : mRunnables)
        if (r != null) r.run();
}

我确实意识到我没有发送resultRunnable,但是我不想实现一个新Runnable类型来处理它。如果你需要这个,我想这对你来说有点功课!

于 2012-09-09T04:07:29.467 回答
1

The way I found the best is just simply create public class that extends AsyncTask and then you just override onPostExecute function in every activity you use it.

Example:

MyDataTask dataTask = new MyDataTask() //you can add your parameters in class constructor
        {
            @Override
            protected void onPostExecute(Object result) //replace Object with your result type
            {
                MyActivity.this.doStuff(result); //use result in current activity
            }
        };

you can also create some custom functions to set private variables in datatask

dataTask.AddParam("user", username);
dataTask.AddParam("pass", pass);

and then just execute it with your args...

dataTask.execute(myArgs);
于 2013-06-27T11:31:10.843 回答
1

我已将异步任务类用作单个类。对于每个 Web 服务调用,我都使用了唯一的 IntentFilter 来广播响应。将广播接收器放在每个班级中。你有完美的解决方案。它运作良好。

于 2016-02-02T09:46:54.190 回答