1

I understand the basic concepts of memory leak in Java (i.e., some unneeded objects are still referred to by others and cannot be GCed).

How can I map this concept to the WindowLeaked exception in Android?

For example, the following code would cause a WindowLeaked exception when changing the orientation during AsyncTask execution. In this case, what objects still hold references the unneeded ones? ProgressDialog or the Activity?

public class WindowLeakedTestActivity extends AppCompatActivity {
    ...
    static class MyTask extends AsyncTask<Void, Void, String> {
        Context context;
        private ProgressDialog mProgress;

        public MyTask(Context c) {
            context = c;
        }

        protected void onPreExecute() {
            super.onPreExecute();
            mProgress = ProgressDialog.show(context, "hello world", "wait", true, true);
        }

        protected String doInBackground(Void... params) {
            try {
                Thread.sleep(8000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "";
        }
    }
}
JackWM
  • 10,085
  • 22
  • 65
  • 92

2 Answers2

0

WindowLeaked is caused by ProgressDialog because changing rotation in android causes activity to destroy and load again.

Therefore, you need to call mProgress.dismiss() before your activity is destroyed.

waqaslam
  • 67,549
  • 16
  • 165
  • 178
  • thanks for answering! but why `progressdialog` becomes leaked when `activity` is destroyed? – JackWM Jun 29 '16 at 21:54
  • Good link. But it does not answer who is holding the references to `progressdialog` so that it cannot be GCed. – JackWM Jun 30 '16 at 06:24
  • WindowLeak is not translated as memory leak... the naming scheme sounds misleading. It's just a notification from framework that the window on which the Dialog is shown has been leaked because the activity that holds the window is destroyed... – waqaslam Jun 30 '16 at 07:25
0

You didn't show what type of context you use (activity or application). The main problem is not even with progress bar but a context. Any static class can outlive Activity caller and if static class holds context it prevents owner of that context to be reaped during configuration changes.

You can use AsyncTaskLoader that respects Activity lifecycle.

Maxim G
  • 1,479
  • 1
  • 15
  • 23