Asynchronous Tasks in Android
AsyncTask is an abstract class provided by Android which helps us to use the UI(User Interface) thread properly. This class allows us to perform long/background operations and show its result on the UI(User Interface) thread without having to manipulate threads.
Android implements single thread model and whenever an android application is launched, a thread is created.Let on any event like, on button click a request would be made to the server and response will be awaited. Due to single thread model of android, till the time response is awaited our screen is non-responsive. So we should avoid performing long running operations on the UI(User Interface) thread.
AsyncTask has four main methods to perform certain operations:
- doInBackground: Code performing long running operation goes in this method. When onClick method is executed on click of button, it calls execute method which accepts parameters and automatically calls doInBackground method with the parameters passed.
- onPostExecute: This method is called after doInBackground method completes processing. Result from doInBackground is passed to this method.
- onPreExecute: This method is called before doInBackground method is called.
- onProgressUpdate: This method is invoked by calling publishProgress anytime from doInBackground call this method.
Code Snippets of AsynTask class that can be used to create a timer….
private class AsyncTaskRunner extends AsyncTask<String, String, String> {
private String resp;
@Override
protected String doInBackground(String… params) {
publishProgress(“Sleeping…”); // Calls onProgressUpdate()
try
{
// Do your long operations here and return the result
int time = Integer.parseInt(params[0]);
// Sleeping for given time period
Thread.sleep(time);
resp = “Slept for ” + time + ” milliseconds”;
}
catch (Exception e)
{
e.printStackTrace();
resp = e.getMessage();
}
catch (Exception e)
{
e.printStackTrace();
resp = e.getMessage();
}
return resp;
}
@Override
protected void onPostExecute(String result)
{
// execution of result of Long time consuming operation
finalResult.setText(result);
}
Comments
Post a Comment