What happens when running System.exit (0)?

I have two different activities. The first launches the second.

Intent intent = new Intent(this, Activity2.class); startActivity(intent); 

In the second step, I call System.exit (0). I think the first action returns because of the "page stack". But I discovered that two things happened.

  • the expected option has lost its value. (I think restart)
  • a file created in the first action, and added data in the second activity and saved, lost! (deleted from the sandbox). The file I created using applicationContext.openFileOutput(fileName, Context.MODE_PRIVATE);

Was the sandbox cleaned up in this situation? Normal exit using the return key or even android.os.Process.killProcess(android.os.Process.myPid()) , the file was saved in the sandbox. So what actually happened when executing System.exit (0)?

Thanks!

+4
source share
4 answers

You can do one thing:

Do not use System.exit (0); instead, you can simply use the finish ( ) as follows:

 Intent intent = new Intent(this, Activity2.class); startActivity(intent); finish(); 

No data will be lost here. Hth :)

+9
source

What happens when System.exit (0) executes?

The VM stops further execution, and the program terminates.

Now in your case, the first action is returned due to the activity stack. So when you move from one operation to another using Intent , execute finish() current activity like this.

 Intent intent=new Intent(getApplicationContext(), NextActivity.class); startActivity(intent); CurrentActivity.this.finish(); 

This ensures that there is no activity when the application is closed.

And to exit the 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 uses any resource in the background, for example a music player playing a song from the background or any application that uses Internet data in the background or any widget that depends on your application.

For more information, follow the links:

+2
source

So what actually happened when executing System.exit (0)?

android.os.Process.killProcess(android.os.Process.myPid()) and System.exit(0) same. When you call any of them from the second action, the application will be closed and reopened with only one action (we assume that you had 2 actions). You can test this behavior by entering logging ( Log.i("myTag", "MainActivity started"); ) in the onCreate menthod of your main action.

0
source

Source: https://habr.com/ru/post/1395168/


All Articles