When/why does my Java singleton instance get destroyed?

前端 未结 4 1857
刺人心
刺人心 2020-12-16 03:34

I have an android app that is setup to start a Java activity (call it MyJavaActivity), which in turn launches a NativeActivity. When the NativeActivity finishes it returns b

相关标签:
4条回答
  • 2020-12-16 04:11

    I'd make mInstance private. Just in case some other code is accidentally setting it.

    0 讨论(0)
  • 2020-12-16 04:29

    "Android OS can and will terminate your singleton and not even tell you about it."

    Source: http://www.2linessoftware.com/2010/08/03/singletons-and-services-and-shutdowns-oh-my/

    The author of that article suggests some solutions, such as using a Service, or subclassing the Application class. There seems to be quite a bit of support for the latter:

    How to declare global variables in Android?

    0 讨论(0)
  • 2020-12-16 04:35

    Each Android app runs in its own process so as long as it keeps running, your singleton will be available. When the process dies, your singleton is lost. Therefore when the app is re-launched this singleton object will need to be re-created.

    0 讨论(0)
  • 2020-12-16 04:36

    Be sure to read the documentation on the process lifecycle:

    http://developer.android.com/guide/topics/fundamentals/processes-and-threads.html#Lifecycle

    In this case, whenever your app is in the background (in terms of activities, none of your activities are visible to the user), your process can be killed at any time. If the user later returns to one of your activities, a new process will be created and a new instance of the activity created.

    0 讨论(0)
提交回复
热议问题