Why does this happen during rotation?

I came across the following memory leak example

package com.justinschultz.android; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; public class LeakedDialogActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setIcon(android.R.drawable.ic_dialog_alert); builder.setMessage("This dialog leaks!").setTitle("Leaky Dialog").setCancelable(false).setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) {} }); AlertDialog alert = builder.create(); alert.show(); } } 

I do not understand why it flows during rotation. I understand that a new action is created when a dialog is still on the screen (containing a link to the old action). Suppose you close the dialog and rotate again. Should the link to the oldest occupation not disappear, which will allow to restore the memory?

+4
source share
1 answer

AlertDialogs (if used outside of fragments) must be created via onCreateDialog() / showDialog() to avoid leaks.

This implementation is deprecated and should be replaced with DialogFragment , but will work for you:

 @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); showDialog(YOUR_DIALOG_ID); } @Override protected Dialog onCreateDialog(int id) { switch(id) { case YOUR_DIALOG_ID: return new AlertDialog.Builder(LeakedDialogActivity.this) .setIcon(android.R.drawable.ic_dialog_alert) .setMessage("This dialog leaks!") .setTitle("Leaky Dialog") .setCancelable(false) .setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) {} }) .create(); } return super.onCreateDialog(id); } 

ADDED

If you do not create a dialog in onCreateDialog , it is essentially not tied to (or belongs to) the Activity and, therefore, its life cycle. When an action is destroyed or recreated, the dialog maintains a link to it.

In theory, Dialog should not flow if you use setOwnerActivity() and onPause() (I suppose).

I'm not sure that you need to worry a lot about this problem, as there are general leaks. Dialogs are a special case.

+3
source

Source: https://habr.com/ru/post/1443948/


All Articles