Memory leak in very simple Android App

Kristy Welsh

I have a very complex app that is leaking memory. In order to track down the leak I stripped the launcher app to a very simple Android app which is still leaking an activity upon navigation to the next activity. I found the leak using the hprof analyzer in Android studio. The entire stripped down launcher activity is:

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class HomeTest extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    Button btnStaffStart = (Button)findViewById(R.id.btnStaffStart);

    btnStaffStart.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {


            Intent startNewActivityOpen = new Intent(HomeTest.this, StaffMenu.class);
            startActivity(startNewActivityOpen);

            finish();
        }

    });
}


}

When I navigate to the StaffMenu activity, the analyzer shows a leak of the HomeTest Activity. What, if anything, am I doing wrong or does the launching activity always leak memory in Android? I'm not getting an OutOfMemory error message, I just don't like to be leaking memory. The app is not allocating much memory so the free memory is very minimal, even in the stripped down activity (less than 1%).

I'm running Android 4.2, 4.4 and 5.1.

EDIT I just tried another application and it also leaked the launcher activity after navigation to the next activity. Known android bug???

Robertas Setkus

There is no memory leak in this code. I cannot explain results of memory leak analyzer but I won't entirely trust cause this particular feature was introduced in last AS version.

Have you checked how many activity instances you have when you navigate between these two activities for multiple times? You could check this out using this command in terminal adb shell dumpsys meminfo <package_name|pid> or using AS in "Android Monitor" perspective.There shouldn't be more than 2 active activities in your case.

enter image description here

If you wanna be sure I recommend you to use MAT memory profiler. How to use it you can find here.

EDIT: this is another good option to make sure if your activities are not leaked. Example how to dump a memory heap on activity leak.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related