Webview冻结在android中

时间:2014-12-27 05:52:28

标签: android webview bitmap

我试图捕获webview但是当我试图压缩位图webview冻结时。我尝试了很多,但我没有找到解决方案。请帮忙..

这里有一些代码:

        webview.getHeight();
        Picture p = webview.capturePicture();
        webview.setDrawingCacheEnabled(true);           
        Bitmap bitmap = pictureDrawable2Bitmap(p);
        webview.setDrawingCacheEnabled(false);

        String fname = System.currentTimeMillis() + ".png";
        File file1 = new File(fname);
        try 
        {
            FileOutputStream out = new FileOutputStream(file1);
            bitmap.compress(Bitmap.CompressFormat.PNG, 10, out);
            out.flush();
            out.close();
        } 
        catch (Exception e) 
        {
            e.printStackTrace();
        }


private static Bitmap pictureDrawable2Bitmap(Picture picture) 
{
    PictureDrawable pictureDrawable = new PictureDrawable(picture);
                Bitmap bitmap = null;
        try
        {
            bitmap =  Bitmap.createBitmap(pictureDrawable.getIntrinsicWidth(),pictureDrawable.getIntrinsicHeight(), Config.ARGB_8888);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        Canvas canvas = new Canvas(bitmap);
        canvas.drawPicture(pictureDrawable.getPicture());
        return bitmap;
}

1 个答案:

答案 0 :(得分:0)

根据建议,所有磁盘和网络操作都应该脱离主线程 为此,我们为您提供了ThreadAsyncTaskLoader类,我看到您在主线程上也使用了Bitmap,不建议这样做所需的资源量这就是为什么我们必须完成主线程的这个过程。

Android Developer documentation上有一个如何使用上述类完成此操作的详细示例,这里有一个示例,需要一个Bitmap加载线程(这是你正在尝试的事情之一)做):

class BitmapWorkerTask extends AsyncTask<Integer, Void, Bitmap> {
    private final WeakReference<ImageView> imageViewReference;
    private int data = 0;

    public BitmapWorkerTask(ImageView imageView) {
        // Use a WeakReference to ensure the ImageView can be garbage collected
        imageViewReference = new WeakReference<ImageView>(imageView);
    }

    // Decode image in background.
    @Override
    protected Bitmap doInBackground(Integer... params) {
        data = params[0];
        return decodeSampledBitmapFromResource(getResources(), data, 100, 100));
    }

    // Once complete, see if ImageView is still around and set bitmap.
    @Override
    protected void onPostExecute(Bitmap bitmap) {
        if (imageViewReference != null && bitmap != null) {
            final ImageView imageView = imageViewReference.get();
            if (imageView != null) {
                imageView.setImageBitmap(bitmap);
            }
        }
    }
}

以下是调用和加载位图的方法。

public void loadBitmap(int resId, ImageView imageView) {
    BitmapWorkerTask task = new BitmapWorkerTask(imageView);
    task.execute(resId);
}

正如您在上面看到的那样,使用网络或磁盘操作有点棘手,但Android Documentation充满了解决这些问题的示例。

希望你能解决问题。