简体   繁体   中英

Android Application class - lifecycle of field members

I have Android application and own Application derived class holding some internal data. Among other there are some string fields. The problem is that if I put the application in foreground, work on other application, switch back to my app again, the app may be restarted because it got killed by system. Unfortunatelly the Application object seems not to be created again because the onCreate method of application object doesn't get called and all fields are set to null. My Activity gets recreated but all Application's object fields are null. When is the Application.onCreate method called? How to handle it?

there is no onCreate that you can register to.
in later API's there's a way to register to the Activity lifecycle functions. and then you can do what ever you want.

basically, what you should do is use SharedPrefrences for storing information.

what I would do is:

class MyApp extends Application {
    private static String someResource = null;
    public static String getSomeResource(Context context) {
       if(someResource == null) {
           SharedPrefrences prefs = (SharedPrefrences)
                  context.getSystemService(Context.SHARED_PREFRENCES);
           someResource = prefs.getString(SOME_RESOURCE, null);
       }
    return someResource;
 }

Application onCreate() will called only for one time during its life-cycle, ie. only when application is started.

As suggested by thepoosh below answer is valid ,if your application is killed,still the data is saved in shared preference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM