Misuse of AsyncTask
cuixiaoyiyi opened this issue · 0 comments
cuixiaoyiyi commented
According to our research, there are misuses about the following AsyncTask class:
( tkj.android.homecontrol.mythmote. GestureBuilderActivity.BikeNetworksListActivity)
//……
new JSONDownloadTask().execute(apiUrl);
//……
private class JSONDownloadTask extends AsyncTask<String, Void, String>
The problems are:
- It is inner class. It holds strong reference to the GUI element of Activity( BikeNetworksListActivity ), which can lead to memory leak when the Activity is destroyed and the AsyncTask did not finish.
- Its instances are not cancelled before the Activity is destroyed, which can lead to the wrong invocation of onPostExecute.
- Its instance should be cancelled before the Activity is destroyed. But in the doInBackground method there are for or while loops without the call of isCancelled() . These loops may not be able to terminate when the task is cancelled. This will cause waste of resources or even flashback.
I think we can make following changes to fix the misuse problems:
- I think the GUI-related fields should be wrapped into WeakReference. Take
private final BikeNetworksListActivity _context
as example, it can be changed toprivate final WeakReference<BikeNetworksListActivity> _context
. - Define JSONDownloadTask instance as a field instead of a local. Invoke
cancel()
in the onDestroy() method of Activities or Fragments. - Every loop should check the status of AsyncTask to break the loop.
while(condition1){
if(isCancelled()){
break;
}
//blablabla…
while(condition2){
if(isCancelled()){
break;
}
//blablabla…
}
}
These are my suggestions above, thank you.