我正在阅读有关 AsyncTask
的内容,并尝试了下面的简单程序。但这似乎不起作用。我怎样才能让它工作?
public class AsyncTaskActivity extends Activity {
Button btn;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener((OnClickListener) this);
}
public void onClick(View view){
new LongOperation().execute("");
}
private class LongOperation extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
for(int i=0;i<5;i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
TextView txt = (TextView) findViewById(R.id.output);
txt.setText("Executed");
return null;
}
@Override
protected void onPostExecute(String result) {
}
@Override
protected void onPreExecute() {
}
@Override
protected void onProgressUpdate(Void... values) {
}
}
}
我只是想在后台进程 5 秒后更改标签。
这是我的 main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:indeterminate="false"
android:max="10"
android:padding="10dip">
</ProgressBar>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Progress" >
</Button>
<TextView android:id="@+id/output"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Replace"/>
</LinearLayout>
AsyncTask
已折旧。请参阅文档:public abstract class AsyncTask
我的完整答案是 here,但这里有一张解释性图片来补充此页面上的其他答案。对我来说,了解所有变量的去向是一开始最令人困惑的部分。
https://i.stack.imgur.com/ytin1.png
好的,您正在尝试通过另一个线程访问 GUI。总的来说,这不是好的做法。
AsyncTask 在另一个线程内执行 doInBackground()
中的所有内容,该线程无权访问您的视图所在的 GUI。
preExecute()
和 postExecute()
在此新线程中发生繁重工作之前和之后为您提供对 GUI 的访问,您甚至可以将长操作的结果传递给 postExecute()
以显示任何处理结果。
请参阅稍后更新 TextView 的这些行:
TextView txt = findViewById(R.id.output);
txt.setText("Executed");
将它们放入 onPostExecute()
。
然后,您将看到在 doInBackground
完成后更新的 TextView 文本。
我注意到您的 onClick 侦听器不会检查已选择的视图。我发现最简单的方法是通过 switch 语句。我在下面编辑了一个完整的课程,其中包含所有避免混淆的建议。
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings.System;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.view.View.OnClickListener;
public class AsyncTaskActivity extends Activity implements OnClickListener {
Button btn;
AsyncTask<?, ?, ?> runningTask;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = findViewById(R.id.button1);
// Because we implement OnClickListener, we only
// have to pass "this" (much easier)
btn.setOnClickListener(this);
}
@Override
public void onClick(View view) {
// Detect the view that was "clicked"
switch (view.getId()) {
case R.id.button1:
if (runningTask != null)
runningTask.cancel(true);
runningTask = new LongOperation();
runningTask.execute();
break;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
// Cancel running task(s) to avoid memory leaks
if (runningTask != null)
runningTask.cancel(true);
}
private final class LongOperation extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... params) {
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// We were cancelled; stop sleeping!
}
}
return "Executed";
}
@Override
protected void onPostExecute(String result) {
TextView txt = (TextView) findViewById(R.id.output);
txt.setText("Executed"); // txt.setText(result);
// You might want to change "executed" for the returned string
// passed into onPostExecute(), but that is up to you
}
}
}
btn.setOnClickListener(this);
Eclipse报错-----“View类型中的方法setOnClickListener(View.OnClickListener)不适用于参数(AsyncTaskActivity)”
onPostExecute(String result)
方法中获取参数。这将使未来的读者更清楚该参数由 doInBackground(String... params)
的返回值填充。
我确定它执行正确,但您试图更改后台线程中的 UI 元素,但这是行不通的。
修改您的呼叫和 AsyncTask 如下:
调用类
注意:我个人建议在执行 AsyncTask 线程的任何地方使用 onPostExecute()
,而不是在扩展 AsyncTask 本身的类中。我认为它使代码更易于阅读,特别是如果您需要在多个地方使用 AsyncTask 处理的结果略有不同。
new LongThread() {
@Override public void onPostExecute(String result) {
TextView txt = (TextView) findViewById(R.id.output);
txt.setText(result);
}
}.execute("");
LongThread 类(扩展 AsyncTask):
@Override
protected String doInBackground(String... params) {
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return "Executed";
}
onPostExecute
非常棒。
概念和代码在这里
我创建了一个使用 Android 的 AsyncTask 的简单示例。它从 onPreExecute(), doInBackground(), publishProgress()
开始,最后是 onProgressUpdate()
。
在此,doInBackground() 作为后台线程工作,而其他工作在 UI 线程中。您无法访问 doInBackground() 中的 UI 元素。顺序和我提到的一样。
但是,如果您需要从 doInBackground
更新任何小部件,您可以从 doInBackground
publishProgress
调用 onProgressUpdate
来更新您的 UI 小部件。
class TestAsync extends AsyncTask<Void, Integer, String> {
String TAG = getClass().getSimpleName();
protected void onPreExecute() {
super.onPreExecute();
Log.d(TAG + " PreExceute","On pre Exceute......");
}
protected String doInBackground(Void...arg0) {
Log.d(TAG + " DoINBackGround", "On doInBackground...");
for (int i=0; i<10; i++){
Integer in = new Integer(i);
publishProgress(i);
}
return "You are at PostExecute";
}
protected void onProgressUpdate(Integer...a) {
super.onProgressUpdate(a);
Log.d(TAG + " onProgressUpdate", "You are in progress update ... " + a[0]);
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.d(TAG + " onPostExecute", "" + result);
}
}
在您的活动中这样称呼它:
new TestAsync().execute();
移动这两行:
TextView txt = (TextView) findViewById(R.id.output);
txt.setText("Executed");
从您的 AsyncTask 的 doInBackground
方法中取出并将它们放入 onPostExecute
方法中。您的 AsyncTask
应如下所示:
private class LongOperation extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
try {
Thread.sleep(5000); // no need for a loop
} catch (InterruptedException e) {
Log.e("LongOperation", "Interrupted", e);
return "Interrupted";
}
return "Executed";
}
@Override
protected void onPostExecute(String result) {
TextView txt = (TextView) findViewById(R.id.output);
txt.setText(result);
}
}
AsyncTask
的报告结果;并将一个值从服务发送到其他讨论地址的 ui 线程。这些问题是独立的。
如何记住 AsyncTask 中使用的参数?
别
如果您是 AsyncTask 的新手,那么在编写 AsyncTask 时很容易感到困惑。罪魁祸首是AsyncTask中使用的参数,即AsyncTask<A, B, C>
。基于 A、B、C(参数) 签名的方法不同,这使事情变得更加混乱。
把事情简单化!
关键是不要死记硬背。如果您可以想象您的任务真正需要做什么,那么在第一次尝试时使用正确的签名编写 AsyncTask 将是小菜一碟。只需弄清楚您的 Input
、Progress
和 Output
是什么,您就可以开始了。
那么什么是 AsyncTask?
AsyncTask 是在后台线程中运行的后台任务。它需要一个 Input
,执行 Progress
并给出一个 Output
。
即,AsyncTask。
例如:
https://i.stack.imgur.com/uaRqY.png
与方法有什么关系?
在 AsyncTask 和 doInBackground() 之间
https://i.stack.imgur.com/IE6tI.png
doInBackground() 和 onPostExecute(),onProgressUpdate()` 也有关系
https://i.stack.imgur.com/4VITv.png
怎么写在代码里?
DownloadTask extends AsyncTask<String, Integer, String>{
// Always same signature
@Override
public void onPreExecute()
{}
@Override
public String doInbackGround(String... parameters)
{
// Download code
int downloadPerc = // Calculate that
publish(downloadPerc);
return "Download Success";
}
@Override
public void onPostExecute(String result)
{
super.onPostExecute(result);
}
@Override
public void onProgressUpdate(Integer... parameters)
{
// Show in spinner, and access UI elements
}
}
您将如何运行此任务?
new DownLoadTask().execute("Paradise.mp3");
背景/理论
AsyncTask 允许您在后台线程上运行任务,同时将结果发布到 UI 线程。
用户应该始终能够与应用程序交互,因此避免阻塞主 (UI) 线程与从 Web 下载内容等任务非常重要。这就是我们使用 AsyncTask 的原因。它通过包装 UI 线程消息队列和处理程序提供了一个简单的界面,允许您发送和处理来自其他线程的可运行对象和消息。
执行
AsyncTask 是一个泛型类。 (它在其构造函数中采用参数化类型。)
它使用这三种通用类型:
Params
- 执行时发送给任务的参数类型。
Progress
- 在后台计算期间发布的进度单元的类型。
Result
- 后台计算结果的类型。
并非所有类型都始终由异步任务使用。要将类型标记为未使用,只需使用类型 Void: private class MyTask extends AsyncTask
这三个参数对应于三个主要函数,您可以在 AsyncTask
中覆盖:
doInBackground(参数...)
onProgressUpdate(进度...)
onPostExecute(结果)
执行 AsyncTask
使用要发送到后台任务的参数调用 execute()。
怎么了
在主/UI 线程上,调用 onPreExecute()。在这个线程中初始化一些东西。 (例如,在用户界面上显示进度条。)在后台线程上,调用 doInBackground(Params...)。 (参数是通过执行传递的。)长时间运行的任务应该发生在哪里。必须至少覆盖 doInBackground() 才能使用 AsyncTask。调用 publishProgress(Progress...) 以在后台计算仍在执行时更新用户界面并显示进度(例如 UI 动画或打印的日志文本)。导致 onProgressUpdate() 被调用。在后台线程上,从 doInBackground() 返回一个结果。 (这会触发下一步。)在主/UI 线程上,使用返回的结果调用 onPostExecute()。
例子
在这两个示例中,“阻塞任务”都是从网络下载的。
示例 A 下载图像并将其显示在 ImageView 中,而
示例 B 下载了一些文件。
示例 A
doInBackground()
方法下载图像并将其存储在 BitMap 类型的对象中。 onPostExecute()
方法获取位图并将其放置在 ImageView 中。
class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bitImage;
public DownloadImageTask(ImageView bitImage) {
this.bitImage = bitImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mBmp = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mBmp = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mBmp;
}
protected void onPostExecute(Bitmap result) {
bitImage.setImageBitmap(result);
}
}
示例 B
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
示例 B 执行
new DownloadFilesTask().execute(url1, url2, url3);
当一个异步任务被执行时,任务会经过四个步骤:
onPreExecute() doInBackground(Params...) onProgressUpdate(Progress...) onPostExecute(Result)
下面是一个演示示例:
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled())
break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
一旦你创建了一个任务,就会非常简单地执行:
new DownloadFilesTask().execute(url1, url2, url3);
仅以异步方式执行某些操作的最短示例:
class MyAsyncTask extends android.os.AsyncTask {
@Override
protected Object doInBackground(Object[] objects) {
// Do something asynchronously
return null;
}
}
要运行它:
(new MyAsyncTask()).execute();
当你在工作线程中时,你不能直接操作 Android 上的 UI 元素。
当您使用 AsyncTask 时,请了解回调方法。
例如:
public class MyAyncTask extends AsyncTask<Void, Void, Void>{
@Override
protected void onPreExecute() {
// Here you can show progress bar or something on the similar lines.
// Since you are in a UI thread here.
super.onPreExecute();
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
// After completing execution of given task, control will return here.
// Hence if you want to populate UI elements with fetched data, do it here.
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
// You can track you progress update here
}
@Override
protected Void doInBackground(Void... params) {
// Here you are in the worker thread and you are not allowed to access UI thread from here.
// Here you can perform network operations or any heavy operations you want.
return null;
}
}
仅供参考:要从工作线程访问 UI 线程,您可以在视图上使用 runOnUiThread() 方法或 post 方法。
例如:
runOnUiThread(new Runnable() {
textView.setText("something.");
});
or
yourview.post(new Runnable() {
yourview.setText("something");
});
这将帮助您更好地了解事情。因此,在您的情况下,您需要在 onPostExecute() 方法中设置您的文本视图。
我建议您使用此库进行后台工作,让您的生活更轻松:
https://github.com/Arasthel/AsyncJobLibrary
就是这么简单...
AsyncJob.doInBackground(new AsyncJob.OnBackgroundJob() {
@Override
public void doOnBackground() {
startRecording();
}
});
带有 POST 请求的示例异步任务:
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("key1", "value1"));
params.add(new BasicNameValuePair("key1", "value2"));
new WEBSERVICEREQUESTOR(URL, params).execute();
class WEBSERVICEREQUESTOR extends AsyncTask<String, Integer, String>
{
String URL;
List<NameValuePair> parameters;
private ProgressDialog pDialog;
public WEBSERVICEREQUESTOR(String url, List<NameValuePair> params)
{
this.URL = url;
this.parameters = params;
}
@Override
protected void onPreExecute()
{
pDialog = new ProgressDialog(LoginActivity.this);
pDialog.setMessage("Processing Request...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
super.onPreExecute();
}
@Override
protected String doInBackground(String... params)
{
try
{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
HttpPost httpPost = new HttpPost(URL);
if (parameters != null)
{
httpPost.setEntity(new UrlEncodedFormEntity(parameters));
}
httpResponse = httpClient.execute(httpPost);
httpEntity = httpResponse.getEntity();
return EntityUtils.toString(httpEntity);
} catch (Exception e)
{
}
return "";
}
@Override
protected void onPostExecute(String result)
{
pDialog.dismiss();
try
{
}
catch (Exception e)
{
}
super.onPostExecute(result);
}
}
更新:2020 年 3 月
根据 Android 开发人员 official documentation 的说法,AsyncTask 现在已被弃用。
建议改用 kotlin corourines。简单地说,它允许您以顺序样式编写异步任务。
简单地:
LongOperation MyTask = new LongOperation();
MyTask.execute();
您需要在单击侦听器上声明按钮。单击后,它会调用 AsyncTask 类 DownloadJson。
该过程将如下所示:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new DownloadJson().execute();
}
});
}
// DownloadJSON AsyncTask
private class DownloadJson extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... params) {
newlist = new ArrayList<HashMap<String, String>>();
json = jsonParser.makeHttpRequest(json, "POST");
try {
newarray = new JSONArray(json);
for (int i = 0; i < countdisplay; i++) {
HashMap<String, String> eachnew = new HashMap<String, String>();
newobject = newarray.getJSONObject(i);
eachnew.put("id", newobject.getString("ID"));
eachnew.put("name", newobject.getString("Name"));
newlist.add(eachnew);
}
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void args) {
newlisttemp.addAll(newlist);
NewAdapterpager newadapterpager = new NewAdapterpager(ProcesssActivitypager.this, newlisttemp);
newpager.setAdapter(newadapterpager);
}
}
private class AsyncTaskDemo extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(false);
progressDialog.show();
}
@Override
protected Void doInBackground(Void... arg0) {
// Do code here
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
@Override
protected void onCancelled() {
super.onCancelled();
progressDialog.dismiss();
Toast toast = Toast.makeText(
getActivity(),
"An error is occurred due to some problem",
Toast.LENGTH_LONG);
toast.setGravity(Gravity.TOP, 25, 400);
toast.show();
}
}
在使用 AsyncTask 时,有必要创建一个类继承者并在其中注册我们所需的方法的实现。在本课中,我们将研究三种方法:
doInBackground - 将在一个新线程中执行,在这里我们解决了所有困难的任务。因为非主线程无权访问 UI。
onPreExecute - 在 doInBackground 之前执行并且可以访问 UI
onPostExecute - 在 doInBackground 之后执行(如果 AsyncTask 被取消,则不起作用 - 关于这一点在下一课中)并且可以访问 UI。
这是 MyAsyncTask 类:
class MyAsyncTask extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
tvInfo.setText("Start");
}
@Override
protected Void doInBackground(Void... params) {
// Your background method
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
tvInfo.setText("Finish");
}
}
这是调用 Activity 或 Fragment 的方法:
MyAsyncTask myAsyncTask = new MyAsyncTask();
myAsyncTask.execute();
异步任务:
public class MainActivity extends AppCompatActivity {
private String ApiUrl="your_api";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyTask myTask=new MyTask();
try {
String result=myTask.execute(ApiUrl).get();
Toast.makeText(getApplicationContext(),result,Toast.LENGTH_SHORT).show();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public class MyTask extends AsyncTask<String,Void,String>{
@Override
protected String doInBackground(String... strings) {
String result="";
HttpURLConnection httpURLConnection=null;
URL url;
try {
url=new URL(strings[0]);
httpURLConnection=(HttpURLConnection) url.openConnection();
InputStream inputStream=httpURLConnection.getInputStream();
InputStreamReader reader=new InputStreamReader(inputStream);
result=getData(reader);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
public String getData(InputStreamReader reader) throws IOException{
String result="";
int data=reader.read();
while (data!=-1){
char now=(char) data;
result+=data;
data=reader.read();
}
return result;
}
}
}
MyTask
在类 MainActivity
内?这是惯例吗?
带有进度的示例 AsyncTask 示例
import android.animation.ObjectAnimator;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
public class AsyncTaskActivity extends AppCompatActivity implements View.OnClickListener {
Button btn;
ProgressBar progressBar;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(this);
progressBar = (ProgressBar)findViewById(R.id.pbar);
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.button1:
new LongOperation().execute("");
break;
}
}
private class LongOperation extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... params) {
Log.d("AsyncTask", "doInBackground");
for (int i = 0; i < 5; i++) {
try {
Log.d("AsyncTask", "task "+(i + 1));
publishProgress(i + 1);
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.interrupted();
}
}
return "Completed";
}
@Override
protected void onPostExecute(String result) {
Log.d("AsyncTask", "onPostExecute");
TextView txt = (TextView) findViewById(R.id.output);
txt.setText(result);
progressBar.setProgress(0);
}
@Override
protected void onPreExecute() {
Log.d("AsyncTask", "onPreExecute");
TextView txt = (TextView) findViewById(R.id.output);
txt.setText("onPreExecute");
progressBar.setMax(500);
progressBar.setProgress(0);
}
@Override
protected void onProgressUpdate(Integer... values) {
Log.d("AsyncTask", "onProgressUpdate "+values[0]);
TextView txt = (TextView) findViewById(R.id.output);
txt.setText("onProgressUpdate "+values[0]);
ObjectAnimator animation = ObjectAnimator.ofInt(progressBar, "progress", 100 * values[0]);
animation.setDuration(1000);
animation.setInterpolator(new LinearInterpolator());
animation.start();
}
}
}
如果你打开 AsyncTask 类,你可以看到下面的代码。
public abstract class AsyncTask<Params, Progress, Result> {
@WorkerThread
protected abstract Result doInBackground(Params... params);
@MainThread
protected void onPreExecute() {
}
@SuppressWarnings({"UnusedDeclaration"})
@MainThread
protected void onPostExecute(Result result) {
}
}
异步任务功能
AsyncTask 是抽象类 AsyncTask 有 3 个通用参数。 AsyncTask 有 doInBackground、onPreExecute、onPostExecute 的抽象方法 doInBackground 是 WorkerThread(不能更新 UI) onPreExecute 是 MainThread onPostExecute 是 MainThread(可以更新 UI)
例子
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
AsyncTask<Void, Void, Post> asyncTask = new AsyncTask<Void, Void, Post>() {
@Override
protected Post doInBackground(Void... params) {
try {
ApiClient defaultClient = Configuration.getDefaultApiClient();
String authorization = "eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJleHAiOjE1ODIxMzM4MTB9.bA3Byc_SuB6jzqUGAY4Pyt4oBNg0VfDRctZ8-PcPlYg"; // String | JWT token for Authorization
ApiKeyAuth Bearer = (ApiKeyAuth) defaultClient.getAuthentication("Bearer");
Bearer.setApiKey(authorization);
PostApi apiInstance = new PostApi();
String id = "1"; // String | id
Integer commentPage = 1; // Integer | Page number for Comment
Integer commentPer = 10; // Integer | Per page number For Comment
Post result;
try {
result = apiInstance.apiV1PostsIdGet(id, authorization, commentPage, commentPer);
} catch (ApiException e) {
e.printStackTrace();
result = new Post();
}
return result;
} catch (Exception e) {
e.printStackTrace();
return new Post();
}
}
@Override
protected void onPostExecute(Post post) {
super.onPostExecute(post);
if (post != null) {
mEmailView.setText(post.getBody());
System.out.print(post);
}
}
};
asyncTask.execute();
}
更改您的代码,如下所示:
@Override
protected void onPostExecute(String result) {
runOnUiThread(new Runnable() {
public void run() {
TextView txt = (TextView) findViewById(R.id.output);
txt.setText("Executed");
}
});
}
params
是一个数组。 (在上面的示例中,它是一个String
数组。)这允许您传入多个相同类型的参数。然后您可以使用params[0]
、params[1]
、params[2]
等访问这些参数。在示例中,params
数组中只有一个String
。如果您需要传入多个不同类型的参数(例如,String
和int
),请参阅 this question。