I am going to discuss about AsyncTask. Do you know about AsyncTask and what are the usage of it?
Here are some of the points:
- AsyncTask enables proper and easy use of the UI thread.
- AsyncTask is used when you want to perform long awaited task in background.
- AsyncTask publish result on the UI thread(display result to the UI) without having to manipulate any threads or handlers. It means that user doesn’t bother about Thread management, everything is managed by itself. And thats why it is known as Painless Threading, see below point.
- It is also known as Painless Threading.
- The result of AsyncTask operation is published on UI thread.
- It has basically 4 methods to override: onPreExecute, doInBackground, onProgressUpdate and onPostExecute.
- Once AsyncTask is created(same as below example), we can execute it by using execute method.
new LongOperation().execute(params);
For example:
private class LongOperation extends AsyncTask<String,Void,Void> { @Override protected void onPreExecute() { // Things to be done before execution of long running operation. //For example showing ProgessDialog } @Override protected Void doInBackground(String... params) { // perform long running operation operation return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); // execution of result of Long time consuming operation } @Override protected void onProgressUpdate(Void... values) { // Things to be done while execution of long running operation is in progress. For example updating ProgessDialog } }
Note:
Some time you are required forcefully cancel the ongoing AsyncTask, read article on: Cancelling AsyncTask in Android.