Skip to content
This repository was archived by the owner on Dec 18, 2023. It is now read-only.
This repository was archived by the owner on Dec 18, 2023. It is now read-only.

Misuse of AsyncTask #50

@cuixiaoyiyi

Description

@cuixiaoyiyi

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:

  1. 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.
  2. Its instances are not cancelled before the Activity is destroyed, which can lead to the wrong invocation of onPostExecute.
  3. 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:

  1. I think the GUI-related fields should be wrapped into WeakReference. Take
    private final BikeNetworksListActivity _context as example, it can be changed to private final WeakReference<BikeNetworksListActivity> _context.
  2. Define JSONDownloadTask instance as a field instead of a local. Invoke cancel() in the onDestroy() method of Activities or Fragments.
  3. 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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions