Wednesday, 20 December 2017

AsyncTask in Android Tutorial

AsyncTask enables proper and easy use of the UI thread. This class allows you to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

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 ExecutorThreadPoolExecutor and FutureTask.
An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called ParamsProgress and Result, and 4 steps, called onPreExecutedoInBackgroundonProgressUpdate and onPostExecute
LoadAsycTask.java
public class LoadAsycTask extends AsyncTask<Void, Void, Void> {
    ProgressDialog
progressDialog;

   
private final Context mContext;

   
public LoadAsycTask(Context mContext) {
       
this.mContext = mContext;
    }


   
@Override
   
protected void onPreExecute() {
       
super.onPreExecute();
       
progressDialog = ProgressDialog.show(this.mContext, "Loading", "please wait....");
    }

   
@Override
   
protected Void doInBackground(Void... params) {
       
try {
            Thread.sleep(
3000);
        }
catch (InterruptedException e) {
            e.printStackTrace();
        }
       
return null;
    }

   
@Override
   
protected void onPostExecute(Void aVoid) {
       
super.onPostExecute(aVoid);
       
progressDialog.dismiss();
      
// Toast.makeText(mContext, "result pubslished", Toast.LENGTH_SHORT).show();
   
}
}

onCreate Methode:


............

LoadAsycTask loadAsycTask = new LoadAsycTask(MainActivity.this);

loadAsycTask.execute();








No comments:

Post a Comment