开发者

Large images in WebView cause Out Of Memory

开发者 https://www.devze.com 2023-03-31 16:07 出处:网络
I have activity that parses XML feed (with news) and loads parsed data (text and image url) inWebView\'s, which are inside gallery widget.

I have activity that parses XML feed (with news) and loads parsed data (text and image url) in WebView's, which are inside gallery widget.

Something like this:

mimeType = "text/html";

encoding = "utf-8";

String html = "<img src=\""
+ newsImageUrl.get(position)
+ "\" style=\"max-width:200px; max-height:200px;\" align=\"left\""
+ "/>" + newsDescription.get(position);

data.loadDataWithBaseURL("", html, mimeType, encoding, "");

Everything works fine, but sometimes inside news feed there is this BIG IMAGES. Well, they dont cause any problems unless you start to rotate a phone. And after couple of orientation changes we have happy Out Of Memory exception.

Well, in Android, OOM is always hiding somewhere near Bitmas, that's why most people use BitmapFactory with inSampleSize, or something more exotic. Well, supposedly, I can download and resample images, and then just load them from SD card. But for now I will try to avoid it.

Anyway, the question is - what to do with large images when they are being loaded in WebView? Is there a way to resize the开发者_运维技巧m (not only visually)? Is there any way to clear memory occupied by WebView onOrientationChange (webview.freeMemory() doesn't really helps).


Actually, you don't have so many choices. Freeing memory doesn't help as your images are still allocated in memory, and the images are too big to fit.

The only workable way is to reduce their size, either at the source (this way you have nothing to do programmatically) or at download time, before you display them (you save them scaled down to the SD and you display these local copies instead of the source images).

This depends of whether you have to use the full-scale images at some point. If not, there's absolutely no point in keeping them so large.


Anyway, the problem was not in webview large images.

I downscaled app and apparently the problem was in my gallery widget design. To be more specific in graphical interface elements that surrounds it. Even with empty gallery after couple orientation changes I got oom.

And I found the reason to it only today. I used /drawables/ folder which downscales all images to mdpi. And all phones I tested it on was hdpi. Apparently android uses some maybe no so efficient scaling method, and it's leaking somewhere there.

I moved all my drawables to hdpi and mdpi folders and crashes magically stopped.

So, conclusion - avoid using /drawables/ folder.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号