abhishekengineer
9/7/2019 - 8:38 AM

AsyncTask

Perhaps the best known of the asynchronous API, AsyncTask is easy to implement and returns results on the main thread. There are some issues with AsyncTask, for example, they are not aware of the activity or fragment lifecycle and so it is the programmer's responsibility to handle the AsyncTasks behaviour when the activity is destroyed. This means that they are not the best option for long running operations and also, if the app is in the background and the app is terminated by Android, your background processing is also terminated.

Run instructions in the background and synchronize again with the Main Thread. Useful for short background operations. How it works ?

  1. onPreExecute(), onPostExecute() and onProgressUpdate() are all invoked on the UI Thread.
  2. The value returned by doInBackground() is sent to onPostExecute().
  3. You can call publishProgress() at anytime in doInBackground() to execute onProgressUpdate() on the UI thread.

Problems:

  1. No support for configuration changes.
  2. No error handler, so we have to ask onPostExecute whether the result is an error or not.
  3. Complex chain of asynchronous operations, so it is advisable that the operations performed in the background are all synchronized to avoid the famous Callback Hell.
  4. Each AsyncTask instance can be executed only/just one time.
/////// $$$$$$$$$$$ SYNTAX
//...

new AsyncTask<Void, Void, String>() {
	@Override
	protected void onPreExecute() {
		//...
	}

	@Override
	protected String doInBackground(Void... voids) {
		return performBlockingTask();
	}

	@Override
	protected void onProgressUpdate(Integer... progress) {
		mProgessBar.setProgress(progress);
	}

	@Override
	protected void onPostExecute(String result) {
		mTextView.setText(result);
	}
   
}.execute();

//...

// WORKING EXAMPLE

new 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");
     } 
 }.execute(url1, url2, url3);
// Modified Code from google Android API