In this Tutorial we will learn, how to use the AsyncTask class, which makes it easier to do operations on a background thread and publish the results on the UI/main thread, without having to manipulate threads and handlers ourselves.
For this we will subclass Asynctask, define 3 generic types for the params, the progress and the result and override 4 methods:
onPreExecute, where we do preparations on the UI thread, doInBackground where we do the heavy work on a background thread, onProgressUpdate where we publish the progress to the UI thread (for example to a ProgressBar), and onPostExecute where we get back the result from the background task.
In order to not leak memory by holding onto a strong reference to our MainActivity, we will make the AsyncTask static and keep a WeakReference to our Activity.
In MainActivity.java class file add these lines of codes:-
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
import java.lang.ref.WeakReference;
import android.os.Bundle;
import android.os.AsyncTask;
public class MainActivity extends AppCompatActivity {
private ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = findViewById(R.id.progress_bar);
}
public void startAsyncTask(View v) {
ExampleAsyncTask task = new ExampleAsyncTask(this);
task.execute(10);
}
private static class ExampleAsyncTask extends AsyncTask<Integer, Integer, String> {
private WeakReference<MainActivity> activityWeakReference;
ExampleAsyncTask(MainActivity activity) {
activityWeakReference = new WeakReference<MainActivity>(activity);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
MainActivity activity = activityWeakReference.get();
if (activity == null || activity.isFinishing()) {
return;
}
activity.progressBar.setVisibility(View.VISIBLE);
}
@Override
protected String doInBackground(Integer... integers) {
for (int i = 0; i < integers[0]; i++) {
publishProgress((i * 100) / integers[0]);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return "Finished!";
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
MainActivity activity = activityWeakReference.get();
if (activity == null || activity.isFinishing()) {
return;
}
activity.progressBar.setProgress(values[0]);
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
MainActivity activity = activityWeakReference.get();
if (activity == null || activity.isFinishing()) {
return;
}
Toast.makeText(activity, s, Toast.LENGTH_SHORT).show();
activity.progressBar.setProgress(0);
activity.progressBar.setVisibility(View.INVISIBLE);
}
}
}
In activity_main.xml file add these lines of codes:-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:gravity="center"
android:orientation="vertical"
tools:context=".MainActivity">
<ProgressBar
android:id="@+id/progress_bar"
style="@style/Widget.AppCompat.ProgressBar.Horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:visibility="invisible"
tools:visibility="visible" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="startAsyncTask"
android:text="Start" />
</LinearLayout>
Now, after adding these codes run this application and the output will be seen.

Comments