Sunday 27 January 2013

AsyncTask in Android(1)

Using AsyncTask we can avoid ANR(Application Not Responding).



AsyncTask enables proper and easy use of the UI thread. This class allows 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 pacakge such as Executor, ThreadPoolExecutor and FutureTask.


AsyncTask's Generic Types:

    Params, the type of the parameters sent to the task upon execution.
      Progress, the type of the progress units published during the background computation.
        Result, the type of the result of the background computation.
          The 4 Steps:
            When an asynchronous task is executed, the task goes through 4 steps:
              1.onPreExecute(), invoked on the UI thread before the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.
                2.doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress(Progress...) to publish one or more units of progress. 
                  These values are published on the UI thread, in the onProgressUpdate(Progress...) step.
                    3.onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.
                      4.onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.

                      MainActivity.java:

                      package com.ram.asynctaskdemo;

                      import android.app.Activity;
                      import android.app.ProgressDialog;
                      import android.os.AsyncTask;
                      import android.os.Bundle;
                      import android.widget.Toast;

                      public class MainActivity extends Activity {

                          @Override
                          protected void onCreate(Bundle savedInstanceState) {
                              super.onCreate(savedInstanceState);
                              setContentView(R.layout.activity_main);
                              MyAsync ma = new MyAsync();
                              ma.execute();
                          }

                           class MyAsync extends AsyncTask<Void, Void, Void>{
                           ProgressDialog pd ;
                           @Override
                          protected void onPreExecute() {
                          
                             pd = ProgressDialog.show(MainActivity.this, "downloading", "please wait");
                           
                          super.onPreExecute();
                          }
                           
                      @Override
                      protected Void doInBackground(Void... params) {

                      try {
                      Thread.sleep(5000);
                      } catch (InterruptedException e) {

                      e.printStackTrace();
                      }
                      return null;
                      }

                      @Override
                      protected void onPostExecute(Void result) {

                      pd.cancel();

                      Toast.makeText(getApplicationContext(), "result published", 3000).show();

                      super.onPostExecute(result);

                      }
                           
                           }
                          
                      }

                      No comments:

                      Post a Comment