Perhaps the best known of the asynchronous API, AsyncTask is easy to implement and returns results on the main thread. There are some issues with AsyncTask, for example, they are not aware of the activity or fragment lifecycle and so it is the programmer's responsibility to handle the AsyncTasks behaviour when the activity is destroyed. This means that they are not the best option for long running operations and also, if the app is in the background and the app is terminated by Android, your background processing is also terminated.
Run instructions in the background and synchronize again with the Main Thread. Useful for short background operations. How it works ?
Problems:
/////// $$$$$$$$$$$ SYNTAX
//...
new AsyncTask<Void, Void, String>() {
@Override
protected void onPreExecute() {
//...
}
@Override
protected String doInBackground(Void... voids) {
return performBlockingTask();
}
@Override
protected void onProgressUpdate(Integer... progress) {
mProgessBar.setProgress(progress);
}
@Override
protected void onPostExecute(String result) {
mTextView.setText(result);
}
}.execute();
//...
// WORKING EXAMPLE
new AsyncTask<URL, Integer, Long>() {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}.execute(url1, url2, url3);
// Modified Code from google Android API