gpt4 book ai didi

android - Viewpager Webview 内存问题

转载 作者:IT王子 更新时间:2023-10-28 23:34:56 24 4
gpt4 key购买 nike

我正在使用 viewpager 加载大约 50 个 webviews...所有 webviews 都加载到 assests 中,每个 weview 都有一个 HTML 页面,每个页面访问大约 70 个图像...当我滑动时,我的应用程序在之后崩溃大约 30 页,可能是因为 webviews 仍然保留对 assests 文件夹中图像的引用......有没有办法释放 Viewpager 在那个特定时间没有使用的 webviews?

awesomePager.setAdapter(new AwesomePagerAdapter(this, webviewdata));

详情:

Android WebView Memory Leak when loading html file from Assets  
Failed adding to JNI local ref table (has 512 entries)
"Thread-375" prio=5 tid=15 RUNNABLE

同时在 viewpager 上动态加载 webview

Logcat: enter image description here

最佳答案

尝试缩小位图。大多数情况下,位图是我们遇到内存问题的主要原因。还了解如何回收位图。以下代码段将对您有所帮助。

BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile( filename, options );
options.inJustDecodeBounds = false;
options.inSampleSize = 2;

bitmap = BitmapFactory.decodeFile( filename, options );
if ( bitmap != null && exact ) {
bitmap = Bitmap.createScaledBitmap( bitmap, width, height, false );
}

还要确保您确实覆盖了以下方法。

@Override
public void destroyItem(View collection, int position, Object view) {
((ViewPager) collection).removeView((TextView) view);
}

或者你可以创建一个函数来缩小位图

private byte[] resizeImage( byte[] input ) {

if ( input == null ) {
return null;
}

Bitmap bitmapOrg = BitmapFactory.decodeByteArray(input, 0, input.length);

if ( bitmapOrg == null ) {
return null;
}

int height = bitmapOrg.getHeight();
int width = bitmapOrg.getWidth();
int newHeight = 250;

float scaleHeight = ((float) newHeight) / height;

// creates matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(scaleHeight, scaleHeight);

// recreate the new Bitmap
Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0,
width, height, matrix, true);

bitmapOrg.recycle();

ByteArrayOutputStream bos = new ByteArrayOutputStream();
resizedBitmap.compress(CompressFormat.PNG, 0 /*ignored for PNG*/, bos);

resizedBitmap.recycle();

return bos.toByteArray();
}

关于android - Viewpager Webview 内存问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10942929/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com