Android AlertDialog leaks memory when show & dismiss multiple times?

Viewed 372

I have a simple Activity with only one button to popup a simple dialog. Code is:

1. MainActivity.java

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void showDialogBlank(View dumbView) {
        AlertDialog.Builder dlgBuilder = new AlertDialog.Builder(this);
        dlgBuilder.setTitle("TEST-TITLE")
                .create()
                .show();
    }
}

2. activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/btnShowDialogBlank"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:onClick="showDialogBlank"
        android:text="btn-blank" />

</LinearLayout>

After I click the button & empty area multiple times, the memory is like: enter image description here

Mainly, the Native memory grows by ~3.6MB, which cannot be GC... Why is that?

3 Answers

There is no memory leak!

Yes, the memory use increased, when you show a Dialog, because it needs memory to create the instance and present the instance to the user.

When Android present the Dialog some native functions are called to draw the Dialog to the screen.

But when you close the Dialog on one says that Android also clear all his native caches.

The system assumes that when you have shown a dialog once you maybe want to show another dialog after that. It will cache some native instances for that. So the system can show up the dialog faster at the next time.

When the memory is needed Android will clear this caches but should the system do this when there is enough memory.

Not entirely sure, but I would assume its because every time you call your onclick method you're creating a new object.

AlertDialog.Builder dlgBuilder = new AlertDialog.Builder(this);

This does not necessarily means there is a leak. Maybe gc has not decided which objects to collect. You can initiate gc in onResume yourself and test if objects get GCed or not. LeakCanary can be very useful to detect memory leaks, you can install it just by adding the dependency. Check your code with LeakCanary too, then you can trace the leak easily if there is one.

Related