The application I\'m working on is using a background thread to download a list of images through a API, then display the images in a slideshow.
There is a backgroun
Thanks to a helpful discussion with Waqas (thank you!) I finally uncovered the error in my code. In fact all above written is correct and works as is. Issue with my case was that the second task blocked the first one and vice versa.
It was perhaps a coincidence to find this post on Google Groups: http://groups.google.com/group/android-developers/browse_thread/thread/f0cd114c57ceefe3?tvc=2&q=AsyncTask+in+Android+4.0 . Recommend that everyone involved in threading reads this discussion carefully.
AsyncTask switched the Threading model to a serial executor (again), which is not compatible with my approach of having 2 AsyncTasks it seems.
Finally I switched the handling of the "Download" to a classic Thread
and used the Handler
to post messages to cancel the Slideshow if neccessary. Using the Handlers sendEmptyMessageDelayed
I will simple recreate the Download Thread after a while to refresh the data.
Thanks to all comments & answers.
Handler
is a kind of thread in android, and AsyncTask also runs in different thread. When you use AsyncTask there are few rules..
There are a few threading rules that must be followed for this class to work properly:
The task instance must be created on the UI thread. execute(Params...) must be invoked on the UI thread. Do not call onPreExecute(), onPostExecute(Result), doInBackground(Params...), onProgressUpdate(Progress...) manually. The task can be executed only once (an exception will be thrown if a second execution is attempted.)
So it clearly says AsyncTAsk must be called from UI thread.. where as you call it from Handler which is not an UI thread...
well try this too
mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
runOnUiThread(new Runnable() {
@Override
public void run() {
if(mDownloadTask != null) {
mDownloadTask.cancel(true);
}
if([isCancelled()][1]){
mDownloadTask = new DownloadTask();
mDownloadTask.execute((Void[]) null);
} // i assume your task is not getting cancelled before starting it again..
}
});
}
};
and also the documentation says this..
There are two main uses for a Handler:
(1) to schedule messages and runnables to be executed as some point in the future; and (2) to enqueue an action to be performed on a different thread than your own.