如何使用的AsyncTask如何使用、AsyncTask

2023-09-12 22:58:35 作者:你负责貌美如花我负责养你

AsyncTask的问题

我跟着一些教程,但它仍然是我不清楚。这里的code我目前有以下code一些问题。 MainActivity调用SomeClassWithHTTPNeeds,然后调用JSONParser(AsyncTask的<>)

MainActivity:

 字符串站= SomeClassWithHTTPNeeds.getInstance()getStation(123)。
 

SomeClassWithHTTPNeeds:

  getStation {

JSONParser =新JSONParser();
的JSONObject站= parser.getJSONFromUrl(https://开头API ......);
返回JSONObject.getString(站);
}
 

JSONParser(AsyncTask的<字符串,太虚,字符串>)

 保护字符串doInBackground(); ==>单独的线程
保护无效onPostExecute(); ==>在GUI线程
 
AsyncTask2

我在想: ---把HTT prequest在doInBackground();

但问题是我不知道如何: 获得JSONParser到的JSONObject返回getStation方法?

我需要知道

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

=>如何使用JSONParser一旦它是一个AsyncTask的?请问执行()函数返回值?

=>的AsyncTask<字符串,太虚,String>的==>这是如何工作的?它的返回类型?

非常感谢!

解决方案

常见问题解答和的AsyncTask的用法一般的解释

  

=>我应该在哪里做的网络操作?我应该在哪里回我获得性价值?

在一般情况下,你应该做的网络运营中的单独的线程 - > doInBackground(); ,因为你不希望你的UI冻结时,网络操作需要的时间。所以,你应该连接到您的服务或.PHP脚本或无论你从 doInBackground()方法中获取数据。那么你也可以解析数据存在,并通过指定的返回类型从 doInBackground()方法返回所分析的数据doInBackground()来你的欲望,更多的是出现了下滑。那么 onPostExecute()方法从收到返回的值doInBackground(),并使用重present他们用户界面。

  

=>的AsyncTask<字符串,整数,长> ==>这是如何工作的?

在一般情况下,的AsyncTask 类看起来是这样的:

 的AsyncTask< PARAMS,进展,结果>
 

  

您可以指定参数类型的的AsyncTask 需要,进度指示器的类型和结果类型(返回类型   的doInBackGround())。

下面是一个为例的AsyncTask 寻找这样的:

 的AsyncTask<字符串,整数,龙>
 

我们有String类型的参数,类型整型的进步和长型的结果(的返回类型doInBackground())。 您可以用您想用PARAMS,进展和成效的任何类型的。

 私有类DownloadFilesTask扩展的AsyncTask<字符串,整数,龙> {

 //这些字符串/或串是/是任务的参数,可通过的AsyncTask的excecute(PARAMS)方法被移交
 保护龙doInBackground(字符串... PARAMS){

    串参数1 = PARAMS [0];
    串param2的= PARAMS [1];
    // 等等...
    //做一些与参数...
    //要小心,这很容易导致ArrayIndexOutOfBounds异常情况
    //如果您尝试访问更多的参数比你交给

    长someLong;
    INT someInt;

    //做点什么这里PARAMS
    //在PARAMS例如可以包含一个URL,你可以在这里使用这个网址下载的东西

    //整型变量用于进展
    publishProgress(someInt);

    //一旦数据被下载(例如JSON数据)
    //解析数据,并将其返回到onPostExecute()方法
    //在本实施例的返回数据是一个简单的长值
    //这也可能是您的自定义对象的列表,...
    返回someLong;
 }

 //每当你在下载东西时更新进度条时调用puhlishProgress(整数),例如,这就是所谓的
 保护无效onProgressUpdate(整数...进度){
     setProgressPercent(进展[0]);
 }

 //该onPostexecute方法接收doInBackGround的返回类型()
 保护无效onPostExecute(长效){
     //做一些事情的结果,例如在ListView显示接收到的数据
     //在这种情况下,结果将包含由doInBackground退货someLong变量();
 }
}
 

  

=>如何使用AsyncTask的?我怎么能叫了吗?我如何执行了吗?

在这种情况下,AsyncTask的需要一个字符串或字符串数​​组作为参数这将是这样的,一旦AsyncTask的被称为:(指定的参数用于执行(参数的AsyncTask的)方法)。

 新DownloadFilesTask()执行(Somestring); //一些String作为参数
 

要知道,这个调用的没有返回值,你应该使用唯一的返回值是从 doInBackground()。 使用的onPostExecute()方法做利用返回的值。的

另外要小心这行code:(此执行,实际上有一个返回值)

 长myLong =新DownloadFilesTask()执行(somestring)得到()。
 

的获得()调用导致UI线程被阻塞(这样的UI冻结如果操作时间超过几millisecons),而AsyncTask的执行时,因为执行不发生在一个单独的线程。 如果您删除调用获得(),它会执行异步。

  

=>这是什么符号执行(字符串... PARAMS)是什么意思?

要保持它的简单,我只想说,这意味着实际的未指定的参数个数,你可以传递给方法。所以,这个调用例如可以是这样的:

 执行(参数1);
 

但它可能但是也可以是这样的:

 执行(参数1,参数2);
 

或甚至更多的参数。假设我们还在谈论的AsyncTask ,该参数可以通过这种方式在 doInBackground访问(字符串... PARAMS)方法:

 保护龙doInBackground(字符串... PARAMS){

     串STR1 = PARAMS [0];
     串STR2 = PARAMS [1]; //这里要小心,你可以很容易地得到一个ArrayOutOfBoundsException

     //做其他的东西
 }
 

您可以阅读更多有关AsyncTask的位置:http://developer.android.com/reference/android/os/AsyncTask.html

另外看看这个AsyncTask的例子: http://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:

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?

To keep it simple, I will just say that it means that the actual number of parameters you can pass on to the method is not specified. 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: http://stackoverflow.com/a/9671602/1590502