如何使用异步任务 [英] How to use AsyncTask

查看:29
本文介绍了如何使用异步任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

异步任务问题

我已经学习了一些教程,但我仍然不清楚.这是我目前在代码下方有一些问题的代码.MainActivity 调用 SomeClassWithHTTPNeeds,然后调用 JSONParser (AsyncTask<>)

<小时>

主要活动:

String station = SomeClassWithHTTPNeeds.getInstance().getStation(123);

<小时>

SomeClassWithHTTPNeeds:

getStation {JSONParser = 新的 JSONParser();JSONObject station = parser.getJSONFromUrl("https://api....");返回 JSONObject.getString("station");}

<小时>

JSONParser (AsyncTask)

protected String doInBackground();==>分离线程protected void onPostExecute();==>在 GUI 线程上

我在想:--- 将 HTTPRequest 放入 doInBackground();

问题是我不知道如何:获取JSONParser 将JSONObject 返回给getStation 方法?

我需要知道的

=> 我应该在哪里返回 JSONObject:在后台或执行?

=> 一旦成为 AsyncTask,我该如何使用 JSONParser?execute() 函数会返回值吗?

=> 异步任务 ==> 这是如何工作的?是返回类型吗?

非常感谢!

解决方案

FAQs 和 AsyncTask 使用的一般说明

<块引用>

=> 我应该在哪里进行网络操作?我应该在哪里返回我获得的值?

通常,您应该在单独线程 -> doInBackground(); 中执行网络操作,因为您不希望您的 UI 在网络操作花费时间时冻结.因此,您应该连接到您的 Service 或 .php 脚本或从 doInBackground() 方法内部获取数据的任何地方.然后你也可以解析那里的数据,并通过指定 doInBackground() 的返回类型来从 doInBackground() 方法返回解析的数据到你的愿望,更多关于那里.onPostExecute() 方法然后将从 doInBackground() 接收您的返回值并使用 UI 表示它们.

<块引用>

=> 异步任务 ==> 这是如何工作的?

一般来说,AsyncTask 类看起来像这样,它只不过是一个具有 3 个不同 泛型类型:

AsyncTask

<块引用>

您可以指定 AsyncTask 采用的参数类型、进度指示器的类型和结果的类型(返回类型doInBackGround()).

这是一个 AsyncTask 的示例,如下所示:

AsyncTask

参数类型为字符串,进度类型为整数,结果类型为长(doInBackground() 的返回类型).您可以为参数、进度和结果使用任何类型.

private class DownloadFilesTask extends AsyncTask{//这些Strings/或String是/是任务的参数,可以通过AsyncTask的execute(params)方法来传递protected Long doInBackground(String... params) {字符串 param1 = params[0];字符串 param2 = params[1];//等等...//对参数做一些事情...//小心,这很容易导致 ArrayIndexOutOfBounds 异常//如果您尝试访问的参数多于您提交的参数长一些长;int someInt;//在这里用参数做一些事情//例如,参数可以包含一个 url,您可以在此处使用此 url 下载内容//Integer 变量用于进度发布进度(someInt);//一旦数据被下载(例如 JSON 数据)//解析数据并返回给 onPostExecute() 方法//在这个例子中,返回数据只是一个长值//这也可以是您的自定义对象的列表,...返回一些Long;}//每当您调用 puhlishProgress(Integer) 时都会调用此方法,例如在下载内容时更新进度条protected void onProgressUpdate(Integer... progress) {setProgressPercent(progress[0]);}//onPostexecute 方法接收到 doInBackGround() 的返回类型protected void onPostExecute(Long result) {//对结果做一些事情,例如在 ListView 中显示接收到的数据//在这种情况下,result"将包含由 doInBackground() 返回的someLong"变量;}}

<块引用>

=> 如何使用 AsyncTask?我怎样才能调用"它?我怎样才能执行"它?

在这种情况下,AsyncTask 将字符串或字符串数​​组作为参数,一旦 AsyncTask 被调用,它将如下所示:(指定参数用于执行(参数) AsyncTask 的方法).

new DownloadFilesTask().execute("Somestring");//一些字符串作为参数

请注意,此调用没有返回值,您应该使用的唯一返回值是从 doInBackground() 返回的值.使用 onPostExecute() 方法确实使用返回值.

还要小心这行代码:(这个执行实际上会有一个返回值)

long myLong = new DownloadFilesTask().execute("somestring").get();

.get() 调用导致 UI 线程被阻塞(因此,如果操作花费的时间超过几毫秒,UI 就会冻结),而 AsyncTask 正在执行,因为执行 不会发生在单独的线程中.如果您删除对 .get() 的调用,它将异步执行.

<块引用>

=> 这个符号execute(String... params)"是什么意思?

这是一种带有所谓的varargs 的方法"(可变参数)参数.为简单起见,我只想说这意味着您可以通过此参数传递给方法的实际值的数量没有指定,并且您传递给方法的任何数量的值都将被视为方法内的数组.例如,此调用可能如下所示:

execute("param1");

但它也可能看起来像这样:

execute("param1", "param2");

甚至更多参数.假设我们还在讨论AsyncTask,在doInBackground(String... params)方法中可以这样访问参数:

