Die Anleitung zu Android AsyncTask
View more Tutorials:
Die Klasse AsyncTask wurde seit API Level 3 in Android eingeführt, um einen Standard für die einfache Arbeit mit UI Thread.

Normalerweise wird AsyncTask verwendet, um eine Aufgabe im Hintergrund der Anwendung auszuführen und den Status dieser Aufgabe in die Interface während der Aufgabenerledigung zu aktualisieren.
In einigen Fällen verwenden Sie UI um mit AsyncTask zu interagieren, was einige Risiken bringt. Insbesondere kann dies zu Kontextlecks, verpassten callback oder Abstützen bei Konfigurationsänderungen führen (z.B der Benutzer dreht den Bildschirm vom Gerät). Es hat auch ein inkonsistentes Verhalten auf verschiedenen Versionen der Platform, verschluckt die Ausnahmen aus doInBackground und bietet nicht viel Nutzen bei der direkten Verwendung von Executor .
AsyncTask wurde als Hilfsklasse für Thread und Handler. Es sollte für kurze Aktivitäten (innerhalb einiger Sekunden). Wenn ein Thread längere Zeit ausgeführt werden soll, sollten Sie die von java.util.concurrent bereitgestellten Klassen wie Executor, ThreadPoolExecutor und FutureTask.
AsyncTask wurde seit API Level 3 in Android eingeführt und seit API Level 30 (Ạndroid 11) als veraltet markiert.
Android AsyncTask Javadocs:Sehen Sie mehr:
In diesem Beispiel verwenden wir die AsyncTask, um eine Aufgabe im Hintergrund der Anwendung auszuführen und um den Status der Aufgabe in der Interface während ihres Betriebs zu aktualisieren.

Im Android Studio erstellen Sie ein neues Projekt:
- File > New > New Project > Empty Activity
- Name: AsyncTaskExample
- Package name: org.o7planning.asynctaskexample
- Language: Java
Die Interface der Anwendung:

main_activity.xml
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <ProgressBar android:id="@+id/progressBar" style="?android:attr/progressBarStyleHorizontal" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginLeft="16dp" android:layout_marginTop="32dp" android:layout_marginEnd="16dp" android:layout_marginRight="16dp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <TextView android:id="@+id/textView_info" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginLeft="16dp" android:layout_marginTop="16dp" android:layout_marginEnd="16dp" android:layout_marginRight="16dp" android:gravity="center" android:text="Working info" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/progressBar" /> <Button android:id="@+id/button_start" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="24dp" android:text="Click to Start" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView_info" /> <Button android:id="@+id/button_cancel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:text="Cancel" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/button_start" /> </androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java
package org.o7planning.asynctaskexample; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ProgressBar; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private ProgressBar progressBar; private TextView textViewInfo; private Button buttonStart; private Button buttonCancel; private MyWorkTask myWorkTask; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); this.progressBar = (ProgressBar) this.findViewById(R.id.progressBar); this.textViewInfo = (TextView) this.findViewById(R.id.textView_info); this.buttonStart = (Button) this.findViewById(R.id.button_start); this.buttonCancel = (Button) this.findViewById(R.id.button_cancel); this.buttonStart.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startWork(); } }); this.buttonCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { requestCancel(); } }); } private void startWork() { this.myWorkTask = new MyWorkTask(this.progressBar, this.textViewInfo, this.buttonStart, this.buttonCancel); ParamInfo param = new ParamInfo("Param 1", "Param 2"); this.myWorkTask.execute(param); } private void requestCancel() { if(this.myWorkTask != null) { this.myWorkTask.cancel(true); } } }

MyWorkTask.java
package org.o7planning.asynctaskexample; import android.os.AsyncTask; import android.os.SystemClock; import android.widget.Button; import android.widget.ProgressBar; import android.widget.TextView; import java.util.Date; // <Params, Progress, Result> public class MyWorkTask extends AsyncTask<ParamInfo, ProgressInfo, ResultInfo> { private final ProgressBar progressBar; private final TextView textViewInfo; private final Button buttonStart; private final Button buttonCancel; private final int PROGRESS_MAX; private int workCount = 0; private long startTimeInMillis; public MyWorkTask(ProgressBar progressBar, TextView textViewInfo, Button buttonStart, Button buttonCancel) { this.progressBar = progressBar; this.textViewInfo = textViewInfo; this.buttonStart = buttonStart; this.buttonCancel = buttonCancel; this.PROGRESS_MAX = this.progressBar.getMax(); } @Override protected void onPreExecute() { this.progressBar.setVisibility(ProgressBar.VISIBLE); this.textViewInfo.setText("Start..."); this.buttonStart.setEnabled(false); this.buttonCancel.setEnabled(true); this.startTimeInMillis = new Date().getTime(); } @Override protected ResultInfo doInBackground(ParamInfo... params) { final int WORK_MAX = 30; while (this.workCount < WORK_MAX) { SystemClock.sleep(100); // 100 Milliseconds. this.workCount++; int progress = (this.workCount * PROGRESS_MAX) / WORK_MAX; // Progress value. int percent = (progress * 100) / PROGRESS_MAX; String info = "(" + percent +"%) - Working part " + this.workCount + " of " + WORK_MAX; ProgressInfo progressInfo = new ProgressInfo(progress, info); this.publishProgress(progressInfo); // Progress ...values } long finishTimeInMillis = new Date().getTime(); long workTimeInMillis = finishTimeInMillis - this.startTimeInMillis; ResultInfo result = new ResultInfo(true, workTimeInMillis); return result; } @Override protected void onProgressUpdate(ProgressInfo... values) { // Progress ...values ProgressInfo progressInfo= values[0]; int progress = progressInfo.getProgress(); this.progressBar.setProgress(progress); this.textViewInfo.setText(progressInfo.getWorkingInfo()); } @Override protected void onPostExecute(ResultInfo resultInfo) { super.onPostExecute(resultInfo); this.buttonStart.setEnabled(true); this.buttonCancel.setEnabled(false); this.textViewInfo.setText(resultInfo.getMessage()); } @Override protected void onCancelled(ResultInfo resultInfo) { super.onCancelled(resultInfo); this.buttonStart.setEnabled(true); this.buttonCancel.setEnabled(false); this.textViewInfo.setText(resultInfo.getMessage()); } }
ParamInfo.java
package org.o7planning.asynctaskexample; public class ParamInfo { private String param1; private String param2; public ParamInfo(String param1, String param2) { this.param1 = param1; this.param2 = param2; } public String getParam1() { return param1; } public String getParam2() { return param2; } }
ProgressInfo.java
package org.o7planning.asynctaskexample; public class ProgressInfo { private int progress; private String workingInfo; public ProgressInfo(int progress, String workingInfo) { this.progress = progress; this.workingInfo = workingInfo; } public int getProgress() { return progress; } public String getWorkingInfo() { return workingInfo; } }
ResultInfo.java
package org.o7planning.asynctaskexample; public class ResultInfo { private boolean completed; private long workTimeInMillis; public ResultInfo(boolean completed, long workTimeInMillis) { this.completed = completed; this.workTimeInMillis = workTimeInMillis; } public boolean isCompleted() { return completed; } public long getWorkTimeInMillis() { return workTimeInMillis; } public String getMessage() { if(this.completed) { return "Complete in " + this.workTimeInMillis +" milliseconds"; } return "Failed or cancelled"; } }