Reputation: 741
I am using a static variable in an activity in android (it is not the main activity). But when I go to the main activity and I press the back button, the static value remains the same. The back button does not kill the main process. Why?
Upvotes: 1
Views: 3646
Reputation: 16393
Using the back button destroys the activity, not the application. All activities are part of an application that is running in a Dalvik VM. The application is still there, running (even if all activities have been destroyed), until the system decides that it needs resources and kills the process.
As such, your static member will remain in memory as long as the process/app is running.
If you try running some memory-intensive application or closing the running application with some task manager, you may see the static value reset.
Upvotes: 9
Reputation: 791
The user pressing the back button to navigate off of the main activity does not guarantee that the activity will be destroyed. It just moves your UI (activity) to not being seen. Refer to https://developer.android.com/reference/android/app/Activity.html and https://developer.android.com/training/basics/activity-lifecycle/index.html.
Update:
Below are some snippets of text from that second web page: From the Figure 1 text: “When the user leaves your activity, the system calls onStop() to stop the activity (1). If the user returns while the activity is stopped, the system calls onRestart() (2), quickly followed by onStart() (3) and onResume() (4). Notice that no matter what scenario causes the activity to stop, the system always calls onPause() before callingonStop().”
And “Note: Because the system retains your Activity instance in system memory when it is stopped, …”
And: “When your activity receives a call to the onStop() method, …. Once your activity is stopped, the system might destroy the instance if it needs to recover system memory. In extreme cases, the system might simply kill your app process without calling the activity's final onDestroy() callback, …. “
All of the above demonstrate that when the user leaves your activity (by the back button in your scenario), that it is not necessarily destroyed. It is only initially stopped.
Upvotes: 1
Reputation: 12134
Try with this,
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK))
{
finish();
System.exit(0);
}
return super.onKeyDown(keyCode, event);
}
Upvotes: 1