AsyncTaskAndroid示例

我正在阅读关于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>
1052439 次浏览

好的,您正在尝试通过另一个线程访问GUI。这主要不是很好的做法。

在另一个线程中执行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
}
}
}

我确信它正在正确执行,但您正在尝试更改后台线程中的UI元素,这是行不通的。

修改您的call和AsyncOrder如下:

呼叫类

备注:我个人建议使用onPostExecute()无论你在哪里执行你的AsyncTeam线程,而不是在扩展AsyncTeam本身的类中。我认为它使代码更易于阅读,特别是如果你需要在多个地方处理结果略有不同。

new LongThread() {
@Override public void onPostExecute(String result) {
TextView txt = (TextView) findViewById(R.id.output);
txt.setText(result);
}
}.execute("");

LongThread类(扩展Async任务):

@Override
protected String doInBackground(String... params) {
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}


return "Executed";
}

移动这两行:

TextView txt = (TextView) findViewById(R.id.output);
txt.setText("Executed");

从AsyncStory的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);
}
}

简单地说:

LongOperation MyTask = new LongOperation();
MyTask.execute();

这里的概念和代码

我创建了一个使用Android的Async任务的简单示例。它以onPreExecute(), doInBackground(), publishProgress()开头,最后是onProgressUpdate()

在这种情况下,doIn背景()作为后台线程工作,而其他线程在UI线程中工作。你不能访问doIn背景()中的UI元素。序列与我提到的相同。

但是,如果您需要从doInBackground更新任何小部件,您可以从doInBackground调用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();

开发者参考这里

执行异步任务时,任务会经历四个步骤:

  1. onPreExecute()//执行前是否执行
  2. 在后台执行(参数…)
  3. 关于进度更新(进度…)
  4. 执行后(结果)

下面是一个demo示例:

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

您需要声明按钮onclicklistener。单击后,它会调用Async任务类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();
}


}

我建议使用这个库进行背景工作,让你的生活更轻松:

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

我的完整答案是这里,但这里有一张解释性图片来补充本页上的其他答案。对我来说,理解所有变量的去向是一开始最令人困惑的部分。

在此处输入图片描述

当您在工作线程中时,您不能直接操作Android上的UI元素。

当您使用AsyncTeam时,请了解回调方法。

例如:

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()方法中设置您的文本视图。

更改您的代码,如下所示:

@Override
protected void onPostExecute(String result) {


runOnUiThread(new Runnable() {
public void run() {
TextView txt = (TextView) findViewById(R.id.output);
txt.setText("Executed");
}
});
}

背景/理论

异步任务允许您在后台线程上运行任务,同时将结果发布到UI线程。

用户应该始终能够与应用程序进行交互,因此它很重要 避免阻塞主(UI)线程与任务,如 从网上下载内容。

这就是为什么我们使用AsyncTask

它通过包装UI线程消息队列和处理程序,允许您发送和处理来自其他线程的可运行对象和消息提供了一个简单的界面。

实施

异步任务是一个泛型类。(它在其构造函数中采用参数化类型。)

它使用这些三种泛型类型:

Params-执行时发送到任务的参数类型。

Progress-在后台计算期间发布的进度单元的类型。

Result-后台计算结果的类型。

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

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

这三个参数对应三个主要功能可以在AsyncTask中覆盖:

  • doInBackground(Params...)
  • onProgressUpdate(Progress...)
  • onPostExecute(Result)

执行异步任务

  • 使用要发送到后台任务的参数调用execute()

发生了什么

  1. 主/UI线程上,调用onPreExecute()

    • 初始化此线程中的某些内容。(例如,在用户交互界面上显示进度条。)
  2. 后台线程上,调用doInBackground(Params...)

    • Params通过execute传递。)
    • 长时间运行的任务应该发生在哪里。
    • 必须至少重写doInBackground()才能使用Async任务。

    • 调用publishProgress(Progress...)更新用户交互界面,显示进度(例如UI动画或打印的日志文本),同时后台计算仍在执行。

      • 导致onProgressUpdate()被调用。
  3. 后台线程上,从doInBackground()返回结果。

    • (这将触发下一步。
  4. main/UI线程上,使用返回的结果调用onPostExecute()

示例

在这两个示例中,“阻止任务”都是从Web下载。

  • 例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);

带进度的示例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();
}
}
}

如何记住在AsyncTeam中使用的参数?

不要

如果您不熟悉AsyncTeam,那么在编写AsyncTeam时感到困惑是很常见的。主要罪魁祸首是AsyncTeam中使用的参数,即AsyncTask<A, B, C>。基于方法的A, B, C(论据)签名不同,这使得事情更加混乱。

保持简单!

关键是不要记住。如果你能可视化你的任务真正需要做什么,那么在第一次尝试时用正确的签名编写AsyncTeam将是小菜一碟。只要弄清楚你的InputProgressOutput是什么,你就可以开始了。

那么,什么是异步任务呢?

AsyncTeam是在后台线程中运行的后台任务。它接受Input,执行Progress并给出Output

AsyncTask<Input, Progress, Output>

例如:

在此处输入图片描述

跟方法有什么关系

AsyncTaskdoInBackground()之间

在此处输入图片描述

doInBackground()onPostExecute(),onProgressUpdate()'也是 相关

在此处输入图片描述

如何在代码中编写它?

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");

异步任务

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

在使用AsyncTeam时,有必要创建一个类后继者,并在其中注册我们所需的方法的实现。在本课中,我们将研究三种方法:

背景信息-将在新线程中执行,在这里我们解决了所有困难的任务。因为非主线程无权访问UI。

onPreExecute-在doIn背景之前执行并有权访问UI

onPostExecute-在doIn后台之后执行(如果AsyncTask-在接下来的课程中关于这一点-不起作用)并且可以访问UI。

这是MyAsyncTarget类:

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

这是如何调用你的活动或片段:

MyAsyncTask myAsyncTask = new MyAsyncTask();
myAsyncTask.execute();

如果你打开AsyncTeam类,你可以看到下面的代码。

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) {
}
}

异步任务功能

  1. AsyncTarget是抽象类
  2. AsyncTeam有3个泛型参数。
  3. Async的抽象方法有doIn背景、onPreExecute、onPostExecute
  4. doIn后台是WorkerThread(你不能更新UI)
  5. onPreExecute是主线程
  6. 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();
}

更新:2020年3月

根据Android开发人员官方留档的说法,现在不建议使用AsyncTeam。

建议改用kotlin corourines。简单地说,它允许您以顺序样式编写异步任务。