Many of us will face this surprising issue in our app, it seems like everything is ok with code but not aware of any glitch we are creating in it. AsyncTasks are one of those, it is very useful to do our job in background thread and produce required result. I faced this glitch when trying to download thumb nail image for a customised listview. And here is the issue, when I tried to navigate to next activity before finishing the thumb nail task, there occurs a glitch, I tried to make a server call while creating next activity it took much more un expected time to respond. Your app(UI thread) will do anything only after completing the AsyncTasks you started. And the simple solution for this is as below., 1. Create a Set (a collection that contains no duplicate value) of AsyncTasks

Set asyncTasks = Collections.synchronizedSet(new HashSet());

2. Add each AsyncTask class in Set(Collection) as you create in your app. You can do this onPreExecute() method of Task

@Override
protected void onPreExecute() {
asyncTasks.add(this); 
}

3. And finally you can cancel every asynctasks as below. I prefer to do this at onStop() method of activity

for (AsyncTask asyncTask : asyncTasks) { 
if (asyncTask != null)
   asyncTask.cancel(true); 
}

Hence you may avoid un wanted glitches / delays in your app. Enjoy …! useful link

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s