-1

By passing activity object to the constructor of the AsyncTask. Is there any possibility of Activity leaking. if so then how it happen, can anyone please explain this. and how to avoid the activity leaking if it happening.

public class RemoteLoader extends AsyncTask<Void, Void, Void> {

    private Activity activity;

    public RemoteLoader(Activity context){
      this.activity = context;
    }

    @Override
    protected Void doInBackground(Void... Pages) {
        // do in bg
    }

    @Override
    protected void onPostExecute(Void result) {
        // Set title into TextView
        TextView txttitle = (TextView)activity.findViewById(R.id.txtProtip);
        txttitle.setText(protip);
    }

}
Rizier123
  • 58,877
  • 16
  • 101
  • 156
Dehan Wjiesekara
  • 3,152
  • 3
  • 32
  • 46

2 Answers2

2

The AsyncTask keeps a reference to the Activity, therefore the Activity instance cannot be garbage collected while the AsyncTask is alive/running.

In certain cases, such as orientation change, the "old" Activity instance is no longer required as another Activity instance is created by the framework. In such cases, if your AsyncTask is keeping a strong reference to the Activity instance, then there will be a memory leak.

To avoid this issue, use WeakReference as follows:

public class RemoteLoader extends AsyncTask<Void, Void, Void>{
    private WeakReference<Activity> activity;

    public RemoteLoader(Activity context){
      this.activity = new WeakReference<Activity>(context);
    }
    ...
    ...
}

When using WeakReference you can ensure that the Activity instance is garbage collectable if needed. You can read more about WeakReference here.

Amulya Khare
  • 7,718
  • 2
  • 23
  • 38
1

Try having a WeakReference to your Activity in the AsyncTask. And upon completion, check if the Activity still exists.

jelgh
  • 705
  • 1
  • 6
  • 22