Tuesday, 9 September 2014

AsyncTask Example in Android

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


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.



                  public class AshncTask extends Activity{

                  @Override
                  protected void onCreate(Bundle savedInstanceState) {
                  super.onCreate(savedInstanceState);
                  setContentView(R.layout.ashnctask);

                  new asy().execute();

                  }
                  class asy extends AsyncTask<Void, Void, Void> {
                  ProgressDialog pd;
                  @Override
                  protected void onPreExecute() {

                     pd = new ProgressDialog(AshncTask.this);
                         pd.setTitle("downloading");
                           pd.setMessage("please wait");
                               pd.show();

                  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();
                  super.onPostExecute(result);
                  }
                  }

                  }
                  .............................................................................................................................................................
                  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                      xmlns:tools="http://schemas.android.com/tools"
                      android:layout_width="match_parent"
                      android:layout_height="match_parent" >

                      <TextView
                          android:id="@+id/textView1"
                          android:layout_width="wrap_content"
                          android:layout_height="wrap_content"
                          android:layout_alignParentTop="true"
                          android:layout_centerHorizontal="true"
                          android:text="async_task"
                          tools:context=".AsyncTaskActivity" />

                      <ProgressBar
                          android:id="@+id/progress"
                          style="?android:attr/progressBarStyleHorizontal"
                          android:layout_width="match_parent"
                          android:layout_height="50dp"
                          android:layout_below="@+id/textView1"
                          android:layout_marginTop="30dp" />

                      <Button
                          android:id="@+id/btn_start"
                          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="start_btn" />

                      <TextView
                          android:id="@+id/txt_percentage"
                          android:layout_width="wrap_content"
                          android:layout_height="wrap_content"
                          android:layout_alignParentLeft="true"
                          android:layout_below="@+id/progress"
                          android:text="downloading  0%"
                          android:textAppearance="?android:attr/textAppearanceMedium" />

                  </RelativeLayout>


                  public class agshjkhas extends Activity implements OnClickListener{
                  Button btn_start;
                  ProgressBar progressBar;
                  TextView txt_percentage;
                  @Override
                  protected void onCreate(Bundle savedInstanceState) {
                  super.onCreate(savedInstanceState);
                  setContentView(R.layout.agsync);
                  btn_start = (Button) findViewById(R.id.btn_start);
                  progressBar = (ProgressBar) findViewById(R.id.progress);
                  txt_percentage = (TextView) findViewById(R.id.txt_percentage);
                  btn_start.setOnClickListener(this);
                  }
                  @Override
                  public void onClick(View v) {
                  btn_start.setEnabled(false);
                  new agjghjas().execute();
                  }
                  private class agjghjas extends AsyncTask<Void, Integer, Void>{

                  int prograssStatus;


                  @Override
                  protected void onPreExecute() {

                  prograssStatus = 0;
                  txt_percentage.setText("downloading 0%");
                  super.onPreExecute();
                  }
                  @Override
                  protected Void doInBackground(Void... params) {
                  while (prograssStatus < 100) {

                  prograssStatus += 2;

                  publishProgress(prograssStatus);
                  SystemClock.sleep(3000);

                  }
                  return null;
                  }
                  @Override
                  protected void onProgressUpdate(Integer... values) {
                  // TODO Auto-generated method stub
                  super.onProgressUpdate(values);
                  progressBar.setProgress(values[0]);
                  txt_percentage.setText("downloading " + values[0] + "%");
                  }
                  @Override
                  protected void onPostExecute(Void result) {
                  // TODO Auto-generated method stub
                  super.onPostExecute(result);
                  txt_percentage.setText("download complete");
                  btn_start.setEnabled(true);
                  }
                  }
                  }

                  No comments:

                  Post a Comment