2

I want to convert HTML in Image in background without UI interaction. I found that using webview we can achieve this. But Android has deprecated webview.capturePicture(); method and for that we require UI interaction also.

ligi
  • 39,001
  • 44
  • 144
  • 244
  • check this out http://stackoverflow.com/questions/20942623/which-can-replace-capturepicture-function – jmhostalet Sep 29 '14 at 14:03
  • Hi,I already gone through this example. But same this require webview to use. and with webview we can not perform action in background service. Because we don't know when this service is going to call. – Binita Shah Sep 30 '14 at 08:57

1 Answers1

0

first instantiate new WebView in code with proper layout parameter:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    WebView.enableSlowWholeDocumentDraw();
}
WebView webView = new WebView(context);
FrameLayout frameLayout = new FrameLayout(context);
frameLayout.setLayoutParams(new FrameLayout.LayoutParams(512, 100));
webView.setLayoutParams(new FrameLayout.LayoutParams(512, FrameLayout.LayoutParams.WRAP_CONTENT));
frameLayout.addView(webView);
webView.setDrawingCacheEnabled(true);

then set a WebViewClient to listen when webview finish loading:

webView.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(final WebView view, String url) {
                return false;
            }
            @Override
            public void onPageFinished(final WebView view, String url) {
                Log.i("HTML", "page finished loading " + url);
                view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
                view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
                view.buildDrawingCache(true);

                Bitmap b = Bitmap.createBitmap(view.getDrawingCache());
                // bitmap is ready
                } ) ;

then load your html into WebView:

webView.loadDataWithBaseURL(null, YOUR_HTML_STRING, "text/html", "UTF-8", null);

IMPORTANT TIP: in all step make sure the webview width and height aren't zero;

Mohammad
  • 69
  • 10