在 android 中实现应用程序范围的缓存
Implementing an application-wide cache in android
我正在使用 LruCache 的扩展来存储网络调用的结果。目前缓存是片段中的一个实例变量(唯一需要它的地方),每次应用程序旋转或暂停时都会重新创建。如何使缓存通过轮换和 pausing/resuming 应用程序持续存在?
我读到我可以使用 setRetainInstanceState to handle the rotation case,但这对暂停和恢复情况都没有帮助,并且要求我不要将片段添加到后台堆栈。
我也可以extend Application,但它似乎有点未封装,因为缓存只需要在一个片段中。
将缓存放在 Service 中是个好方法吗?我不清楚服务如何与片段交互,但看起来我可以将服务绑定到应用程序,这样它只会在应用程序执行时终止。
我通常在 Application 对象本身做这样的事情...
class MyApplication extends Application {
private LruCache cache; // or whatever
public Thing getThingFromCache(String key) { /* or whatever */ }
}
...不要忘记将 MyApplication 放入清单中...
<application
android:name=".MyApplication"
android:icon="@drawable/icon"
android:label="@string/name"
>
<!-- whatever -->
</application>
此外,考虑使用 Volley,一个由 Google 开发的网络库。
我正在使用 LruCache 的扩展来存储网络调用的结果。目前缓存是片段中的一个实例变量(唯一需要它的地方),每次应用程序旋转或暂停时都会重新创建。如何使缓存通过轮换和 pausing/resuming 应用程序持续存在?
我读到我可以使用 setRetainInstanceState to handle the rotation case,但这对暂停和恢复情况都没有帮助,并且要求我不要将片段添加到后台堆栈。
我也可以extend Application,但它似乎有点未封装,因为缓存只需要在一个片段中。
将缓存放在 Service 中是个好方法吗?我不清楚服务如何与片段交互,但看起来我可以将服务绑定到应用程序,这样它只会在应用程序执行时终止。
我通常在 Application 对象本身做这样的事情...
class MyApplication extends Application {
private LruCache cache; // or whatever
public Thing getThingFromCache(String key) { /* or whatever */ }
}
...不要忘记将 MyApplication 放入清单中...
<application
android:name=".MyApplication"
android:icon="@drawable/icon"
android:label="@string/name"
>
<!-- whatever -->
</application>
此外,考虑使用 Volley,一个由 Google 开发的网络库。