gpt4 book ai didi

android - android中asyntask参数有什么区别?

转载 作者:太空狗 更新时间:2023-10-29 16:05:37 25 4
gpt4 key购买 nike

正如我的问题所说,我指的是 http://developer.android.com/reference/android/os/AsyncTask.html

它告诉我

  Asyntask <params, progress, result> 

但我没有使用进度。是按照你的安排说的吗?或者它有规则?

例如:

   class loadingdata extends AsyncTask<?,?,?>
protected void onPreExecute() {}
protected String doInBackground(String... args) {}
protected void onPostExecute() {}

所以我应该插入 3 参数作为

asyntask <void String void> ? 

或者它有一个规则

<preExecute, postExecute, doInBackground> or so fourth?

请帮助我,我是初学者,我不明白。

最佳答案

异步任务由 3 个通用类型定义,称为 Params、Progress 和 Result,以及 4 个步骤,称为 onPreExecutedoInBackgroundonProgressUpdateonPostExecute

AsyncTask 的通用类型:

异步任务使用的三种类型如下:

 Params -> the type of the parameters sent to the task upon execution.
Progress -> the type of the progress units published during the background computation.
Result -> the type of the result of the background computation.

并非所有类型都总是被异步任务使用。要将类型标记为未使用,只需使用类型 Void:

  private class MyTask extends AsyncTask<Void, Void, Void> { ... }

AsyncTask 并实现了 4 个方法:

<强>1。 doInBackground: 执行长时间运行操作的代码进入此方法。当点击按钮执行onClick方法时,它会调用execute方法,该方法接受参数并自动调用 传入参数的 doInBackground 方法。

<强>2。 onPostExecute:该方法在doInBackground方法处理完成后调用。 doInBackground 的结果传递给此方法。

<强>3。 onPreExecute:在调用doInBackground方法之前调用此方法。

<强>4。 onProgressUpdate:通过从 doInBackground 调用此方法的任何时间调用 publishProgress 来调用此方法。

     Overriding onPostExecute, onPreExecute and onProgressUpdate is optional.

要记住的要点:

 1. Instance of Async Task needs to be created in UI thread. As shown in  onClick method a new instance of LongOperation is created there. Also execute method with parameters should be called from UI thread.

2. Methods onPostExecute, onPreExecute and onProgressUpdate should not be explicitly called.

3. Task can be executed only once.

让我们看一个示例类 LongOperation,它扩展了下面的 AsyncTask:查看源代码打印?

   private class LongOperation extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
// perform long running operation operation
return null;
}
/* (non-Javadoc)
* @see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
@Override
protected void onPostExecute(String result) {
// execution of result of Long time consuming operation
}
/* (non-Javadoc)
* @see android.os.AsyncTask#onPreExecute()
*/
@Override
protected void onPreExecute() {
// Things to be done before execution of long running operation.
//For example showing ProgessDialog
}
/* (non-Javadoc)
* @see android.os.AsyncTask#onProgressUpdate(Progress[])
*/
@Override
protected void onProgressUpdate(Void... values) {
/* Things to be done while execution of long running operation
is in progress.
For example updating ProgessDialog */
}
}

关于android - android中asyntask参数有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15962929/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com