Android AsyncTask Example | Simplest code

AsyncTask

is a background process that easily handle UI without handler.You must know that why we use background process. We need background process / multi threading for long processes like communicate with Internet or database. If you handle Multi Threading smartly then your mobile application should perform better.

Simplest AsyncTask example is given below:

private class AsyncLogin extends AsyncTask<String, Integer, Boolean> {
	
	@Override
	protected void onPreExecute() {
		// Executed before 'doInBackground'
		// You can handle user interface (UI) here
	}
	
     protected Boolean doInBackground(String... userCredencials) {
    	 // Expensive process should be here
    	 // Don't use any control like Button, TextBox, Label or ListView etc
    	 
    	 // Call this function to call "onProgressUpdate", you can send progress of work using this function.
    	 // We can call this function from loop or tell downloading file progress
    	 publishProgress(50);

         return true;
     }

     protected void onProgressUpdate(Integer... progress) {
         // set progress percent progress[0]
    	 // or frequently UI work
    	 // progress[0] is comming from 'publishProgress(50);'
     }

     protected void onPostExecute(Boolean result) {
         // Update user interface (UI)
    	 // value of parameter result is coming from 'doInBackground'
    	 // After 'doInBackground' it calls 'onPostExecute'
     }
 }

 

For more examples about android background thread examples follow the links:-

How to use simple thread in Android

android.os.NetworkOnMainThreadException

Leave a comment

Your email address will not be published. Required fields are marked *