Difference between finish() and System.exit(0) - android

I'm talking about programming in android.
In early days I thought that, finish() closes current activity and go back to the previous in Activity stack, and System.exit(0) closes the whole application.
But I was wrong.
I made a small experiment and understood that Both will finish only the current Activity.
The only differences that I could notice is that, in Android 2.3.3
The ActivityResult is propagated back to onActivityResult() using finish(). Whereas onActivityResult() not called for System.exit(0).
But in Android 4.2.2, onActivityResult() is called for both! and Intent was null for exit().
(I tested only in these 2 devices)
There is a time lag when using exit() whereas finish() is faster.(seems like more background operations are there in exit())
So,
what's the difference between two?
In which situations, I can use exit()?
I believe there is something more that I'm missing in between the two methods.
Hope somebody can Explain more and correct me.
Thanks
EDIT UPON REQUEST:
Make an Android application with 2 Activities. Call second Activity from Launcher activity using Intent. Now, inside the second activity, upon a button click, call System.exit(0);.
"The VM stops further execution and program will exit."????(according to documentation)
I see first activity there. Why?
(You are welcome to prove that I'm wrong/ I was right)

Actually there is no difference if you have only one activity. However, if you have several activities on the stack, then:
finish() - finishes the activity where it is called from and you see the previous activity.
System.exit(0) - restarts the app with one fewer activity on the stack. So, if you called ActivityB from ActivityA, and System.exit(0) is called in ActivityB, then the application will be killed and started immediately with only one activity ActivityA

According to android Developer -
finish()
Call this when your activity is done and should be closed. The
ActivityResult is propagated back to whoever launched you via
onActivityResult().
System.exit(0)
The VM stops further execution and program will exit.

According to the documentation, The program will exit.
But it seems a bug in the documentation. In case of a java program, it is correct. But coming to Android, You will see the previous Activity from the stack.
Since Android coding is done using java coding, most of the documentation is same as those for java.
From documentation,
System.exit(0)
The VM stops further execution and program will exit.
For Android aspect, we have to replace the word 'program' with something else. May be Activity or Context.

Sa Qada answer is correct after my testing.
finish will close this activity and back to prevous.
but exit will close current activity too and empty all the activity in freeze and start again the previous activity
Actually there is no difference if you have only one activity.
However, if you have several activities on the stack, then:
finish() - finishes the activity where it is called from and you see
the previous activity. System.exit(0) - restarts the app with one
fewer activity on the stack. So, if you called ActivityB from
ActivityA, and System.exit(0) is called in ActivityB, then the
application will be killed and started immediately with only one
activity ActivityA

Related

Understanding Android lifecycle - onDestroy()

I have MainActivity and SecondActivity in my practice app to understand activity lifecycle. I am clicking the overview button closing the app once it is in MainActivity ( see below which does not call its onDestroy())
and closing the app once I navigate to the SecondActivity through a button click(in this case MainActivity's onDestroy() is called, image below)
I am not sure how important understanding this scenario is, as I am preparing for my interviews. Any advise is much appreciated.
There are situations where the system will simply kill the activity's hosting process without calling this method (or any others) in it, so it should not be used to do things that are intended to remain around after the process goes away.
so,you can't be always sure, that this method will be called
here is the google docs
https://developer.android.com/reference/android/app/Activity.html#onDestroy%28%29*

Android : Returning to prior Activity

When you're in an an Activity (we'll call it A), and you invoke a subsequent Activity (B), perhaps as a result of clicking a button in A, and then RETURN to that prior Activity A, either by clicking the Back button or explicitly calling finish() from within B, it causes A to be completely rebuilt, calling its constructor and its OnCreate() method, etc.
Is there any way to prevent that from happening, so that it actually does return to the prior, already existing, Activity A?
Correct me if I'm wrong, but it should not call onCreate() here's a gross over simplification, but let's say activity's are managed much like a simple stack, let's call it AppStack
When a onCreate() for Activity A is called, the OS pushes the Activity Instance onto the AppStack
________ _________________
Activity|
___A____|_________________
When you click a button on Activity A, it launches a new intent to Activity B
Intent actB = new Intent(this, ActivityB.class);
and subsequently puts Activity A into Stopped state
When Activity B's onCreate() is called the OS pushes that Activity Instance onto the AppStack
________ __________________
Activity|Activity|
___A____|___B____|_________
Now if you call finish() or super.onBackPressed() in Activity B, the OS will pop() the Activity from the AppStack
________ __________________
Activity|
___A____|__________________
When the OS returns to the previous activity, it sees that it is Stopped and begins the process of Resuming it through onResume().
Now if there is some data that you require to be persistent, you can add it in by Overriding onResume()
Check out the activity lifecycle docs, for more info:
This is by design:
If an activity is paused or stopped, the system can drop it from memory either by asking it to finish (calling its finish() method), or simply killing its process. When the activity is opened again (after being finished or killed), it must be created all over.
See Activity Lifecycle. It's also why the Service class exists:
A Service is an application component that can perform long-running operations in the background and does not provide a user interface. Another application component can start a service and it will continue to run in the background even if the user switches to another application.
It's not a typical scenario but when onCreate() is called when going back to that activity that means the Android OS kills it in the background.
Reason: Android is experiencing some memory shortage so killing some of the background task will be a must.
Is there any way to prevent that from happening?
No, you don't have a control over it, there are many reasons why its having a memory shortage e.g. other app installed that certain device is consuming more than expected. Although you can handle this use-case by storing the current information in onSaveInstanceState() and recovering the value from onCreate().
Calling finish() on ActivityB or pressing back will just destroy ActivityB.
ActivityA will not be completely rebuilt. This means it will not call onCreate method. It will just call onResume.
This is the normal behaviour.
However, on special situations, the system could destroy ActivityA (maybe because it needs memory to perform another task), so when you go back to it, the system will have to rebuild it.
To simulate this situation, there is a setting that you can check/uncheck, called "Don't keep activities".
If you have it checked, you will be simulating the situation explained above, it will always destroy the ActivityA as soon as it is not shown, and when you come back to it, the system will have to rebuild it calling onCreate.

Android onActivityResult and onResume Lifecycle after low memory cleanup

I have two activities: ActivityA and ActivityB. ActivityA starts Activity B for result, and expects a certain resultCode. If it does not get it, ActivityA finishes. The idea is that this closes the application.
ActivityA also has an onResume method that does some stuff. I do not want this stuff to be done if ActivityA decides to finish in the onActivityResult method.
This works in most cases, except in low memory situations where android removes both ActivityA and ActivityB from memory and reloads them.
For example: ActivityA starts ActivityB. Background the application. Then android does its memory cleanup whatever. We can simulate that in DDMS.
Bring App To Foreground.
onCreate() called for ActivityB
Back Button to finish ActivityB
onCreate() called for ActivityA
onActivityResult() called for ActivityA
result is a cancel, call finish()
onResume() called for ActivityA
on resume does stuff
These last two steps are not desirable. Without the low memory issues, the normal workflow looks like this:
Bring App to Foreground
Back Button to finish ActivityB
onActivityResult() called for ActivityA
result is a cancel, call finish()
I have seen this on both a phone running Gingerbread and a Nexus 7 running Jellybean.
My first question: Am I missing something obvious in the Activity Lifecycle?
Failing that, is this the expected behavior from Android? Is there an elegant way to resolve this, or do I have to hack something, or should I try a different approach all together?
Thanks in advance. If anyone needs more information or code, just let me know.
You can declare a class member private boolean mShouldFinished. Set it to true in onActivityResult when called finish. In onResume check mShouldFinished and if true call finish.

Not able to kill 2 activities at the same time. why is that?

I'm trying to kill 2 activities on the onclick of a button. The current activity and the previous activity. Using their pids. I'm just able to kill one activity. Why does this happen?
public void onClick(View v) {
android.os.Process.killProcess(pidofmain);
android.os.Process.killProcess(android.os.Process.myPid());
}
If I see in my logcat, The activity with pid "pidofmain" is getting killed whereas the current activity is not getting killed.
"pidofmain" is an integer i received from the previous activity using an intent.
Leave process killing to the OS. This is bad for any kind of program in a timesharing OS. If you want to conserve memory or something like that, let the OS handle it.
Also you can't really know if the process was correctly killed because well, if it is you wouldn't know, and if it doesn't you were not supposed to do it.
What do you want to do this for?
A much better way to do this is to call finish() for the current activity. You can also signal the previous activity to finish if it calls the current activity using startActivityForResult(Intent). The current activity would call setResult(int) before calling finish() to send a return code back to the previous activity. The previous activity can test the return code in onActivityResult(int, int, Intent) and also call finish() based on the result code.
Killing processes should be left to the OS. Once the activities finish, the will kill it off if it needs the resources. Otherwise it can let it around, which might help speed up a relaunch of your app if the user wants to run it again.
This isn't a definitive answer, but more like some thoughts that I have but it's too late for my to fire up Eclipse and prototype them. If it doesn't help you let me know and I'll try to look into it deeper tomorrow night.
A few thoughts (I hope they help):
1) Android apps really are single-threaded, and your main activity controls all the dispatch events (including events to what I assume to be a second thread that you created). If you kill the main activity, I'm pretty sure that your application would terminate execution immediately following your first call to android.os.Process.killProcess(pidofmain), and you'd never make it to your second call because you would have killed your entire application. Again, this is assuming by the variable name pidofmain that you are killing the main UI thread and not just an activity called main.
2) I'm a little curious also about where you got pidofmain? It sounds like you have three activities total, and in the first activity you get it's process id and send it to the second activity in an intent bundle, which also gets passed along to a third activity (which is the place where you're trying to kill this whole thing)? If that is the case, and you're trying to kill the currently running activity, the table in the documentation here leads me to believe that you can't just kill an activity that's in the resumed state using the same method. Official Android Docs for Activity You might want to try calling the finish() method for your currently running activity.
What exactly do you see in logcat? And what happens in the UI? Does the visible activity continue to run, but the other activity has been removed from the backstack?

Activity.finish() called but activity stays loaded in memory

When I run my app on the debugger, I get the main thread and 3 binder threads.
On a button click I call Activity.finish(), which looks like it ends the activity as the UI closes and goes back to the home screen.
However, in the debugger, it still shows the main thread and 3 binder threads as "(running)".
I am baffled to why this is happening. Even more so, it is causing my app to call Activity.onResume() when I run it again after exiting the app.
I currently override these methods in the Activity, but I call the appropriate super functions in each one:
onDestroy()
onPause()
onResume()
onSaveInstanceState()
Any help or advice regarding this is much appreciated!
You don't control when your app leaves main memory, the OS does. Look closely at Activity.finish...
Call this when your activity is done
and should be closed. The
ActivityResult is propagated back to
whoever launched you via
onActivityResult().
Note that is says nothing about memory. As to calling Activity.onResume, that's exactly what you would expect for the lifecycle; remeber that onResume is not just called after a resume but even when the app is first launched after onCreate.
While not exactly what you asked I suggest you read this article about exit buttons which goes on to say something very important
[Activity.finish] is exactly equivalent to hitting the back button.

Categories

Resources