当前位置: 首页 > 面试题库 >

如何使用AsyncTask

太叔志文
2023-03-14
问题内容

AsyncTask问题

我已经遵循了一些教程,但是对我来说仍然不清楚。这是我目前在代码下面有一些问题的代码。MainActivity调用SomeClassWithHTTPNeeds,然后调用JSONParser(AsyncTask
<>)

主要活动:

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

SomeClassWithHTTPNeeds:

getStation {

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

JSONParser(AsyncTask

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

我在想:—将HTTPRequest放在doInBackground();中。

问题是我不确定如何:获取JSONParser以将JSONObject返回到getStation方法?

我需要知道的

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

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

=> AsyncTask <字符串,无效,字符串> ==>这是如何工作的?是返回类型吗?

非常感谢!


问题答案:

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

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

通常,您应该在 单独的线程中 执行网络操作 - > doInBackground();

因为您不希望在网络操作花费时间时冻结UI。因此,您应该连接到Service或.php脚本,或者从doInBackground()方法内部获取数据的任何位置。然后,您还可以解析那里的数据,并doInBackground()通过指定所需的返回类型,从该方法返回经过解析的数据doInBackground(),更多有关该处的信息。onPostExecute()然后,该方法将从doInBackground()UI
接收您的返回值并表示它们。

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

通常,AsyncTask该类看起来像这样,只不过是具有3种不同泛型类型的泛型类:

AsyncTask<Params, Progress, Result>

您可以指定AsyncTaskTake 的Parameter
类型,Progress指示器的Type和结果的类型(doInBackGround()的返回类型)。

这是一个AsyncTask看起来像这样的例子:

AsyncTask<String, Integer, Long>

我们的参数类型为String,进度类型为Integer,结果类型为Long(返回类型doInBackground())。
您可以将任意类型用于参数,进度和结果。

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

=>如何使用AsyncTask?我该如何“打电话”呢?我如何“执行”它?

在这种情况下,AsyncTask将字符串或字符串数​​组作为 参数 ,一旦调用AsyncTask,它将看起来像这样:(在AsyncTask
的execute(param)方法中使用了指定的参数)。

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

请注意,此调用 没有返回值 ,您应该使用的唯一返回值是从返回的值doInBackground()
使用onPostExecute()方法 可以利用返回值。

还要注意以下代码行:(此执行实际上将有一个返回值)

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

执行AsyncTask时, .get()调用会导致UI线程被阻塞
(因此,如果操作花费的时间超过几个millisecons,则UI冻结),因为执行 不会 在单独的线程中进行。
如果删除对.get()的调用,它将异步执行。

=>此符号“ execute(String … params)”是什么意思?

这是带有所谓的“ varargs ”(可变参数)参数的方法。为简单起见,我只是说这意味着 未指定您可以通过此参数传递给方法 的实际
值的数量,并且您传递给该方法的 任何数量的值都将被视为数组中的一个数组。方法。因此,此调用可能看起来像这样:

execute("param1");

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

execute("param1", "param2");

甚至更多参数。假设我们仍在讨论AsyncTask,则可以在方法中以这种方式访问​​参数doInBackground(String... params)

 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
 }

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

还要看看这个AsyncTask示例:http://codingdict.com/questions/112231



 类似资料:
  • 问题内容: AsyncTask问题 我已经遵循了一些教程,但是对我来说仍然不清楚。这是我目前在代码下面有一些问题的代码。MainActivity调用SomeClassWithHTTPNeeds,然后调用JSONParser(AsyncTask <>) 主要活动: SomeClassWithHTTPNeeds: JSONParser(AsyncTask ) 我在想:—将HTTPRequest放在do

  • 如何使用

  • 将一段文档传入BeautifulSoup 的构造方法,就能得到一个文档的对象, 可以传入一段字符串或一个文件句柄. from bs4 import BeautifulSoup soup = BeautifulSoup(open("index.html")) soup = BeautifulSoup("<html>data</html>") 首先,文档被转换成Unicode,并且HTML的实例

  • 基础运用 Redis::set('user:profile:' . $id, "Swoft"); $userDesc = Redis::get('user:profile:' . $id); 你可以通过 Redis:: 调用任何 Redis 命令。Swoft 使用魔术方法将命令传递给 Redis 服务端,因此只需传递 Redis 命令所需的参数即可。示例: Redis::set('name',

  • 引入 WeUI.css文件 利用 vue init mpvue/mpvue-quickstart my-project 初始化一个 mpvue 项目,然后在 /src/main.js 中引入 weui.css 由于是在小程序中使用,于是就直接使用了 weiui-wxss 中的样式文件,官方提供的是 weui.wxss,因此手动转成了 weui.css,然后引入即可。 这里提供 weui.css 一

  • 将一段文档传入BeautifulSoup 的构造方法,就能得到一个文档的对象, 可以传入一段字符串或一个文件句柄. from bs4 import BeautifulSoup soup = BeautifulSoup(open("index.html")) soup = BeautifulSoup("<html>data</html>") 首先,文档被转换成Unicode,并且HTML的实例