Using the Android Application class to persist data

前端 未结 7 870
栀梦
栀梦 2020-11-22 08:55

I\'m working on a fairly complex Android application that requires a somewhat large amount of data about the application (I\'d say a total of about 500KB -- is this large fo

相关标签:
7条回答
  • 2020-11-22 09:28

    If you want to access the "Global Singleton" outside of an activity and you don't want to pass the Context through all the involved objects to obtain the singleton, you can just define a static attribute in your application class, which holds the reference to itself. Just initialize the attribute in the onCreate() method.

    For example:

    public class ApplicationController extends Application {
        private static ApplicationController _appCtrl;
    
        public static ApplicationController getAppCtrl()
        {
             return _appCtrl;
        }
    }
    

    Because subclasses of Application also can obtain the Resources, you could access them simply when you define a static method, which returns them, like:

    public static Resources getAppResources()
    {
        return _appCtrl.getResources();
    }
    

    But be very careful when passing around Context references to avoid memory leaks.

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