Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
140 views
in Technique[技术] by (71.8m points)

android - Save cache when rotate device

I have a Gallerywiew.

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

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();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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).

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.

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.


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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...