Viewpager Webview内存问题

时间:2012-06-08 04:04:41

标签: android memory webview

我正在使用一个viewpager加载大约50个网页浏览...所有的网页浏览都被加载到assests中,每个weview都有一个HTML页面,每个页面可以访问大约70个图像...当我轻扫时,我的应用程序崩溃了大约30页,可能是webview的cos仍然保持对assests文件夹中图像的引用...有没有办法发布Viewpager在那个特定时间没有使用的webview?

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

2 个答案:

答案 0 :(得分:1)

尝试缩小位图。大多数时候Bitmap是导致内存问题的主要原因。 还要了解如何回收位图。 以下代码片段可以帮助您。

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();            
}       

答案 1 :(得分:0)

将webview的图层类型设置为软件。

struct TestStruct {
    var name : String?
    var age : Int

    init(name: String?, age: Int){
        self.name = name
        self.age = age
    }

    func printInfo(){
        //Since your name property is an optional, you should check for a nil before using it.
        print("Name:", (self.name ?? "") + "\nAge: \(self.age)")
    }
}

let myStruct = TestStruct(name: "Sandeep", age: 26)
myStruct.printInfo()

//output
Name: Sandeep
Age: 26

let myStruct2 = TestStruct(name: nil, age: 18)
myStruct2.printInfo()

//output 
Name: No Name provided
Age: 18

但是现在你失去了硬件加速,你的webview可能会变慢。