 protected Long doInBackground(String... params) {字符串 str1 = params[0];字符串 str2 = params[1];//这里要小心,你很容易得到一个 ArrayOutOfBoundsException//做其他事情}

您可以在此处阅读有关 AsyncTask 的更多信息:http://developer.android.com/reference/android/os/AsyncTask.html

另请看这个 AsyncTask 示例:https://stackoverflow.com/a/9671602/1590502

AsyncTask question

I've followed some tutorials but it still isn't clear to me. Here's the code I currently have with some questions below the code. MainActivity calls SomeClassWithHTTPNeeds, which then calls the JSONParser (AsyncTask<>)


MainActivity:

String station = SomeClassWithHTTPNeeds.getInstance().getStation(123);


SomeClassWithHTTPNeeds:

getStation {

JSONParser = new JSONParser();
JSONObject station = parser.getJSONFromUrl("https://api....");
return JSONObject.getString("station");
}


JSONParser (AsyncTask< String, Void, String >)

protected String doInBackground(); ==> Seperate thread
protected void onPostExecute(); ==> On GUI thread

I was thinking: --- Put the HTTPRequest in doInBackground();

Problem is I'm not sure how to: get the JSONParser to return the JSONObject to the getStation method?

What I need to know

=> Where should I return the JSONObject: in background or execute?

=> How do I use the JSONParser once it's an AsyncTask? Will the execute() function return the value?

=> AsyncTask< String, Void, String > ==> How does this work? It's the return type?

Thanks a lot!

解决方案

FAQs and general explaination of the usage of AsyncTask

=> Where should I do network operations? Where should I return my aquired values?

In general, you should do Network Operations in a Seperate Thread -> doInBackground(); since you do not want your UI to freeze when a Network Operation takes its time. So you should connect to your Service or .php script or wherever you get the Data from inside the doInBackground() method. Then you could also parse the data there and return the parsed data from the doInBackground() method by specifying the return type of doInBackground() to your desires, more about that down there. The onPostExecute() method will then receive your returned values from doInBackground() and represent them using the UI.

=> AsyncTask< String, Integer, Long> ==> How does this work?

In general, the AsyncTask class looks like this, which is nothing more than a generic class with 3 different generic types:

AsyncTask<Params, Progress, Result>

You can specify the type of Parameter the AsyncTask takes, the Type of the Progress indicator and the type of the result (the return type of doInBackGround()).

Here is an Example of an AsyncTask looking like this:

AsyncTask<String, Integer, Long>

We have type String for the Parameters, Type Integer for the Progress and Type Long for the Result (return type of doInBackground()). You can use any type you want for Params, Progress and Result.

private class DownloadFilesTask extends AsyncTask<String, Integer, Long> {

 // these Strings / or String are / is the parameters of the task, that can be handed over via the excecute(params) method of AsyncTask
 protected Long doInBackground(String... params) {

    String param1 = params[0];
    String param2 = params[1];
    // and so on...
    // do something with the parameters...
    // be careful, this can easily result in a ArrayIndexOutOfBounds exception
    // if you try to access more parameters than you handed over

    long someLong;
    int someInt;

    // do something here with params
    // the params could for example contain an url and you could download stuff using this url here

    // the Integer variable is used for progress
    publishProgress(someInt);

    // once the data is downloaded (for example JSON data)
    // parse the data and return it to the onPostExecute() method
    // in this example the return data is simply a long value
    // this could also be a list of your custom-objects, ...
    return someLong;
 }

 // this is called whenever you call puhlishProgress(Integer), for example when updating a progressbar when downloading stuff
 protected void onProgressUpdate(Integer... progress) {
     setProgressPercent(progress[0]);
 }

 // the onPostexecute method receives the return type of doInBackGround()
 protected void onPostExecute(Long result) {
     // do something with the result, for example display the received Data in a ListView
     // in this case, "result" would contain the "someLong" variable returned by doInBackground();
 }
}

=> How to use AsyncTask? How can I "call" it? How can I "execute" it?

In this case, the AsyncTask takes a String or String Array as a Parameter which will look like this once the AsyncTask is called: (The specified parameter is used in the execute(param) method of AsyncTask).

new DownloadFilesTask().execute("Somestring"); // some String as param

Be aware, that this call does not have a return value, the only return value you should use is the one returned from doInBackground(). Use the onPostExecute() method do make use of the returned value.

Also be careful with this line of code: (this execution will actually have a return value)

long myLong = new DownloadFilesTask().execute("somestring").get();

The .get() call causes the UI thread to be blocked (so the UI freezes if the operation takes longer than a few millisecons) while the AsyncTask is executing, because the execution does not take place in a separate thread. If you remove the call to .get() it will perform asynchronously.

=> What does this notation "execute(String... params)" mean?

This is a method with a so called "varargs" (variable arguments) parameter. To keep it simple, I will just say that it means that the actual number of values you can pass on to the method via this parameter is not specified, and any amount of values you hand to the method will be treated as an array inside the method. So this call could for example look like this:

execute("param1");

but it could however also look like this:

execute("param1", "param2");

or even more parameters. Assuming we are still talking about AsyncTask, the parameters can be accessed in this way in the doInBackground(String... params) method:

 protected Long doInBackground(String... params) {

     String str1 = params[0];
     String str2 = params[1]; // be careful here, you can easily get an ArrayOutOfBoundsException

     // do other stuff
 }

You can read more about AsyncTask here: http://developer.android.com/reference/android/os/AsyncTask.html

Also take a look at this AsyncTask example: https://stackoverflow.com/a/9671602/1590502

这篇关于如何使用异步任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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