Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capture picture from WebView

Is it possible to listen for WebView page load full completed and then capture screenshot of loaded page?

I tried two ways, but they both not working:

  • using WebViewClient and onPageFinished(WebView view, String url).
    It doesn't work (and it described in docs) because Picture may be not ready it this moment

  • using WebView.PictureListener and onNewPicture(WebView view, Picture picture)
    It also doesn't solve problem, because this method calls undetermined times. At first time, picture often contains only part of page content. And I don't know way how determine, that the current call is last for the page.

I want to notice, that the problem is to find right moment to make screenshot, and not how it can be done.

like image 685
AlexKorovyansky Avatar asked Dec 27 '10 11:12

AlexKorovyansky


1 Answers

[Note that since I answered this, onNewPicture has been deprecated (see http://developer.android.com/reference/android/webkit/WebView.PictureListener.html and What does "This method is deprecated" mean for application developers). Unfortunately, there is no information on what replaces it, or at what API levels it was supported. I guess that means that you use this at your own risk.]

I think you’re correct that onNewPicture is the right place to capture a screenshot of a loaded WeView page, but also correct that it is hard to know when to actually do the capture.

It appears that WebView calls onNewPicture whenever there has been any drawing. For example, it calls onNewPicture repeatedly when the search bar is in keyboard entry mode and the cursor is flicking. Similarly, for some web pages (eg www.yelp.com/nyc) it calls onNewPicture repeatedly, even after the page has finished drawing, probably because of the flashing cursor in the Search box. But at the other extreme it will call onNewPicture only once (eg if the user drops down an iGoogle item).

So there’s no easy rule? The approach we’ve taken is to

  • monitor a range of events that are involved / affect page loading – such as shouldOverrideUrl, onPageFinished, focus changes, scrolling start/end, in addition to onNewPicture
  • run a timer (2secs is working well) on onNewPicture, reset by a new onNewPicture
  • implement a page loading FSM which uses the events and timer expiry as inputs, and moves through a series of state/action transitions, to the point where it decides it genuinely has a new picture.

Not pretty, but it works, with very few cases where it captures the same picture twice – and no cases where it fails to capture a picture where it should.

like image 196
Torid Avatar answered Sep 29 '22 11:09

Torid