3

I know that this call should not be made but at the moment is the only thing stopping the activity fast enough.

Basically after returning the app from the background (or using the DDMS "Terminate Application" button) some static variables are null. I would like to restart the activity in order to stop crashes and so all values are updated.

At the moment System.exit(0) has done what I want, but I know this is not good.

I have tried finish(), but that does not stop the activity fast enough, it keeps executing some instructions that still causes the crash.

Any suggestions on how to manage this problem.

Matt Clark
  • 27,671
  • 19
  • 68
  • 123
  • 3
    "Basically after returning the app from the background (or using the DDMS "Terminate Application" button) some static variables are null" -- that is because your process was terminated. You need to treat all `static` fields as caches and be in position to lazy-initialize them. – CommonsWare Jul 11 '17 at 23:53
  • Check it: https://developer.android.com/reference/android/app/Activity.html#finish() – Lifka Jul 11 '17 at 23:57

3 Answers3

2

Standard way to close your running android app is simple:

finish();

or more complicated way is this:

android.os.Process.killProcess(android.os.Process.myPid());
Michal
  • 3,584
  • 9
  • 47
  • 74
2

Only in Android api 21 > you can use >

getActivity().finishAndRemoveTask(); 

Finishes all activities in this task and removes it from the recent tasks list.

It stops the application as fast as System.exit (0). But is it better than System.exit(0)? I don't know...

------------------ EDIT ---------------------

In below question

How to quit android application programmatically?

you can see all kinds of ways to stop your application.

Ali Ahmed
  • 313
  • 1
  • 8
alexpfx
  • 6,412
  • 12
  • 52
  • 88
1

According to the docs for Activity.finish():

Call this when your activity is done and should be closed. The ActivityResult is propagated back to whoever launched you via onActivityResult().

When you call System.exit(), you are actually terminating the JVM; by finishing the activity, you allow the Android JVM to do its cleanup.

Matt Clark
  • 27,671
  • 19
  • 68
  • 123
  • finish() does not stop the activity "fast enough" it keeps executing some instructions that still causes the crash. But thanks – Leonardo Hernandez Jul 11 '17 at 23:58
  • 1
    Then I think you need to override `onPause` and shutdown any threads that you still have running? What instructions are still being run? Where are you trying to call this from? These details should be added to your post body. – Matt Clark Jul 12 '17 at 00:00