问题
I have two different activities. The first launches the second one.
Intent intent = new Intent(this, Activity2.class);
startActivity(intent);
In the second activity I call System.exit(0). The first activity comes back caused by 'page stack' I think. But I found two things happened.
- the variant in progress lost its value. (The progress restart I think)
- the file created in first activity, and appended data in second activity and saved, lost!(erased from sandbox). The file I created using
applicationContext.openFileOutput(fileName, Context.MODE_PRIVATE);
Was sandbox cleaned in that situation? The normal exit by 'return key' or even by android.os.Process.killProcess(android.os.Process.myPid())
, the file in sandbox was kept.
So, what actually happened when System.exit(0) execute?
Thanks!
回答1:
You can do one thing:
Donot use System.exit(0); instead you can just use finish() as follows:
Intent intent = new Intent(this, Activity2.class);
startActivity(intent);
finish();
Here data will not be loss.HTH :)
回答2:
What will happen when System.exit(0) execute?
The VM stops further execution and program will be exit.
Now, in your case the first activity comes back due to activity stack. So when you move from one activity to another using Intent
, do the finish()
of current activity like this.
Intent intent=new Intent(getApplicationContext(), NextActivity.class);
startActivity(intent);
CurrentActivity.this.finish();
This will guarantee that no activity running when we close the application.
And for exiting from application use this code:
MainActivity.this.finish();
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(0);
getParent().finish();
And you should not use System.exit()
if your application use any resource in background like Music player that plays song from background or any application that uses internet data in background or any widget that depends on your application.
For more information go through the following references:
- Is quitting an application frowned upon?
- http://android-developers.blogspot.in/2010/04/multitasking-android-way.html
回答3:
Read the documentation:
http://developer.android.com/reference/java/lang/System.html#exit(int)
回答4:
So, what actually happened when System.exit(0) execute?
android.os.Process.killProcess(android.os.Process.myPid())
and System.exit(0)
are the same. When you call any of them from the second activity, then the application will be closed and opened again with only one activity (we assume that you had 2 activities). You can check this behaviour by putting logging (Log.i("myTag", "MainActivity started");
) in onCreate menthod of your main activity.
来源:https://stackoverflow.com/questions/9172367/what-will-happen-when-system-exit0-execute