Monday, August 12, 2013

Async task simple example

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 the mani[ulate thread and/or handlers.

Here is an example of simple AsyncTask Demo :
  • Create private class PostTask which extends AsyncTask.
  • add unimplemented methods like-doInBackground,onPostExecute,onPreExecute.
  • insert code in doInBackground method.It acts as a thread and it is also independent from UI.
  • It will not affect the UI or it will not freeze your UI.
  • PostTask class code is given below:

 private class PostTask extends AsyncTask<String , Integer, String>{

    @Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
    String url=params[0];
    // Dummy code
         for (int i = 0; i <= 100; i += 5) {
           try {
             Thread.sleep(50);
           } catch (InterruptedException e) {
             e.printStackTrace();
           }
            publishProgress(i);
         }
         return "All Done!";
   
}

@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
Log.v("*********************","Progressbar dismissed....");
super.onPostExecute(result);
}

@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
Log.v("*********************","Downloading.....................");
super.onPreExecute();
}
    }



  • Now just call this class in onCreate method of MainActivity.java like this:

 new PostTask().execute("http://feeds.pcworld.com/pcworld/latestnews");


  • Don't forget to see LogCat for output.

Download Source code : Link



No comments:

Post a Comment