Sunday, September 18, 2016

AsyncTask in Android @ Better than Thread

Hi .... Dear All ....  Today I am uploading a superb example of AsyncTask.
In this example i have one Main Thread and a AsyncTask.
 
AsyncTask updates the status on UI thread.
Just see this example first otherwise you can't undersatnd the importance of AsyncTask.

http://androidclue4u.blogspot.in/2016/09/thread-in-android-worker-and-main.html

AsyncTask is an Abstract class belonging to Android’s OS framework.
It allows us to interact with the UI thread efficiently and performs time-consuming jobs in another thread.
It is an ideal choice for operation that can be completed in short time.
  To implement an AsyncTask, we need to know about the three generic type params
  1. Params: This generic is to specify the type of the parameters that you want to send to the task for execution
  2. Progress: This is to define the type of progress parameter.
  3. Result: Return type for background execution. 

A. Output will be same as previous example 
B. Layout files are also same 
C. Java code is as 

package com.exam.ravi.threadasync;

import android.os.AsyncTask;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class AsyncActivity extends AppCompatActivity {

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_async);
        CountingTask countingTask = new CountingTask();
        countingTask.execute();
    }

    private class CountingTask extends AsyncTask<Void, Integer, Integer> {
        CountingTask() {}
        @Override        protected Integer doInBackground(Void... params) {
            int count = 0;
            while (count < 100) {
                SystemClock.sleep(200);
                count++;
                if (count % 10 == 0) {
                    publishProgress(count);
                }
            }
            return count;
        }

        @Override        protected void onProgressUpdate(Integer... params) {

            TextView textView = (TextView) findViewById(R.id.counter);
            textView.setText(params[0]+"% Complete");
        }

        @Override        protected void onPostExecute(Integer params) {
            TextView textView = (TextView) findViewById(R.id.counter);
            textView.setText(" Task Completed");
        }
    }
}

No comments:

Post a Comment