Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What will happen when System.exit(0) execute?

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.

  1. the variant in progress lost its value. (The progress restart I think)
  2. 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!

like image 675
Kane Avatar asked Dec 16 '22 04:12

Kane


2 Answers

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 :)

like image 94
Android Killer Avatar answered Jan 08 '23 21:01

Android Killer


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:

  1. Is quitting an application frowned upon?
  2. http://android-developers.blogspot.in/2010/04/multitasking-android-way.html
like image 38
dakshbhatt21 Avatar answered Jan 08 '23 21:01

dakshbhatt21