2

I was attempting to track down memory leaks today in an application which has been hitting out-of-memory on some of the older devices. One of the leaks I found really threw me. I solved the leak but I was wondering if anybody had any insight into why the fix works at all.

The activity (let's call it activity B) that is leaking has an icon that is an 'x' for the user to exit that activity. When the x is pressed, it called finish() and then returns to activity A. The code for this click event is below:

    View ivExit = findViewById(R.id.imageview_exit);
    ivExit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!isFinishing()) {
                finish();
            }
        }
    });

The result is that it would work as expected but was leaking memory. However, with one simple change I was able to run the same exact test without any leak. All I had to do was change finish() to onBackPressed() and it no longer leaked. This is very strange to me because I was under the impression that onBackPressed() and finish() are essentially the same thing, and yet one of them leaks memory and the other does not. Does anybody know why this would be the case?

4
  • 1
    onBackPressed() handles some use-case behind the scene but later on it will also call the finish() implicitly.
    – Enzokie
    Feb 24, 2017 at 0:10
  • What is the OS version on that device? Is that is AppCompatActivity?
    – j2ko
    Feb 24, 2017 at 0:21
  • The device is a Nexus 5X running Android 6.0.1. And yes, the activity extends AppCompatActivity @j2ko Feb 24, 2017 at 17:38
  • It's interesting that you asked @j2ko because when I tested on a different device it didn't occur. Which is extra interesting so this very odd discrepancy only occurs on Nexus? Feb 28, 2017 at 18:34

1 Answer 1

0

The difference is that in FragmentedActivity (that is the parent of AppCompatActivity) has following code in onBackPressed:

public void onBackPressed() {
    if (!mFragments.popBackStackImmediate()) {
        finish();
    }
}

And it hasn't any specific implementation forfinish(). So looks like this popBackStackImmediate somehow affects your flow. I found OS 5.1.1 implementation :

 @Override
 public boolean popBackStackImmediate() {
     checkStateLoss();
     executePendingTransactions();
     return popBackStackState(mActivity.mHandler, null, -1, 0);
 }

executePendingTransactions() could be the reason why behavior is different between onBackPressed() and finish() calls.

1
  • That is definitely helpful! I'm so curious why it occurs on Nexus and not other devices. I'll mark this as correct but I am definitely curious still. Feb 28, 2017 at 18:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.