How to declare a resource globally in Android

旧时模样 提交于 2019-12-24 14:20:07

问题


I have an application that displays a list of photo albums and then, once an album is selected, displays photos in that album. I am using the memory cache/disk cache implementation from one of the google examples (since the photos are loaded from a website). Everything is working fine, but the disk cache initialization takes place every time an album is chosen, and the initialization takes considerable amount of time. I'd like to declare the disk cache "globally" and use it for all albums. I am not an expert in Java and not clear how to do this, particularly that various activities are being called and I can't just pass a reference to the cache when switching from one activity to another. Should the entire caching logic be build as a "service" and then "called" upon on as needed basis? Or is there a different and/or better/more elegant way of doing this?

Thank You,


回答1:


Extend the Application class.

Here you are an example:

public class MyApplication extends Application {

    private static MyApplication singleInstance;
    //TODO: Your fields here

    public void onCreate() {
        super.onCreate();
        MyApplication.singleInstance = (MyApplication)getApplicationContext();
        //TODO: Your initialization code here
    }

    public static MyApplication getStaticApplicationContext() {
        return singleInstance;
    }

    //TODO: Your methods here
}

There you can add your cache and the relevant code.

You will have to reference the class into the AndroidManifest.xml file, adding the android:name attribute in the application tag, like this:

<manifest ...>
    ...
    <application ...
        android:name="com.example.app.MyApplication">
    ...
</manifest>


来源:https://stackoverflow.com/questions/20914187/how-to-declare-a-resource-globally-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!