问题
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