2012-06-08 69 views
9

我使用viewpager来加载大约50个网页浏览...所有网页浏览都加载到了assests中,每个weview都有一个HTML页面,每个页面访问大约70个图像...当我滑动时,我的应用程序在大约30页后崩溃,可能是因为webviews仍然保留对引用文件夹中图像的引用......是否有任何方法可以释放Viewpager在特定时间未使用的Web视图?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

回答

1

尝试缩放时间位图的下降bitmap.Most是一个主要的原因,我们得到内存问题。 同时了解如何回收位图。 以下代码将帮助您。

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

感谢您的soln,但上面的问题是为webview! –

+1

@Vipul是的,我已覆盖destroyItem,仍然没有运气。 – Kiran

0

web视图的工作原理与JNI,这只能容纳512个本地引用,请尝试直接从网页加载的内容和问题不该不会发生。

我得到这个问题,当我覆盖shouldInterceptRequest(WebView view, String url)webviewclient和手本地引用从我自己的缓存机制。

这可能是webview本身的错误。至少,如果你问我,它不应该如何表现。

0

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

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { 
    webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null); 
} 

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