AsyncTask
Most important thing is AsyncTask is intended to be used on UI thread, so do not try to use it elsewhere. Signature is android.os.AsyncTaskThere are four commonly used and overridden methods:
protected void onPreExecute ()
protected abstract Result doInBackground (Params... params)
protected void onProgressUpdate (Progress... values)
protected void onPostExecute (Result result)
obviously only doInBacground is compulsory to override and that is only one which is not executing on UI thread. Typical implementation looks like this:
private class FetchItemsTask extends AsyncTask
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.setMessage("Downloading. Please wait...");
progressDialog.show();
}
@Override
protected Void doInBackground(Void... params) {
do some heavy I/O work here
return null;
}
@Override
protected void onPostExecute(Void result) {
pass to UI result of work here
progressDialog.dismiss();
}
}
Usually it is declared as inner class inside Activity and we have instance of ProgressDialog accessible.
It is not full size threading framework, it should be used as suggested to do lengthy I/O operations. That lengthy is few seconds not few minutes. So good candidate for downloading image from Internet or pulling data from DB. Very good idea here is to go to your Android SDK Manager and to download source code and see how implementation of AsyncTask looks like. Equally good idea is to place logging at every method and log ID of current thread, so that we can be sure where is what executed.
If we take a look at my example in git://github.com/FBulovic/grumpyoldprogrammer.git we will see that my BroadcastReceiver contains AsyncTask. Knowing that AsyncTask can bi instantiated only from UI thread we can conclude that BroadcastReceiver is also executed on UI thread. That was nice intro to CursorAdapter and ContentProvider where execution happens outside of UI thread but they need to communicate with UI thread and that may course some problems here and there. Especially you want to access SQLite DB directly without using ContentProvider.
Next part of this tutorial will follow, soon.
No comments:
Post a Comment