旋转设备时保存缓存 [英] Save cache when rotate device

查看:30
本文介绍了旋转设备时保存缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Gallerywiew.

我正在使用 lazyload 下载图像,但是当我旋转设备时,它会重新加载所有图像并且不使用缓存.

I'm using lazyload to download images but when I rotate device it reloads all images and does not use the cache.

如果我执行 android:configChanges="keyboardHidden|orientation" 当前图像的大小为最新方向.

If I do android:configChanges="keyboardHidden|orientation" the current images are in size of latest orientation.

为了让图像显示全尺寸,我这样做:

To get the images to show full size I do:

Display display = ((WindowManager)getSystemService(Context.WINDOW_SERVICE))
                           .getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();

推荐答案

不鼓励重写 onConfigurationChanged(),因为您需要做很多工作才能做到正确.

Overriding onConfigurationChanged() is discouraged because there's so much work you have to do to get it right.

您想要做的是在您的活动中实现 onRetainNonConfigurationInstance().当系统知道它将在稍后重新启动它时(例如屏幕旋转),它会在您的 Activity 被终止之前调用.

What you want to do is implement onRetainNonConfigurationInstance() in your activity. This is called just before your activity is killed when the system knows it will be restarting it in a moment (e.g. for screen rotation).

您对 onRetainNonConfigurationInstance() 的实现可能会返回它喜欢的任何对象('this' 是一个不错的选择,或者在您的情况下是您的缓存).此对象将被保留并可供下次调用您的活动使用.

Your implementation of onRetainNonConfigurationInstance() may return any object it likes ('this' is a good choice, or in your case, your cache). This object will be held and made available to the next invocation of your activity.

在您的 onCreate() 方法中,调用 getLastNonConfigurationInstance() 以检索系统为您保存的对象.如果此函数返回 null,请照常进行.如果它返回非空值,那么这将是您之前从 onRetainNonConfigurationInstance() 传回的对象,您可以从中提取任何您想要的信息.这通常意味着您不需要来自 savedInstanceState 包或已保存首选项的任何内容.

In your onCreate() method, call getLastNonConfigurationInstance() to retrieve the object the system is saving for you. If this function returns null, proceed as you would normally. If it returns non-null, then that will be the object you previously passed back from onRetainNonConfigurationInstance() and you can extract any information you want from it. This generally means that you don't need anything from the savedInstanceState bundle or from saved preferences.

我相信即使是打开的套接字、正在运行的线程和其他对象也可以通过这种方式在配置更改时保留.

I believe even open sockets, running threads, and other objects can be preserved across configuration changes this way.

附加:如果您确实通过 onRetaineNonConfigurationInstance() 传递this,请不要坚持下去.您将避免释放大量资源.提取您需要的信息,然后发布.

Adding on: If you do pass this through onRetaineNonConfigurationInstance(), don't hang on to it. You'll keep huge amounts of resources from being freed. Extract the information you need and then release it.

这篇关于旋转设备时保存缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