How to declare global variables in Android?

前端 未结 17 2939
死守一世寂寞
死守一世寂寞 2020-11-21 04:12

I am creating an application which requires login. I created the main and the login activity.

In the main activity onCreate method I added the following

17条回答
  •  误落风尘
    2020-11-21 04:47

    The suggested by Soonil way of keeping a state for the application is good, however it has one weak point - there are cases when OS kills the entire application process. Here is the documentation on this - Processes and lifecycles.

    Consider a case - your app goes into the background because somebody is calling you (Phone app is in the foreground now). In this case && under some other conditions (check the above link for what they could be) the OS may kill your application process, including the Application subclass instance. As a result the state is lost. When you later return to the application, then the OS will restore its activity stack and Application subclass instance, however the myState field will be null.

    AFAIK, the only way to guarantee state safety is to use any sort of persisting the state, e.g. using a private for the application file or SharedPrefernces (it eventually uses a private for the application file in the internal filesystem).

提交回复
热议问题