1

I'm developing on a Galaxy S6 running Lollipop. I used Android Studio to create a ScrollView app using the template that comes with Android Studio. I only added the following Java code:

@Override
public void onBackPressed() {
    Toast.makeText(this, "onBackPressed", Toast.LENGTH_SHORT).show();
    super.onBackPressed();
}

@Override
protected void onPause() {
    Toast.makeText(this, "onPause", Toast.LENGTH_SHORT).show();
    super.onPause();
}

@Override
protected void onStop() {
    Toast.makeText(this, "onStop", Toast.LENGTH_SHORT).show();
    super.onStop();
}

@Override
protected void onDestroy() {
    Toast.makeText(this, "onDestroy", Toast.LENGTH_SHORT).show();
    super.onDestroy();
}

When I tap Back on the device, all 4 toast messages come up in the sequence that they appear in the code. However, when I view the app in Application Manager, the Force Stop button is still enabled, indicating that the process is still active. To confirm that I also downloaded a third party app to view active processes and it shows mine in the list.

Is there something that has to addes so that when hitting the Back button on the device the process will die 100% and not be on that active processes list any longer?

Anthony Tietjen
  • 1,032
  • 2
  • 8
  • 19

2 Answers2

1

This is expected behavior on Android.

Android makes no guarantees as to when it will kill your app when exiting, so I'm not sure why you think it's supposed to. It's more beneficial for Android to keep your app in memory as long as possible so that its's faster to resume.

telkins
  • 10,440
  • 8
  • 52
  • 79
  • Agree. I've tried in different Android devices(LG, HTC, Samsung, Sony). There's no universal solutions for this problem. For example, killProcess is not working on HTC devices. The process still alive in the task list. – VoidExplorer Mar 04 '16 at 03:53
  • if you want to restart your app, I suggest your just send your app back to background and add a flag to clear your activity stacks. – VoidExplorer Mar 04 '16 at 03:57
0

Please this code in your OnBackPressed() method:

int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);

That way your app will be completely closed and removed from running apps.

Eury Pérez Beltré
  • 2,017
  • 20
  • 28
  • Thanks everyone, this is a hard one to determine who is "correct". It's almost a three-way tie. Since my question specifically asks how to do it when pressing Back, and this answer explains where exactly to put that line of code. The linked page above does not specifically address the Back button. I do like trevor-e's answer in that it is not necessarily intended by Android that your app should close all the way when pressing back, and VoidExplorer's backing that up with his experience with different devices. I'll accept this one as the answer and give the others a plus 1. – Anthony Tietjen Mar 05 '16 at 04:32