Seegatesite – I’ll share how to use AsyncTask for android. What does it AsyncTask? AsyncTask is one of the features in Android Programming for executing the operation to be performed in the background. So basically operations are performed in the background thread and then when it is finished it will be directly displayed in the UI. Either successful or unsuccessful in accordance with the pre-arranged. In the previous article about xml parser android, I use the AsyncTask method for which we will execute the xml file. How important AsyncTask for android application?
According to the Android Developers’s Site
AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent package such as Executor, ThreadPoolExecutor and FutureTask.
In essence, the process AsyncTask background done in a separate thread.
Okay, for more details, we immediately began the following experiment
Table of Contents
Creating a simple application using AsyncTask for android
1. Create a new android project named AsynctaskTutorial, read how to create new android project in android studio
2. Add TextView, Progress Bar, and Button on activity_main.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:padding="20dp" android:text="Tutorial Using ASyncTask" tools:context=".AsyncTaskActivity" /> <ProgressBar android:id="@+id/progressbar" style="?android:attr/progressBarStyleHorizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/textView1" android:layout_marginTop="34dp" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/progress" android:layout_centerHorizontal="true" android:layout_marginTop="40dp" android:minWidth="120dp" android:text="Process" /> <TextView android:id="@+id/txtpercentage" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/progress" android:text="Processing 0%" android:textAppearance="?android:attr/textAppearanceMedium" /> |
3. Add the following script to MainActivity.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | package com.example.sigit.asynctasktutorial; // change with your package name import android.os.AsyncTask; import android.os.SystemClock; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { Button btnprocess; ProgressBar progressBar; TextView txtpercentage; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnprocess = (Button) findViewById(R.id.button); progressBar = (ProgressBar) findViewById(R.id.progressbar); txtpercentage= (TextView) findViewById(R.id.txtpercentage); btnprocess.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { btnprocess.setEnabled(false); new DoingAsyncTask().execute(); } }); } private class DoingAsyncTask extends AsyncTask<Void, Integer, Void> { int progress_status; @Override protected void onPreExecute() { super.onPreExecute(); Toast.makeText(MainActivity.this,"Invoke onPreExecute() Process", Toast.LENGTH_SHORT).show(); progress_status = 0; txtpercentage.setText("Processing 0%"); } @Override protected Void doInBackground(Void... params) { while(progress_status<100){ progress_status += 5; publishProgress(progress_status); SystemClock.sleep(200); } return null; } @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); progressBar.setProgress(values[0]); txtpercentage.setText("Processing " +values[0]+"%"); } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); Toast.makeText(MainActivity.this,"Invoke onPostExecute() Process", Toast.LENGTH_SHORT).show(); txtpercentage.setText("Processing complete"); btnprocess.setEnabled(true); } } } |
4. Run App And Click the Process Button
Explanation :
1. onPreExecute()
in this function we prepare early initialization settings, before the operation is executed. In the example above, we initialize progress_status = 0 and display TextView with the word “Processing 0%”. After the process onPreExecute() is complete, the process is continued with doInBackground().
2. doInBackground()
The part where the operations are performed in the background. In the example above will be looping to add the value of progressbar. The value of the progress bar will be displayed to the UI with publishProgress’s method.
3. onProgressUpdate()
when the operating process runs every change will be displayed. onProgressUpdate () will capture the data that is given by the method publishProgress and shown to the UI. In the example above, OnProgressUpdate() will execute progressBar.setProgress(values[0]) and txtpercentage.setText(“Processing ” +values[0]+”%”)
4. onPostExecute()
after the process / operation is completed this function is executed
Thus article about Android Tutorial – Using AsyncTask for Android With Simple Example for Beginners, hope useful.
if you need more example how to use asynctask for android , please read my another article Android Tutorial – How to Use XML Parser Android with Simple Example for Beginner
Leave a Reply