WebView.java revision ffb81c4a779431d686a734f14cc5b81ac84a7fdd
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.webkit;
18
19import android.annotation.NonNull;
20import android.annotation.SystemApi;
21import android.annotation.Widget;
22import android.content.Context;
23import android.content.Intent;
24import android.content.res.Configuration;
25import android.graphics.Bitmap;
26import android.graphics.Canvas;
27import android.graphics.Paint;
28import android.graphics.Picture;
29import android.graphics.Rect;
30import android.graphics.drawable.Drawable;
31import android.net.http.SslCertificate;
32import android.net.Uri;
33import android.os.Build;
34import android.os.Bundle;
35import android.os.Handler;
36import android.os.Looper;
37import android.os.Message;
38import android.os.StrictMode;
39import android.print.PrintDocumentAdapter;
40import android.security.KeyChain;
41import android.util.AttributeSet;
42import android.util.Log;
43import android.view.DragEvent;
44import android.view.KeyEvent;
45import android.view.MotionEvent;
46import android.view.View;
47import android.view.ViewStructure;
48import android.view.ViewDebug;
49import android.view.ViewGroup;
50import android.view.ViewHierarchyEncoder;
51import android.view.ViewTreeObserver;
52import android.view.accessibility.AccessibilityEvent;
53import android.view.accessibility.AccessibilityNodeInfo;
54import android.view.accessibility.AccessibilityNodeProvider;
55import android.view.inputmethod.EditorInfo;
56import android.view.inputmethod.InputConnection;
57import android.widget.AbsoluteLayout;
58
59import java.io.BufferedWriter;
60import java.io.File;
61import java.util.Map;
62
63/**
64 * <p>A View that displays web pages. This class is the basis upon which you
65 * can roll your own web browser or simply display some online content within your Activity.
66 * It uses the WebKit rendering engine to display
67 * web pages and includes methods to navigate forward and backward
68 * through a history, zoom in and out, perform text searches and more.</p>
69 * <p>Note that, in order for your Activity to access the Internet and load web pages
70 * in a WebView, you must add the {@code INTERNET} permissions to your
71 * Android Manifest file:</p>
72 * <pre>&lt;uses-permission android:name="android.permission.INTERNET" /></pre>
73 *
74 * <p>This must be a child of the <a
75 * href="{@docRoot}guide/topics/manifest/manifest-element.html">{@code <manifest>}</a>
76 * element.</p>
77 *
78 * <p>For more information, read
79 * <a href="{@docRoot}guide/webapps/webview.html">Building Web Apps in WebView</a>.</p>
80 *
81 * <h3>Basic usage</h3>
82 *
83 * <p>By default, a WebView provides no browser-like widgets, does not
84 * enable JavaScript and web page errors are ignored. If your goal is only
85 * to display some HTML as a part of your UI, this is probably fine;
86 * the user won't need to interact with the web page beyond reading
87 * it, and the web page won't need to interact with the user. If you
88 * actually want a full-blown web browser, then you probably want to
89 * invoke the Browser application with a URL Intent rather than show it
90 * with a WebView. For example:
91 * <pre>
92 * Uri uri = Uri.parse("http://www.example.com");
93 * Intent intent = new Intent(Intent.ACTION_VIEW, uri);
94 * startActivity(intent);
95 * </pre>
96 * <p>See {@link android.content.Intent} for more information.</p>
97 *
98 * <p>To provide a WebView in your own Activity, include a {@code <WebView>} in your layout,
99 * or set the entire Activity window as a WebView during {@link
100 * android.app.Activity#onCreate(Bundle) onCreate()}:</p>
101 * <pre class="prettyprint">
102 * WebView webview = new WebView(this);
103 * setContentView(webview);
104 * </pre>
105 *
106 * <p>Then load the desired web page:</p>
107 * <pre>
108 * // Simplest usage: note that an exception will NOT be thrown
109 * // if there is an error loading this page (see below).
110 * webview.loadUrl("http://slashdot.org/");
111 *
112 * // OR, you can also load from an HTML string:
113 * String summary = "&lt;html>&lt;body>You scored &lt;b>192&lt;/b> points.&lt;/body>&lt;/html>";
114 * webview.loadData(summary, "text/html", null);
115 * // ... although note that there are restrictions on what this HTML can do.
116 * // See the JavaDocs for {@link #loadData(String,String,String) loadData()} and {@link
117 * #loadDataWithBaseURL(String,String,String,String,String) loadDataWithBaseURL()} for more info.
118 * </pre>
119 *
120 * <p>A WebView has several customization points where you can add your
121 * own behavior. These are:</p>
122 *
123 * <ul>
124 *   <li>Creating and setting a {@link android.webkit.WebChromeClient} subclass.
125 *       This class is called when something that might impact a
126 *       browser UI happens, for instance, progress updates and
127 *       JavaScript alerts are sent here (see <a
128 * href="{@docRoot}guide/developing/debug-tasks.html#DebuggingWebPages">Debugging Tasks</a>).
129 *   </li>
130 *   <li>Creating and setting a {@link android.webkit.WebViewClient} subclass.
131 *       It will be called when things happen that impact the
132 *       rendering of the content, eg, errors or form submissions. You
133 *       can also intercept URL loading here (via {@link
134 * android.webkit.WebViewClient#shouldOverrideUrlLoading(WebView,String)
135 * shouldOverrideUrlLoading()}).</li>
136 *   <li>Modifying the {@link android.webkit.WebSettings}, such as
137 * enabling JavaScript with {@link android.webkit.WebSettings#setJavaScriptEnabled(boolean)
138 * setJavaScriptEnabled()}. </li>
139 *   <li>Injecting Java objects into the WebView using the
140 *       {@link android.webkit.WebView#addJavascriptInterface} method. This
141 *       method allows you to inject Java objects into a page's JavaScript
142 *       context, so that they can be accessed by JavaScript in the page.</li>
143 * </ul>
144 *
145 * <p>Here's a more complicated example, showing error handling,
146 *    settings, and progress notification:</p>
147 *
148 * <pre class="prettyprint">
149 * // Let's display the progress in the activity title bar, like the
150 * // browser app does.
151 * getWindow().requestFeature(Window.FEATURE_PROGRESS);
152 *
153 * webview.getSettings().setJavaScriptEnabled(true);
154 *
155 * final Activity activity = this;
156 * webview.setWebChromeClient(new WebChromeClient() {
157 *   public void onProgressChanged(WebView view, int progress) {
158 *     // Activities and WebViews measure progress with different scales.
159 *     // The progress meter will automatically disappear when we reach 100%
160 *     activity.setProgress(progress * 1000);
161 *   }
162 * });
163 * webview.setWebViewClient(new WebViewClient() {
164 *   public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
165 *     Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
166 *   }
167 * });
168 *
169 * webview.loadUrl("http://developer.android.com/");
170 * </pre>
171 *
172 * <h3>Zoom</h3>
173 *
174 * <p>To enable the built-in zoom, set
175 * {@link #getSettings() WebSettings}.{@link WebSettings#setBuiltInZoomControls(boolean)}
176 * (introduced in API level {@link android.os.Build.VERSION_CODES#CUPCAKE}).</p>
177 * <p>NOTE: Using zoom if either the height or width is set to
178 * {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT} may lead to undefined behavior
179 * and should be avoided.</p>
180 *
181 * <h3>Cookie and window management</h3>
182 *
183 * <p>For obvious security reasons, your application has its own
184 * cache, cookie store etc.&mdash;it does not share the Browser
185 * application's data.
186 * </p>
187 *
188 * <p>By default, requests by the HTML to open new windows are
189 * ignored. This is true whether they be opened by JavaScript or by
190 * the target attribute on a link. You can customize your
191 * {@link WebChromeClient} to provide your own behavior for opening multiple windows,
192 * and render them in whatever manner you want.</p>
193 *
194 * <p>The standard behavior for an Activity is to be destroyed and
195 * recreated when the device orientation or any other configuration changes. This will cause
196 * the WebView to reload the current page. If you don't want that, you
197 * can set your Activity to handle the {@code orientation} and {@code keyboardHidden}
198 * changes, and then just leave the WebView alone. It'll automatically
199 * re-orient itself as appropriate. Read <a
200 * href="{@docRoot}guide/topics/resources/runtime-changes.html">Handling Runtime Changes</a> for
201 * more information about how to handle configuration changes during runtime.</p>
202 *
203 *
204 * <h3>Building web pages to support different screen densities</h3>
205 *
206 * <p>The screen density of a device is based on the screen resolution. A screen with low density
207 * has fewer available pixels per inch, where a screen with high density
208 * has more &mdash; sometimes significantly more &mdash; pixels per inch. The density of a
209 * screen is important because, other things being equal, a UI element (such as a button) whose
210 * height and width are defined in terms of screen pixels will appear larger on the lower density
211 * screen and smaller on the higher density screen.
212 * For simplicity, Android collapses all actual screen densities into three generalized densities:
213 * high, medium, and low.</p>
214 * <p>By default, WebView scales a web page so that it is drawn at a size that matches the default
215 * appearance on a medium density screen. So, it applies 1.5x scaling on a high density screen
216 * (because its pixels are smaller) and 0.75x scaling on a low density screen (because its pixels
217 * are bigger).
218 * Starting with API level {@link android.os.Build.VERSION_CODES#ECLAIR}, WebView supports DOM, CSS,
219 * and meta tag features to help you (as a web developer) target screens with different screen
220 * densities.</p>
221 * <p>Here's a summary of the features you can use to handle different screen densities:</p>
222 * <ul>
223 * <li>The {@code window.devicePixelRatio} DOM property. The value of this property specifies the
224 * default scaling factor used for the current device. For example, if the value of {@code
225 * window.devicePixelRatio} is "1.0", then the device is considered a medium density (mdpi) device
226 * and default scaling is not applied to the web page; if the value is "1.5", then the device is
227 * considered a high density device (hdpi) and the page content is scaled 1.5x; if the
228 * value is "0.75", then the device is considered a low density device (ldpi) and the content is
229 * scaled 0.75x.</li>
230 * <li>The {@code -webkit-device-pixel-ratio} CSS media query. Use this to specify the screen
231 * densities for which this style sheet is to be used. The corresponding value should be either
232 * "0.75", "1", or "1.5", to indicate that the styles are for devices with low density, medium
233 * density, or high density screens, respectively. For example:
234 * <pre>
235 * &lt;link rel="stylesheet" media="screen and (-webkit-device-pixel-ratio:1.5)" href="hdpi.css" /&gt;</pre>
236 * <p>The {@code hdpi.css} stylesheet is only used for devices with a screen pixel ration of 1.5,
237 * which is the high density pixel ratio.</p>
238 * </li>
239 * </ul>
240 *
241 * <h3>HTML5 Video support</h3>
242 *
243 * <p>In order to support inline HTML5 video in your application you need to have hardware
244 * acceleration turned on.
245 * </p>
246 *
247 * <h3>Full screen support</h3>
248 *
249 * <p>In order to support full screen &mdash; for video or other HTML content &mdash; you need to set a
250 * {@link android.webkit.WebChromeClient} and implement both
251 * {@link WebChromeClient#onShowCustomView(View, WebChromeClient.CustomViewCallback)}
252 * and {@link WebChromeClient#onHideCustomView()}. If the implementation of either of these two methods is
253 * missing then the web contents will not be allowed to enter full screen. Optionally you can implement
254 * {@link WebChromeClient#getVideoLoadingProgressView()} to customize the View displayed whilst a video
255 * is loading.
256 * </p>
257 *
258 * <h3>HTML5 Geolocation API support</h3>
259 *
260 * <p>For applications targeting Android N and later releases
261 * (API level > {@link android.os.Build.VERSION_CODES#M}) the geolocation api is only supported on
262 * secure origins such as https. For such applications requests to geolocation api on non-secure
263 * origins are automatically denied without invoking the corresponding
264 * {@link WebChromeClient#onGeolocationPermissionsShowPrompt(String, GeolocationPermissions.Callback)}
265 * method.
266 * </p>
267 *
268 * <h3>Layout size</h3>
269 * <p>
270 * It is recommended to set the WebView layout height to a fixed value or to
271 * {@link android.view.ViewGroup.LayoutParams#MATCH_PARENT} instead of using
272 * {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT}.
273 * When using {@link android.view.ViewGroup.LayoutParams#MATCH_PARENT}
274 * for the height none of the WebView's parents should use a
275 * {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT} layout height since that could result in
276 * incorrect sizing of the views.
277 * </p>
278 *
279 * <p>Setting the WebView's height to {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT}
280 * enables the following behaviors:
281 * <ul>
282 * <li>The HTML body layout height is set to a fixed value. This means that elements with a height
283 * relative to the HTML body may not be sized correctly. </li>
284 * <li>For applications targeting {@link android.os.Build.VERSION_CODES#KITKAT} and earlier SDKs the
285 * HTML viewport meta tag will be ignored in order to preserve backwards compatibility. </li>
286 * </ul>
287 * </p>
288 *
289 * <p>
290 * Using a layout width of {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT} is not
291 * supported. If such a width is used the WebView will attempt to use the width of the parent
292 * instead.
293 * </p>
294 *
295 * <h3>Metrics</h3>
296 *
297 * <p>
298 * WebView may upload anonymous diagnostic data to Google when the user has consented. This data
299 * helps Google improve WebView. Data is collected on a per-app basis for each app which has
300 * instantiated a WebView. An individual app can opt out of this feature by putting the following
301 * tag in its manifest:
302 * <pre>
303 * &lt;meta-data android:name="android.webkit.WebView.MetricsOptOut"
304 *            android:value="true" /&gt;
305 * </pre>
306 * </p>
307 * <p>
308 * Data will only be uploaded for a given app if the user has consented AND the app has not opted
309 * out.
310 * </p>
311 *
312 */
313// Implementation notes.
314// The WebView is a thin API class that delegates its public API to a backend WebViewProvider
315// class instance. WebView extends {@link AbsoluteLayout} for backward compatibility reasons.
316// Methods are delegated to the provider implementation: all public API methods introduced in this
317// file are fully delegated, whereas public and protected methods from the View base classes are
318// only delegated where a specific need exists for them to do so.
319@Widget
320public class WebView extends AbsoluteLayout
321        implements ViewTreeObserver.OnGlobalFocusChangeListener,
322        ViewGroup.OnHierarchyChangeListener, ViewDebug.HierarchyHandler {
323
324    /**
325     * Broadcast Action: Indicates the data reduction proxy setting changed.
326     * Sent by the settings app when user changes the data reduction proxy value. This intent will
327     * always stay as a hidden API.
328     * @hide
329     */
330    @SystemApi
331    public static final String DATA_REDUCTION_PROXY_SETTING_CHANGED =
332            "android.webkit.DATA_REDUCTION_PROXY_SETTING_CHANGED";
333
334    private static final String LOGTAG = "WebView";
335
336    // Throwing an exception for incorrect thread usage if the
337    // build target is JB MR2 or newer. Defaults to false, and is
338    // set in the WebView constructor.
339    private static volatile boolean sEnforceThreadChecking = false;
340
341    /**
342     *  Transportation object for returning WebView across thread boundaries.
343     */
344    public class WebViewTransport {
345        private WebView mWebview;
346
347        /**
348         * Sets the WebView to the transportation object.
349         *
350         * @param webview the WebView to transport
351         */
352        public synchronized void setWebView(WebView webview) {
353            mWebview = webview;
354        }
355
356        /**
357         * Gets the WebView object.
358         *
359         * @return the transported WebView object
360         */
361        public synchronized WebView getWebView() {
362            return mWebview;
363        }
364    }
365
366    /**
367     * URI scheme for telephone number.
368     */
369    public static final String SCHEME_TEL = "tel:";
370    /**
371     * URI scheme for email address.
372     */
373    public static final String SCHEME_MAILTO = "mailto:";
374    /**
375     * URI scheme for map address.
376     */
377    public static final String SCHEME_GEO = "geo:0,0?q=";
378
379    /**
380     * Interface to listen for find results.
381     */
382    public interface FindListener {
383        /**
384         * Notifies the listener about progress made by a find operation.
385         *
386         * @param activeMatchOrdinal the zero-based ordinal of the currently selected match
387         * @param numberOfMatches how many matches have been found
388         * @param isDoneCounting whether the find operation has actually completed. The listener
389         *                       may be notified multiple times while the
390         *                       operation is underway, and the numberOfMatches
391         *                       value should not be considered final unless
392         *                       isDoneCounting is true.
393         */
394        public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches,
395            boolean isDoneCounting);
396    }
397
398    /**
399     * Callback interface supplied to {@link #postVisualStateCallback} for receiving
400     * notifications about the visual state.
401     */
402    public static abstract class VisualStateCallback {
403        /**
404         * Invoked when the visual state is ready to be drawn in the next {@link #onDraw}.
405         *
406         * @param requestId The identifier passed to {@link #postVisualStateCallback} when this
407         *                  callback was posted.
408         */
409        public abstract void onComplete(long requestId);
410    }
411
412    /**
413     * Interface to listen for new pictures as they change.
414     *
415     * @deprecated This interface is now obsolete.
416     */
417    @Deprecated
418    public interface PictureListener {
419        /**
420         * Used to provide notification that the WebView's picture has changed.
421         * See {@link WebView#capturePicture} for details of the picture.
422         *
423         * @param view the WebView that owns the picture
424         * @param picture the new picture. Applications targeting
425         *     {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2} or above
426         *     will always receive a null Picture.
427         * @deprecated Deprecated due to internal changes.
428         */
429        @Deprecated
430        public void onNewPicture(WebView view, Picture picture);
431    }
432
433    public static class HitTestResult {
434        /**
435         * Default HitTestResult, where the target is unknown.
436         */
437        public static final int UNKNOWN_TYPE = 0;
438        /**
439         * @deprecated This type is no longer used.
440         */
441        @Deprecated
442        public static final int ANCHOR_TYPE = 1;
443        /**
444         * HitTestResult for hitting a phone number.
445         */
446        public static final int PHONE_TYPE = 2;
447        /**
448         * HitTestResult for hitting a map address.
449         */
450        public static final int GEO_TYPE = 3;
451        /**
452         * HitTestResult for hitting an email address.
453         */
454        public static final int EMAIL_TYPE = 4;
455        /**
456         * HitTestResult for hitting an HTML::img tag.
457         */
458        public static final int IMAGE_TYPE = 5;
459        /**
460         * @deprecated This type is no longer used.
461         */
462        @Deprecated
463        public static final int IMAGE_ANCHOR_TYPE = 6;
464        /**
465         * HitTestResult for hitting a HTML::a tag with src=http.
466         */
467        public static final int SRC_ANCHOR_TYPE = 7;
468        /**
469         * HitTestResult for hitting a HTML::a tag with src=http + HTML::img.
470         */
471        public static final int SRC_IMAGE_ANCHOR_TYPE = 8;
472        /**
473         * HitTestResult for hitting an edit text area.
474         */
475        public static final int EDIT_TEXT_TYPE = 9;
476
477        private int mType;
478        private String mExtra;
479
480        /**
481         * @hide Only for use by WebViewProvider implementations
482         */
483        @SystemApi
484        public HitTestResult() {
485            mType = UNKNOWN_TYPE;
486        }
487
488        /**
489         * @hide Only for use by WebViewProvider implementations
490         */
491        @SystemApi
492        public void setType(int type) {
493            mType = type;
494        }
495
496        /**
497         * @hide Only for use by WebViewProvider implementations
498         */
499        @SystemApi
500        public void setExtra(String extra) {
501            mExtra = extra;
502        }
503
504        /**
505         * Gets the type of the hit test result. See the XXX_TYPE constants
506         * defined in this class.
507         *
508         * @return the type of the hit test result
509         */
510        public int getType() {
511            return mType;
512        }
513
514        /**
515         * Gets additional type-dependant information about the result. See
516         * {@link WebView#getHitTestResult()} for details. May either be null
517         * or contain extra information about this result.
518         *
519         * @return additional type-dependant information about the result
520         */
521        public String getExtra() {
522            return mExtra;
523        }
524    }
525
526    /**
527     * Constructs a new WebView with a Context object.
528     *
529     * @param context a Context object used to access application assets
530     */
531    public WebView(Context context) {
532        this(context, null);
533    }
534
535    /**
536     * Constructs a new WebView with layout parameters.
537     *
538     * @param context a Context object used to access application assets
539     * @param attrs an AttributeSet passed to our parent
540     */
541    public WebView(Context context, AttributeSet attrs) {
542        this(context, attrs, com.android.internal.R.attr.webViewStyle);
543    }
544
545    /**
546     * Constructs a new WebView with layout parameters and a default style.
547     *
548     * @param context a Context object used to access application assets
549     * @param attrs an AttributeSet passed to our parent
550     * @param defStyleAttr an attribute in the current theme that contains a
551     *        reference to a style resource that supplies default values for
552     *        the view. Can be 0 to not look for defaults.
553     */
554    public WebView(Context context, AttributeSet attrs, int defStyleAttr) {
555        this(context, attrs, defStyleAttr, 0);
556    }
557
558    /**
559     * Constructs a new WebView with layout parameters and a default style.
560     *
561     * @param context a Context object used to access application assets
562     * @param attrs an AttributeSet passed to our parent
563     * @param defStyleAttr an attribute in the current theme that contains a
564     *        reference to a style resource that supplies default values for
565     *        the view. Can be 0 to not look for defaults.
566     * @param defStyleRes a resource identifier of a style resource that
567     *        supplies default values for the view, used only if
568     *        defStyleAttr is 0 or can not be found in the theme. Can be 0
569     *        to not look for defaults.
570     */
571    public WebView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
572        this(context, attrs, defStyleAttr, defStyleRes, null, false);
573    }
574
575    /**
576     * Constructs a new WebView with layout parameters and a default style.
577     *
578     * @param context a Context object used to access application assets
579     * @param attrs an AttributeSet passed to our parent
580     * @param defStyleAttr an attribute in the current theme that contains a
581     *        reference to a style resource that supplies default values for
582     *        the view. Can be 0 to not look for defaults.
583     * @param privateBrowsing whether this WebView will be initialized in
584     *                        private mode
585     *
586     * @deprecated Private browsing is no longer supported directly via
587     * WebView and will be removed in a future release. Prefer using
588     * {@link WebSettings}, {@link WebViewDatabase}, {@link CookieManager}
589     * and {@link WebStorage} for fine-grained control of privacy data.
590     */
591    @Deprecated
592    public WebView(Context context, AttributeSet attrs, int defStyleAttr,
593            boolean privateBrowsing) {
594        this(context, attrs, defStyleAttr, 0, null, privateBrowsing);
595    }
596
597    /**
598     * Constructs a new WebView with layout parameters, a default style and a set
599     * of custom JavaScript interfaces to be added to this WebView at initialization
600     * time. This guarantees that these interfaces will be available when the JS
601     * context is initialized.
602     *
603     * @param context a Context object used to access application assets
604     * @param attrs an AttributeSet passed to our parent
605     * @param defStyleAttr an attribute in the current theme that contains a
606     *        reference to a style resource that supplies default values for
607     *        the view. Can be 0 to not look for defaults.
608     * @param javaScriptInterfaces a Map of interface names, as keys, and
609     *                             object implementing those interfaces, as
610     *                             values
611     * @param privateBrowsing whether this WebView will be initialized in
612     *                        private mode
613     * @hide This is used internally by dumprendertree, as it requires the JavaScript interfaces to
614     *       be added synchronously, before a subsequent loadUrl call takes effect.
615     */
616    protected WebView(Context context, AttributeSet attrs, int defStyleAttr,
617            Map<String, Object> javaScriptInterfaces, boolean privateBrowsing) {
618        this(context, attrs, defStyleAttr, 0, javaScriptInterfaces, privateBrowsing);
619    }
620
621    /**
622     * @hide
623     */
624    @SuppressWarnings("deprecation")  // for super() call into deprecated base class constructor.
625    protected WebView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes,
626            Map<String, Object> javaScriptInterfaces, boolean privateBrowsing) {
627        super(context, attrs, defStyleAttr, defStyleRes);
628        if (context == null) {
629            throw new IllegalArgumentException("Invalid context argument");
630        }
631        sEnforceThreadChecking = context.getApplicationInfo().targetSdkVersion >=
632                Build.VERSION_CODES.JELLY_BEAN_MR2;
633        checkThread();
634
635        ensureProviderCreated();
636        mProvider.init(javaScriptInterfaces, privateBrowsing);
637        // Post condition of creating a webview is the CookieSyncManager.getInstance() is allowed.
638        CookieSyncManager.setGetInstanceIsAllowed();
639    }
640
641    /**
642     * Specifies whether the horizontal scrollbar has overlay style.
643     *
644     * @deprecated This method has no effect.
645     * @param overlay true if horizontal scrollbar should have overlay style
646     */
647    @Deprecated
648    public void setHorizontalScrollbarOverlay(boolean overlay) {
649    }
650
651    /**
652     * Specifies whether the vertical scrollbar has overlay style.
653     *
654     * @deprecated This method has no effect.
655     * @param overlay true if vertical scrollbar should have overlay style
656     */
657    @Deprecated
658    public void setVerticalScrollbarOverlay(boolean overlay) {
659    }
660
661    /**
662     * Gets whether horizontal scrollbar has overlay style.
663     *
664     * @deprecated This method is now obsolete.
665     * @return true
666     */
667    @Deprecated
668    public boolean overlayHorizontalScrollbar() {
669        // The old implementation defaulted to true, so return true for consistency
670        return true;
671    }
672
673    /**
674     * Gets whether vertical scrollbar has overlay style.
675     *
676     * @deprecated This method is now obsolete.
677     * @return false
678     */
679    @Deprecated
680    public boolean overlayVerticalScrollbar() {
681        // The old implementation defaulted to false, so return false for consistency
682        return false;
683    }
684
685    /**
686     * Gets the visible height (in pixels) of the embedded title bar (if any).
687     *
688     * @deprecated This method is now obsolete.
689     * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}
690     */
691    @Deprecated
692    public int getVisibleTitleHeight() {
693        checkThread();
694        return mProvider.getVisibleTitleHeight();
695    }
696
697    /**
698     * Gets the SSL certificate for the main top-level page or null if there is
699     * no certificate (the site is not secure).
700     *
701     * @return the SSL certificate for the main top-level page
702     */
703    public SslCertificate getCertificate() {
704        checkThread();
705        return mProvider.getCertificate();
706    }
707
708    /**
709     * Sets the SSL certificate for the main top-level page.
710     *
711     * @deprecated Calling this function has no useful effect, and will be
712     * ignored in future releases.
713     */
714    @Deprecated
715    public void setCertificate(SslCertificate certificate) {
716        checkThread();
717        mProvider.setCertificate(certificate);
718    }
719
720    //-------------------------------------------------------------------------
721    // Methods called by activity
722    //-------------------------------------------------------------------------
723
724    /**
725     * Sets a username and password pair for the specified host. This data is
726     * used by the WebView to autocomplete username and password fields in web
727     * forms. Note that this is unrelated to the credentials used for HTTP
728     * authentication.
729     *
730     * @param host the host that required the credentials
731     * @param username the username for the given host
732     * @param password the password for the given host
733     * @see WebViewDatabase#clearUsernamePassword
734     * @see WebViewDatabase#hasUsernamePassword
735     * @deprecated Saving passwords in WebView will not be supported in future versions.
736     */
737    @Deprecated
738    public void savePassword(String host, String username, String password) {
739        checkThread();
740        mProvider.savePassword(host, username, password);
741    }
742
743    /**
744     * Stores HTTP authentication credentials for a given host and realm to the {@link WebViewDatabase}
745     * instance.
746     * <p>
747     * To use HTTP authentication, the embedder application has to implement
748     * {@link WebViewClient#onReceivedHttpAuthRequest}, and call {@link HttpAuthHandler#proceed}
749     * with the correct username and password.
750     * <p>
751     * The embedder app can get the username and password any way it chooses, and does not have to
752     * use {@link WebViewDatabase}.
753     * <p>
754     * Notes:
755     * <li>
756     * {@link WebViewDatabase} is provided only as a convenience to store and retrieve http
757     * authentication credentials. WebView does not read from it during HTTP authentication.
758     * </li>
759     * <li>
760     * WebView does not provide a special mechanism to clear HTTP authentication credentials for
761     * implementing client logout. The client logout mechanism should be implemented by the Web site
762     * designer (such as server sending a HTTP 401 for invalidating credentials).
763     * </li>
764     *
765     * @param host the host to which the credentials apply
766     * @param realm the realm to which the credentials apply
767     * @param username the username
768     * @param password the password
769     * @see #getHttpAuthUsernamePassword
770     * @see WebViewDatabase#hasHttpAuthUsernamePassword
771     * @see WebViewDatabase#clearHttpAuthUsernamePassword
772     */
773    public void setHttpAuthUsernamePassword(String host, String realm,
774            String username, String password) {
775        checkThread();
776        mProvider.setHttpAuthUsernamePassword(host, realm, username, password);
777    }
778
779    /**
780     * Retrieves HTTP authentication credentials for a given host and realm from the {@link
781     * WebViewDatabase} instance.
782     *
783     * @param host the host to which the credentials apply
784     * @param realm the realm to which the credentials apply
785     * @return the credentials as a String array, if found. The first element
786     *         is the username and the second element is the password. Null if
787     *         no credentials are found.
788     * @see #setHttpAuthUsernamePassword
789     * @see WebViewDatabase#hasHttpAuthUsernamePassword
790     * @see WebViewDatabase#clearHttpAuthUsernamePassword
791     */
792    public String[] getHttpAuthUsernamePassword(String host, String realm) {
793        checkThread();
794        return mProvider.getHttpAuthUsernamePassword(host, realm);
795    }
796
797    /**
798     * Destroys the internal state of this WebView. This method should be called
799     * after this WebView has been removed from the view system. No other
800     * methods may be called on this WebView after destroy.
801     */
802    public void destroy() {
803        checkThread();
804        mProvider.destroy();
805    }
806
807    /**
808     * Enables platform notifications of data state and proxy changes.
809     * Notifications are enabled by default.
810     *
811     * @deprecated This method is now obsolete.
812     * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}
813     */
814    @Deprecated
815    public static void enablePlatformNotifications() {
816        // noop
817    }
818
819    /**
820     * Disables platform notifications of data state and proxy changes.
821     * Notifications are enabled by default.
822     *
823     * @deprecated This method is now obsolete.
824     * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}
825     */
826    @Deprecated
827    public static void disablePlatformNotifications() {
828        // noop
829    }
830
831    /**
832     * Used only by internal tests to free up memory.
833     *
834     * @hide
835     */
836    public static void freeMemoryForTests() {
837        getFactory().getStatics().freeMemoryForTests();
838    }
839
840    /**
841     * Informs WebView of the network state. This is used to set
842     * the JavaScript property window.navigator.isOnline and
843     * generates the online/offline event as specified in HTML5, sec. 5.7.7
844     *
845     * @param networkUp a boolean indicating if network is available
846     */
847    public void setNetworkAvailable(boolean networkUp) {
848        checkThread();
849        mProvider.setNetworkAvailable(networkUp);
850    }
851
852    /**
853     * Saves the state of this WebView used in
854     * {@link android.app.Activity#onSaveInstanceState}. Please note that this
855     * method no longer stores the display data for this WebView. The previous
856     * behavior could potentially leak files if {@link #restoreState} was never
857     * called.
858     *
859     * @param outState the Bundle to store this WebView's state
860     * @return the same copy of the back/forward list used to save the state. If
861     *         saveState fails, the returned list will be null.
862     */
863    public WebBackForwardList saveState(Bundle outState) {
864        checkThread();
865        return mProvider.saveState(outState);
866    }
867
868    /**
869     * Saves the current display data to the Bundle given. Used in conjunction
870     * with {@link #saveState}.
871     * @param b a Bundle to store the display data
872     * @param dest the file to store the serialized picture data. Will be
873     *             overwritten with this WebView's picture data.
874     * @return true if the picture was successfully saved
875     * @deprecated This method is now obsolete.
876     * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}
877     */
878    @Deprecated
879    public boolean savePicture(Bundle b, final File dest) {
880        checkThread();
881        return mProvider.savePicture(b, dest);
882    }
883
884    /**
885     * Restores the display data that was saved in {@link #savePicture}. Used in
886     * conjunction with {@link #restoreState}. Note that this will not work if
887     * this WebView is hardware accelerated.
888     *
889     * @param b a Bundle containing the saved display data
890     * @param src the file where the picture data was stored
891     * @return true if the picture was successfully restored
892     * @deprecated This method is now obsolete.
893     * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}
894     */
895    @Deprecated
896    public boolean restorePicture(Bundle b, File src) {
897        checkThread();
898        return mProvider.restorePicture(b, src);
899    }
900
901    /**
902     * Restores the state of this WebView from the given Bundle. This method is
903     * intended for use in {@link android.app.Activity#onRestoreInstanceState}
904     * and should be called to restore the state of this WebView. If
905     * it is called after this WebView has had a chance to build state (load
906     * pages, create a back/forward list, etc.) there may be undesirable
907     * side-effects. Please note that this method no longer restores the
908     * display data for this WebView.
909     *
910     * @param inState the incoming Bundle of state
911     * @return the restored back/forward list or null if restoreState failed
912     */
913    public WebBackForwardList restoreState(Bundle inState) {
914        checkThread();
915        return mProvider.restoreState(inState);
916    }
917
918    /**
919     * Loads the given URL with the specified additional HTTP headers.
920     * <p>
921     * Also see compatibility note on {@link #evaluateJavascript}.
922     *
923     * @param url the URL of the resource to load
924     * @param additionalHttpHeaders the additional headers to be used in the
925     *            HTTP request for this URL, specified as a map from name to
926     *            value. Note that if this map contains any of the headers
927     *            that are set by default by this WebView, such as those
928     *            controlling caching, accept types or the User-Agent, their
929     *            values may be overridden by this WebView's defaults.
930     */
931    public void loadUrl(String url, Map<String, String> additionalHttpHeaders) {
932        checkThread();
933        mProvider.loadUrl(url, additionalHttpHeaders);
934    }
935
936    /**
937     * Loads the given URL.
938     * <p>
939     * Also see compatibility note on {@link #evaluateJavascript}.
940     *
941     * @param url the URL of the resource to load
942     */
943    public void loadUrl(String url) {
944        checkThread();
945        mProvider.loadUrl(url);
946    }
947
948    /**
949     * Loads the URL with postData using "POST" method into this WebView. If url
950     * is not a network URL, it will be loaded with {@link #loadUrl(String)}
951     * instead, ignoring the postData param.
952     *
953     * @param url the URL of the resource to load
954     * @param postData the data will be passed to "POST" request, which must be
955     *     be "application/x-www-form-urlencoded" encoded.
956     */
957    public void postUrl(String url, byte[] postData) {
958        checkThread();
959        if (URLUtil.isNetworkUrl(url)) {
960            mProvider.postUrl(url, postData);
961        } else {
962            mProvider.loadUrl(url);
963        }
964    }
965
966    /**
967     * Loads the given data into this WebView using a 'data' scheme URL.
968     * <p>
969     * Note that JavaScript's same origin policy means that script running in a
970     * page loaded using this method will be unable to access content loaded
971     * using any scheme other than 'data', including 'http(s)'. To avoid this
972     * restriction, use {@link
973     * #loadDataWithBaseURL(String,String,String,String,String)
974     * loadDataWithBaseURL()} with an appropriate base URL.
975     * <p>
976     * The encoding parameter specifies whether the data is base64 or URL
977     * encoded. If the data is base64 encoded, the value of the encoding
978     * parameter must be 'base64'. For all other values of the parameter,
979     * including null, it is assumed that the data uses ASCII encoding for
980     * octets inside the range of safe URL characters and use the standard %xx
981     * hex encoding of URLs for octets outside that range. For example, '#',
982     * '%', '\', '?' should be replaced by %23, %25, %27, %3f respectively.
983     * <p>
984     * The 'data' scheme URL formed by this method uses the default US-ASCII
985     * charset. If you need need to set a different charset, you should form a
986     * 'data' scheme URL which explicitly specifies a charset parameter in the
987     * mediatype portion of the URL and call {@link #loadUrl(String)} instead.
988     * Note that the charset obtained from the mediatype portion of a data URL
989     * always overrides that specified in the HTML or XML document itself.
990     *
991     * @param data a String of data in the given encoding
992     * @param mimeType the MIME type of the data, e.g. 'text/html'
993     * @param encoding the encoding of the data
994     */
995    public void loadData(String data, String mimeType, String encoding) {
996        checkThread();
997        mProvider.loadData(data, mimeType, encoding);
998    }
999
1000    /**
1001     * Loads the given data into this WebView, using baseUrl as the base URL for
1002     * the content. The base URL is used both to resolve relative URLs and when
1003     * applying JavaScript's same origin policy. The historyUrl is used for the
1004     * history entry.
1005     * <p>
1006     * Note that content specified in this way can access local device files
1007     * (via 'file' scheme URLs) only if baseUrl specifies a scheme other than
1008     * 'http', 'https', 'ftp', 'ftps', 'about' or 'javascript'.
1009     * <p>
1010     * If the base URL uses the data scheme, this method is equivalent to
1011     * calling {@link #loadData(String,String,String) loadData()} and the
1012     * historyUrl is ignored, and the data will be treated as part of a data: URL.
1013     * If the base URL uses any other scheme, then the data will be loaded into
1014     * the WebView as a plain string (i.e. not part of a data URL) and any URL-encoded
1015     * entities in the string will not be decoded.
1016     * <p>
1017     * Note that the baseUrl is sent in the 'Referer' HTTP header when
1018     * requesting subresources (images, etc.) of the page loaded using this method.
1019     *
1020     * @param baseUrl the URL to use as the page's base URL. If null defaults to
1021     *                'about:blank'.
1022     * @param data a String of data in the given encoding
1023     * @param mimeType the MIMEType of the data, e.g. 'text/html'. If null,
1024     *                 defaults to 'text/html'.
1025     * @param encoding the encoding of the data
1026     * @param historyUrl the URL to use as the history entry. If null defaults
1027     *                   to 'about:blank'. If non-null, this must be a valid URL.
1028     */
1029    public void loadDataWithBaseURL(String baseUrl, String data,
1030            String mimeType, String encoding, String historyUrl) {
1031        checkThread();
1032        mProvider.loadDataWithBaseURL(baseUrl, data, mimeType, encoding, historyUrl);
1033    }
1034
1035    /**
1036     * Asynchronously evaluates JavaScript in the context of the currently displayed page.
1037     * If non-null, |resultCallback| will be invoked with any result returned from that
1038     * execution. This method must be called on the UI thread and the callback will
1039     * be made on the UI thread.
1040     * <p>
1041     * Compatibility note. Applications targeting {@link android.os.Build.VERSION_CODES#N} or
1042     * later, JavaScript state from an empty WebView is no longer persisted across navigations like
1043     * {@link #loadUrl(String)}. For example, global variables and functions defined before calling
1044     * {@link #loadUrl(String)} will not exist in the loaded page. Applications should use
1045     * {@link #addJavascriptInterface} instead to persist JavaScript objects across navigations.
1046     *
1047     * @param script the JavaScript to execute.
1048     * @param resultCallback A callback to be invoked when the script execution
1049     *                       completes with the result of the execution (if any).
1050     *                       May be null if no notification of the result is required.
1051     */
1052    public void evaluateJavascript(String script, ValueCallback<String> resultCallback) {
1053        checkThread();
1054        mProvider.evaluateJavaScript(script, resultCallback);
1055    }
1056
1057    /**
1058     * Saves the current view as a web archive.
1059     *
1060     * @param filename the filename where the archive should be placed
1061     */
1062    public void saveWebArchive(String filename) {
1063        checkThread();
1064        mProvider.saveWebArchive(filename);
1065    }
1066
1067    /**
1068     * Saves the current view as a web archive.
1069     *
1070     * @param basename the filename where the archive should be placed
1071     * @param autoname if false, takes basename to be a file. If true, basename
1072     *                 is assumed to be a directory in which a filename will be
1073     *                 chosen according to the URL of the current page.
1074     * @param callback called after the web archive has been saved. The
1075     *                 parameter for onReceiveValue will either be the filename
1076     *                 under which the file was saved, or null if saving the
1077     *                 file failed.
1078     */
1079    public void saveWebArchive(String basename, boolean autoname, ValueCallback<String> callback) {
1080        checkThread();
1081        mProvider.saveWebArchive(basename, autoname, callback);
1082    }
1083
1084    /**
1085     * Stops the current load.
1086     */
1087    public void stopLoading() {
1088        checkThread();
1089        mProvider.stopLoading();
1090    }
1091
1092    /**
1093     * Reloads the current URL.
1094     */
1095    public void reload() {
1096        checkThread();
1097        mProvider.reload();
1098    }
1099
1100    /**
1101     * Gets whether this WebView has a back history item.
1102     *
1103     * @return true iff this WebView has a back history item
1104     */
1105    public boolean canGoBack() {
1106        checkThread();
1107        return mProvider.canGoBack();
1108    }
1109
1110    /**
1111     * Goes back in the history of this WebView.
1112     */
1113    public void goBack() {
1114        checkThread();
1115        mProvider.goBack();
1116    }
1117
1118    /**
1119     * Gets whether this WebView has a forward history item.
1120     *
1121     * @return true iff this WebView has a forward history item
1122     */
1123    public boolean canGoForward() {
1124        checkThread();
1125        return mProvider.canGoForward();
1126    }
1127
1128    /**
1129     * Goes forward in the history of this WebView.
1130     */
1131    public void goForward() {
1132        checkThread();
1133        mProvider.goForward();
1134    }
1135
1136    /**
1137     * Gets whether the page can go back or forward the given
1138     * number of steps.
1139     *
1140     * @param steps the negative or positive number of steps to move the
1141     *              history
1142     */
1143    public boolean canGoBackOrForward(int steps) {
1144        checkThread();
1145        return mProvider.canGoBackOrForward(steps);
1146    }
1147
1148    /**
1149     * Goes to the history item that is the number of steps away from
1150     * the current item. Steps is negative if backward and positive
1151     * if forward.
1152     *
1153     * @param steps the number of steps to take back or forward in the back
1154     *              forward list
1155     */
1156    public void goBackOrForward(int steps) {
1157        checkThread();
1158        mProvider.goBackOrForward(steps);
1159    }
1160
1161    /**
1162     * Gets whether private browsing is enabled in this WebView.
1163     */
1164    public boolean isPrivateBrowsingEnabled() {
1165        checkThread();
1166        return mProvider.isPrivateBrowsingEnabled();
1167    }
1168
1169    /**
1170     * Scrolls the contents of this WebView up by half the view size.
1171     *
1172     * @param top true to jump to the top of the page
1173     * @return true if the page was scrolled
1174     */
1175    public boolean pageUp(boolean top) {
1176        checkThread();
1177        return mProvider.pageUp(top);
1178    }
1179
1180    /**
1181     * Scrolls the contents of this WebView down by half the page size.
1182     *
1183     * @param bottom true to jump to bottom of page
1184     * @return true if the page was scrolled
1185     */
1186    public boolean pageDown(boolean bottom) {
1187        checkThread();
1188        return mProvider.pageDown(bottom);
1189    }
1190
1191    /**
1192     * Posts a {@link VisualStateCallback}, which will be called when
1193     * the current state of the WebView is ready to be drawn.
1194     *
1195     * <p>Because updates to the DOM are processed asynchronously, updates to the DOM may not
1196     * immediately be reflected visually by subsequent {@link WebView#onDraw} invocations. The
1197     * {@link VisualStateCallback} provides a mechanism to notify the caller when the contents of
1198     * the DOM at the current time are ready to be drawn the next time the {@link WebView}
1199     * draws.</p>
1200     *
1201     * <p>The next draw after the callback completes is guaranteed to reflect all the updates to the
1202     * DOM up to the point at which the {@link VisualStateCallback} was posted, but it may also
1203     * contain updates applied after the callback was posted.</p>
1204     *
1205     * <p>The state of the DOM covered by this API includes the following:
1206     * <ul>
1207     * <li>primitive HTML elements (div, img, span, etc..)</li>
1208     * <li>images</li>
1209     * <li>CSS animations</li>
1210     * <li>WebGL</li>
1211     * <li>canvas</li>
1212     * </ul>
1213     * It does not include the state of:
1214     * <ul>
1215     * <li>the video tag</li>
1216     * </ul></p>
1217     *
1218     * <p>To guarantee that the {@link WebView} will successfully render the first frame
1219     * after the {@link VisualStateCallback#onComplete} method has been called a set of conditions
1220     * must be met:
1221     * <ul>
1222     * <li>If the {@link WebView}'s visibility is set to {@link View#VISIBLE VISIBLE} then
1223     * the {@link WebView} must be attached to the view hierarchy.</li>
1224     * <li>If the {@link WebView}'s visibility is set to {@link View#INVISIBLE INVISIBLE}
1225     * then the {@link WebView} must be attached to the view hierarchy and must be made
1226     * {@link View#VISIBLE VISIBLE} from the {@link VisualStateCallback#onComplete} method.</li>
1227     * <li>If the {@link WebView}'s visibility is set to {@link View#GONE GONE} then the
1228     * {@link WebView} must be attached to the view hierarchy and its
1229     * {@link AbsoluteLayout.LayoutParams LayoutParams}'s width and height need to be set to fixed
1230     * values and must be made {@link View#VISIBLE VISIBLE} from the
1231     * {@link VisualStateCallback#onComplete} method.</li>
1232     * </ul></p>
1233     *
1234     * <p>When using this API it is also recommended to enable pre-rasterization if the {@link
1235     * WebView} is off screen to avoid flickering. See {@link WebSettings#setOffscreenPreRaster} for
1236     * more details and do consider its caveats.</p>
1237     *
1238     * @param requestId An id that will be returned in the callback to allow callers to match
1239     *                  requests with callbacks.
1240     * @param callback  The callback to be invoked.
1241     */
1242    public void postVisualStateCallback(long requestId, VisualStateCallback callback) {
1243        checkThread();
1244        mProvider.insertVisualStateCallback(requestId, callback);
1245    }
1246
1247    /**
1248     * Clears this WebView so that onDraw() will draw nothing but white background,
1249     * and onMeasure() will return 0 if MeasureSpec is not MeasureSpec.EXACTLY.
1250     * @deprecated Use WebView.loadUrl("about:blank") to reliably reset the view state
1251     *             and release page resources (including any running JavaScript).
1252     */
1253    @Deprecated
1254    public void clearView() {
1255        checkThread();
1256        mProvider.clearView();
1257    }
1258
1259    /**
1260     * Gets a new picture that captures the current contents of this WebView.
1261     * The picture is of the entire document being displayed, and is not
1262     * limited to the area currently displayed by this WebView. Also, the
1263     * picture is a static copy and is unaffected by later changes to the
1264     * content being displayed.
1265     * <p>
1266     * Note that due to internal changes, for API levels between
1267     * {@link android.os.Build.VERSION_CODES#HONEYCOMB} and
1268     * {@link android.os.Build.VERSION_CODES#ICE_CREAM_SANDWICH} inclusive, the
1269     * picture does not include fixed position elements or scrollable divs.
1270     * <p>
1271     * Note that from {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1} the returned picture
1272     * should only be drawn into bitmap-backed Canvas - using any other type of Canvas will involve
1273     * additional conversion at a cost in memory and performance. Also the
1274     * {@link android.graphics.Picture#createFromStream} and
1275     * {@link android.graphics.Picture#writeToStream} methods are not supported on the
1276     * returned object.
1277     *
1278     * @deprecated Use {@link #onDraw} to obtain a bitmap snapshot of the WebView, or
1279     * {@link #saveWebArchive} to save the content to a file.
1280     *
1281     * @return a picture that captures the current contents of this WebView
1282     */
1283    @Deprecated
1284    public Picture capturePicture() {
1285        checkThread();
1286        return mProvider.capturePicture();
1287    }
1288
1289    /**
1290     * @deprecated Use {@link #createPrintDocumentAdapter(String)} which requires user
1291     *             to provide a print document name.
1292     */
1293    @Deprecated
1294    public PrintDocumentAdapter createPrintDocumentAdapter() {
1295        checkThread();
1296        return mProvider.createPrintDocumentAdapter("default");
1297    }
1298
1299    /**
1300     * Creates a PrintDocumentAdapter that provides the content of this WebView for printing.
1301     *
1302     * The adapter works by converting the WebView contents to a PDF stream. The WebView cannot
1303     * be drawn during the conversion process - any such draws are undefined. It is recommended
1304     * to use a dedicated off screen WebView for the printing. If necessary, an application may
1305     * temporarily hide a visible WebView by using a custom PrintDocumentAdapter instance
1306     * wrapped around the object returned and observing the onStart and onFinish methods. See
1307     * {@link android.print.PrintDocumentAdapter} for more information.
1308     *
1309     * @param documentName  The user-facing name of the printed document. See
1310     *                      {@link android.print.PrintDocumentInfo}
1311     */
1312    public PrintDocumentAdapter createPrintDocumentAdapter(String documentName) {
1313        checkThread();
1314        return mProvider.createPrintDocumentAdapter(documentName);
1315    }
1316
1317    /**
1318     * Gets the current scale of this WebView.
1319     *
1320     * @return the current scale
1321     *
1322     * @deprecated This method is prone to inaccuracy due to race conditions
1323     * between the web rendering and UI threads; prefer
1324     * {@link WebViewClient#onScaleChanged}.
1325     */
1326    @Deprecated
1327    @ViewDebug.ExportedProperty(category = "webview")
1328    public float getScale() {
1329        checkThread();
1330        return mProvider.getScale();
1331    }
1332
1333    /**
1334     * Sets the initial scale for this WebView. 0 means default.
1335     * The behavior for the default scale depends on the state of
1336     * {@link WebSettings#getUseWideViewPort()} and
1337     * {@link WebSettings#getLoadWithOverviewMode()}.
1338     * If the content fits into the WebView control by width, then
1339     * the zoom is set to 100%. For wide content, the behavior
1340     * depends on the state of {@link WebSettings#getLoadWithOverviewMode()}.
1341     * If its value is true, the content will be zoomed out to be fit
1342     * by width into the WebView control, otherwise not.
1343     *
1344     * If initial scale is greater than 0, WebView starts with this value
1345     * as initial scale.
1346     * Please note that unlike the scale properties in the viewport meta tag,
1347     * this method doesn't take the screen density into account.
1348     *
1349     * @param scaleInPercent the initial scale in percent
1350     */
1351    public void setInitialScale(int scaleInPercent) {
1352        checkThread();
1353        mProvider.setInitialScale(scaleInPercent);
1354    }
1355
1356    /**
1357     * Invokes the graphical zoom picker widget for this WebView. This will
1358     * result in the zoom widget appearing on the screen to control the zoom
1359     * level of this WebView.
1360     */
1361    public void invokeZoomPicker() {
1362        checkThread();
1363        mProvider.invokeZoomPicker();
1364    }
1365
1366    /**
1367     * Gets a HitTestResult based on the current cursor node. If a HTML::a
1368     * tag is found and the anchor has a non-JavaScript URL, the HitTestResult
1369     * type is set to SRC_ANCHOR_TYPE and the URL is set in the "extra" field.
1370     * If the anchor does not have a URL or if it is a JavaScript URL, the type
1371     * will be UNKNOWN_TYPE and the URL has to be retrieved through
1372     * {@link #requestFocusNodeHref} asynchronously. If a HTML::img tag is
1373     * found, the HitTestResult type is set to IMAGE_TYPE and the URL is set in
1374     * the "extra" field. A type of
1375     * SRC_IMAGE_ANCHOR_TYPE indicates an anchor with a URL that has an image as
1376     * a child node. If a phone number is found, the HitTestResult type is set
1377     * to PHONE_TYPE and the phone number is set in the "extra" field of
1378     * HitTestResult. If a map address is found, the HitTestResult type is set
1379     * to GEO_TYPE and the address is set in the "extra" field of HitTestResult.
1380     * If an email address is found, the HitTestResult type is set to EMAIL_TYPE
1381     * and the email is set in the "extra" field of HitTestResult. Otherwise,
1382     * HitTestResult type is set to UNKNOWN_TYPE.
1383     */
1384    public HitTestResult getHitTestResult() {
1385        checkThread();
1386        return mProvider.getHitTestResult();
1387    }
1388
1389    /**
1390     * Requests the anchor or image element URL at the last tapped point.
1391     * If hrefMsg is null, this method returns immediately and does not
1392     * dispatch hrefMsg to its target. If the tapped point hits an image,
1393     * an anchor, or an image in an anchor, the message associates
1394     * strings in named keys in its data. The value paired with the key
1395     * may be an empty string.
1396     *
1397     * @param hrefMsg the message to be dispatched with the result of the
1398     *                request. The message data contains three keys. "url"
1399     *                returns the anchor's href attribute. "title" returns the
1400     *                anchor's text. "src" returns the image's src attribute.
1401     */
1402    public void requestFocusNodeHref(Message hrefMsg) {
1403        checkThread();
1404        mProvider.requestFocusNodeHref(hrefMsg);
1405    }
1406
1407    /**
1408     * Requests the URL of the image last touched by the user. msg will be sent
1409     * to its target with a String representing the URL as its object.
1410     *
1411     * @param msg the message to be dispatched with the result of the request
1412     *            as the data member with "url" as key. The result can be null.
1413     */
1414    public void requestImageRef(Message msg) {
1415        checkThread();
1416        mProvider.requestImageRef(msg);
1417    }
1418
1419    /**
1420     * Gets the URL for the current page. This is not always the same as the URL
1421     * passed to WebViewClient.onPageStarted because although the load for
1422     * that URL has begun, the current page may not have changed.
1423     *
1424     * @return the URL for the current page
1425     */
1426    @ViewDebug.ExportedProperty(category = "webview")
1427    public String getUrl() {
1428        checkThread();
1429        return mProvider.getUrl();
1430    }
1431
1432    /**
1433     * Gets the original URL for the current page. This is not always the same
1434     * as the URL passed to WebViewClient.onPageStarted because although the
1435     * load for that URL has begun, the current page may not have changed.
1436     * Also, there may have been redirects resulting in a different URL to that
1437     * originally requested.
1438     *
1439     * @return the URL that was originally requested for the current page
1440     */
1441    @ViewDebug.ExportedProperty(category = "webview")
1442    public String getOriginalUrl() {
1443        checkThread();
1444        return mProvider.getOriginalUrl();
1445    }
1446
1447    /**
1448     * Gets the title for the current page. This is the title of the current page
1449     * until WebViewClient.onReceivedTitle is called.
1450     *
1451     * @return the title for the current page
1452     */
1453    @ViewDebug.ExportedProperty(category = "webview")
1454    public String getTitle() {
1455        checkThread();
1456        return mProvider.getTitle();
1457    }
1458
1459    /**
1460     * Gets the favicon for the current page. This is the favicon of the current
1461     * page until WebViewClient.onReceivedIcon is called.
1462     *
1463     * @return the favicon for the current page
1464     */
1465    public Bitmap getFavicon() {
1466        checkThread();
1467        return mProvider.getFavicon();
1468    }
1469
1470    /**
1471     * Gets the touch icon URL for the apple-touch-icon <link> element, or
1472     * a URL on this site's server pointing to the standard location of a
1473     * touch icon.
1474     *
1475     * @hide
1476     */
1477    public String getTouchIconUrl() {
1478        return mProvider.getTouchIconUrl();
1479    }
1480
1481    /**
1482     * Gets the progress for the current page.
1483     *
1484     * @return the progress for the current page between 0 and 100
1485     */
1486    public int getProgress() {
1487        checkThread();
1488        return mProvider.getProgress();
1489    }
1490
1491    /**
1492     * Gets the height of the HTML content.
1493     *
1494     * @return the height of the HTML content
1495     */
1496    @ViewDebug.ExportedProperty(category = "webview")
1497    public int getContentHeight() {
1498        checkThread();
1499        return mProvider.getContentHeight();
1500    }
1501
1502    /**
1503     * Gets the width of the HTML content.
1504     *
1505     * @return the width of the HTML content
1506     * @hide
1507     */
1508    @ViewDebug.ExportedProperty(category = "webview")
1509    public int getContentWidth() {
1510        return mProvider.getContentWidth();
1511    }
1512
1513    /**
1514     * Pauses all layout, parsing, and JavaScript timers for all WebViews. This
1515     * is a global requests, not restricted to just this WebView. This can be
1516     * useful if the application has been paused.
1517     */
1518    public void pauseTimers() {
1519        checkThread();
1520        mProvider.pauseTimers();
1521    }
1522
1523    /**
1524     * Resumes all layout, parsing, and JavaScript timers for all WebViews.
1525     * This will resume dispatching all timers.
1526     */
1527    public void resumeTimers() {
1528        checkThread();
1529        mProvider.resumeTimers();
1530    }
1531
1532    /**
1533     * Does a best-effort attempt to pause any processing that can be paused
1534     * safely, such as animations and geolocation. Note that this call
1535     * does not pause JavaScript. To pause JavaScript globally, use
1536     * {@link #pauseTimers}.
1537     *
1538     * To resume WebView, call {@link #onResume}.
1539     */
1540    public void onPause() {
1541        checkThread();
1542        mProvider.onPause();
1543    }
1544
1545    /**
1546     * Resumes a WebView after a previous call to {@link #onPause}.
1547     */
1548    public void onResume() {
1549        checkThread();
1550        mProvider.onResume();
1551    }
1552
1553    /**
1554     * Gets whether this WebView is paused, meaning onPause() was called.
1555     * Calling onResume() sets the paused state back to false.
1556     *
1557     * @hide
1558     */
1559    public boolean isPaused() {
1560        return mProvider.isPaused();
1561    }
1562
1563    /**
1564     * Informs this WebView that memory is low so that it can free any available
1565     * memory.
1566     * @deprecated Memory caches are automatically dropped when no longer needed, and in response
1567     *             to system memory pressure.
1568     */
1569    @Deprecated
1570    public void freeMemory() {
1571        checkThread();
1572        mProvider.freeMemory();
1573    }
1574
1575    /**
1576     * Clears the resource cache. Note that the cache is per-application, so
1577     * this will clear the cache for all WebViews used.
1578     *
1579     * @param includeDiskFiles if false, only the RAM cache is cleared
1580     */
1581    public void clearCache(boolean includeDiskFiles) {
1582        checkThread();
1583        mProvider.clearCache(includeDiskFiles);
1584    }
1585
1586    /**
1587     * Removes the autocomplete popup from the currently focused form field, if
1588     * present. Note this only affects the display of the autocomplete popup,
1589     * it does not remove any saved form data from this WebView's store. To do
1590     * that, use {@link WebViewDatabase#clearFormData}.
1591     */
1592    public void clearFormData() {
1593        checkThread();
1594        mProvider.clearFormData();
1595    }
1596
1597    /**
1598     * Tells this WebView to clear its internal back/forward list.
1599     */
1600    public void clearHistory() {
1601        checkThread();
1602        mProvider.clearHistory();
1603    }
1604
1605    /**
1606     * Clears the SSL preferences table stored in response to proceeding with
1607     * SSL certificate errors.
1608     */
1609    public void clearSslPreferences() {
1610        checkThread();
1611        mProvider.clearSslPreferences();
1612    }
1613
1614    /**
1615     * Clears the client certificate preferences stored in response
1616     * to proceeding/cancelling client cert requests. Note that WebView
1617     * automatically clears these preferences when it receives a
1618     * {@link KeyChain#ACTION_STORAGE_CHANGED} intent. The preferences are
1619     * shared by all the WebViews that are created by the embedder application.
1620     *
1621     * @param onCleared  A runnable to be invoked when client certs are cleared.
1622     *                   The embedder can pass null if not interested in the
1623     *                   callback. The runnable will be called in UI thread.
1624     */
1625    public static void clearClientCertPreferences(Runnable onCleared) {
1626        getFactory().getStatics().clearClientCertPreferences(onCleared);
1627    }
1628
1629    /**
1630     * Gets the WebBackForwardList for this WebView. This contains the
1631     * back/forward list for use in querying each item in the history stack.
1632     * This is a copy of the private WebBackForwardList so it contains only a
1633     * snapshot of the current state. Multiple calls to this method may return
1634     * different objects. The object returned from this method will not be
1635     * updated to reflect any new state.
1636     */
1637    public WebBackForwardList copyBackForwardList() {
1638        checkThread();
1639        return mProvider.copyBackForwardList();
1640
1641    }
1642
1643    /**
1644     * Registers the listener to be notified as find-on-page operations
1645     * progress. This will replace the current listener.
1646     *
1647     * @param listener an implementation of {@link FindListener}
1648     */
1649    public void setFindListener(FindListener listener) {
1650        checkThread();
1651        setupFindListenerIfNeeded();
1652        mFindListener.mUserFindListener = listener;
1653    }
1654
1655    /**
1656     * Highlights and scrolls to the next match found by
1657     * {@link #findAllAsync}, wrapping around page boundaries as necessary.
1658     * Notifies any registered {@link FindListener}. If {@link #findAllAsync(String)}
1659     * has not been called yet, or if {@link #clearMatches} has been called since the
1660     * last find operation, this function does nothing.
1661     *
1662     * @param forward the direction to search
1663     * @see #setFindListener
1664     */
1665    public void findNext(boolean forward) {
1666        checkThread();
1667        mProvider.findNext(forward);
1668    }
1669
1670    /**
1671     * Finds all instances of find on the page and highlights them.
1672     * Notifies any registered {@link FindListener}.
1673     *
1674     * @param find the string to find
1675     * @return the number of occurrences of the String "find" that were found
1676     * @deprecated {@link #findAllAsync} is preferred.
1677     * @see #setFindListener
1678     */
1679    @Deprecated
1680    public int findAll(String find) {
1681        checkThread();
1682        StrictMode.noteSlowCall("findAll blocks UI: prefer findAllAsync");
1683        return mProvider.findAll(find);
1684    }
1685
1686    /**
1687     * Finds all instances of find on the page and highlights them,
1688     * asynchronously. Notifies any registered {@link FindListener}.
1689     * Successive calls to this will cancel any pending searches.
1690     *
1691     * @param find the string to find.
1692     * @see #setFindListener
1693     */
1694    public void findAllAsync(String find) {
1695        checkThread();
1696        mProvider.findAllAsync(find);
1697    }
1698
1699    /**
1700     * Starts an ActionMode for finding text in this WebView.  Only works if this
1701     * WebView is attached to the view system.
1702     *
1703     * @param text if non-null, will be the initial text to search for.
1704     *             Otherwise, the last String searched for in this WebView will
1705     *             be used to start.
1706     * @param showIme if true, show the IME, assuming the user will begin typing.
1707     *                If false and text is non-null, perform a find all.
1708     * @return true if the find dialog is shown, false otherwise
1709     * @deprecated This method does not work reliably on all Android versions;
1710     *             implementing a custom find dialog using WebView.findAllAsync()
1711     *             provides a more robust solution.
1712     */
1713    @Deprecated
1714    public boolean showFindDialog(String text, boolean showIme) {
1715        checkThread();
1716        return mProvider.showFindDialog(text, showIme);
1717    }
1718
1719    /**
1720     * Gets the first substring consisting of the address of a physical
1721     * location. Currently, only addresses in the United States are detected,
1722     * and consist of:
1723     * <ul>
1724     *   <li>a house number</li>
1725     *   <li>a street name</li>
1726     *   <li>a street type (Road, Circle, etc), either spelled out or
1727     *       abbreviated</li>
1728     *   <li>a city name</li>
1729     *   <li>a state or territory, either spelled out or two-letter abbr</li>
1730     *   <li>an optional 5 digit or 9 digit zip code</li>
1731     * </ul>
1732     * All names must be correctly capitalized, and the zip code, if present,
1733     * must be valid for the state. The street type must be a standard USPS
1734     * spelling or abbreviation. The state or territory must also be spelled
1735     * or abbreviated using USPS standards. The house number may not exceed
1736     * five digits.
1737     *
1738     * @param addr the string to search for addresses
1739     * @return the address, or if no address is found, null
1740     */
1741    public static String findAddress(String addr) {
1742        // TODO: Rewrite this in Java so it is not needed to start up chromium
1743        // Could also be deprecated
1744        return getFactory().getStatics().findAddress(addr);
1745    }
1746
1747    /**
1748     * For apps targeting the L release, WebView has a new default behavior that reduces
1749     * memory footprint and increases performance by intelligently choosing
1750     * the portion of the HTML document that needs to be drawn. These
1751     * optimizations are transparent to the developers. However, under certain
1752     * circumstances, an App developer may want to disable them:
1753     * <ol>
1754     *   <li>When an app uses {@link #onDraw} to do own drawing and accesses portions
1755     *       of the page that is way outside the visible portion of the page.</li>
1756     *   <li>When an app uses {@link #capturePicture} to capture a very large HTML document.
1757     *       Note that capturePicture is a deprecated API.</li>
1758     * </ol>
1759     * Enabling drawing the entire HTML document has a significant performance
1760     * cost. This method should be called before any WebViews are created.
1761     */
1762    public static void enableSlowWholeDocumentDraw() {
1763        getFactory().getStatics().enableSlowWholeDocumentDraw();
1764    }
1765
1766    /**
1767     * Clears the highlighting surrounding text matches created by
1768     * {@link #findAllAsync}.
1769     */
1770    public void clearMatches() {
1771        checkThread();
1772        mProvider.clearMatches();
1773    }
1774
1775    /**
1776     * Queries the document to see if it contains any image references. The
1777     * message object will be dispatched with arg1 being set to 1 if images
1778     * were found and 0 if the document does not reference any images.
1779     *
1780     * @param response the message that will be dispatched with the result
1781     */
1782    public void documentHasImages(Message response) {
1783        checkThread();
1784        mProvider.documentHasImages(response);
1785    }
1786
1787    /**
1788     * Sets the WebViewClient that will receive various notifications and
1789     * requests. This will replace the current handler.
1790     *
1791     * @param client an implementation of WebViewClient
1792     */
1793    public void setWebViewClient(WebViewClient client) {
1794        checkThread();
1795        mProvider.setWebViewClient(client);
1796    }
1797
1798    /**
1799     * Registers the interface to be used when content can not be handled by
1800     * the rendering engine, and should be downloaded instead. This will replace
1801     * the current handler.
1802     *
1803     * @param listener an implementation of DownloadListener
1804     */
1805    public void setDownloadListener(DownloadListener listener) {
1806        checkThread();
1807        mProvider.setDownloadListener(listener);
1808    }
1809
1810    /**
1811     * Sets the chrome handler. This is an implementation of WebChromeClient for
1812     * use in handling JavaScript dialogs, favicons, titles, and the progress.
1813     * This will replace the current handler.
1814     *
1815     * @param client an implementation of WebChromeClient
1816     */
1817    public void setWebChromeClient(WebChromeClient client) {
1818        checkThread();
1819        mProvider.setWebChromeClient(client);
1820    }
1821
1822    /**
1823     * Sets the Picture listener. This is an interface used to receive
1824     * notifications of a new Picture.
1825     *
1826     * @param listener an implementation of WebView.PictureListener
1827     * @deprecated This method is now obsolete.
1828     */
1829    @Deprecated
1830    public void setPictureListener(PictureListener listener) {
1831        checkThread();
1832        mProvider.setPictureListener(listener);
1833    }
1834
1835    /**
1836     * Injects the supplied Java object into this WebView. The object is
1837     * injected into the JavaScript context of the main frame, using the
1838     * supplied name. This allows the Java object's methods to be
1839     * accessed from JavaScript. For applications targeted to API
1840     * level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}
1841     * and above, only public methods that are annotated with
1842     * {@link android.webkit.JavascriptInterface} can be accessed from JavaScript.
1843     * For applications targeted to API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN} or below,
1844     * all public methods (including the inherited ones) can be accessed, see the
1845     * important security note below for implications.
1846     * <p> Note that injected objects will not
1847     * appear in JavaScript until the page is next (re)loaded. For example:
1848     * <pre>
1849     * class JsObject {
1850     *    {@literal @}JavascriptInterface
1851     *    public String toString() { return "injectedObject"; }
1852     * }
1853     * webView.addJavascriptInterface(new JsObject(), "injectedObject");
1854     * webView.loadData("<!DOCTYPE html><title></title>", "text/html", null);
1855     * webView.loadUrl("javascript:alert(injectedObject.toString())");</pre>
1856     * <p>
1857     * <strong>IMPORTANT:</strong>
1858     * <ul>
1859     * <li> This method can be used to allow JavaScript to control the host
1860     * application. This is a powerful feature, but also presents a security
1861     * risk for apps targeting {@link android.os.Build.VERSION_CODES#JELLY_BEAN} or earlier.
1862     * Apps that target a version later than {@link android.os.Build.VERSION_CODES#JELLY_BEAN}
1863     * are still vulnerable if the app runs on a device running Android earlier than 4.2.
1864     * The most secure way to use this method is to target {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}
1865     * and to ensure the method is called only when running on Android 4.2 or later.
1866     * With these older versions, JavaScript could use reflection to access an
1867     * injected object's public fields. Use of this method in a WebView
1868     * containing untrusted content could allow an attacker to manipulate the
1869     * host application in unintended ways, executing Java code with the
1870     * permissions of the host application. Use extreme care when using this
1871     * method in a WebView which could contain untrusted content.</li>
1872     * <li> JavaScript interacts with Java object on a private, background
1873     * thread of this WebView. Care is therefore required to maintain thread
1874     * safety.
1875     * </li>
1876     * <li> The Java object's fields are not accessible.</li>
1877     * <li> For applications targeted to API level {@link android.os.Build.VERSION_CODES#LOLLIPOP}
1878     * and above, methods of injected Java objects are enumerable from
1879     * JavaScript.</li>
1880     * </ul>
1881     *
1882     * @param object the Java object to inject into this WebView's JavaScript
1883     *               context. Null values are ignored.
1884     * @param name the name used to expose the object in JavaScript
1885     */
1886    public void addJavascriptInterface(Object object, String name) {
1887        checkThread();
1888        mProvider.addJavascriptInterface(object, name);
1889    }
1890
1891    /**
1892     * Removes a previously injected Java object from this WebView. Note that
1893     * the removal will not be reflected in JavaScript until the page is next
1894     * (re)loaded. See {@link #addJavascriptInterface}.
1895     *
1896     * @param name the name used to expose the object in JavaScript
1897     */
1898    public void removeJavascriptInterface(String name) {
1899        checkThread();
1900        mProvider.removeJavascriptInterface(name);
1901    }
1902
1903    /**
1904     * Creates a message channel to communicate with JS and returns the message
1905     * ports that represent the endpoints of this message channel. The HTML5 message
1906     * channel functionality is described
1907     * <a href="https://html.spec.whatwg.org/multipage/comms.html#messagechannel">here
1908     * </a>
1909     *
1910     * <p>The returned message channels are entangled and already in started state.</p>
1911     *
1912     * @return the two message ports that form the message channel.
1913     */
1914    public WebMessagePort[] createWebMessageChannel() {
1915        checkThread();
1916        return mProvider.createWebMessageChannel();
1917    }
1918
1919    /**
1920     * Post a message to main frame. The embedded application can restrict the
1921     * messages to a certain target origin. See
1922     * <a href="https://html.spec.whatwg.org/multipage/comms.html#posting-messages">
1923     * HTML5 spec</a> for how target origin can be used.
1924     *
1925     * @param message the WebMessage
1926     * @param targetOrigin the target origin. This is the origin of the page
1927     *          that is intended to receive the message. For best security
1928     *          practices, the user should not specify a wildcard (*) when
1929     *          specifying the origin.
1930     */
1931    public void postWebMessage(WebMessage message, Uri targetOrigin) {
1932        checkThread();
1933        mProvider.postMessageToMainFrame(message, targetOrigin);
1934    }
1935
1936    /**
1937     * Gets the WebSettings object used to control the settings for this
1938     * WebView.
1939     *
1940     * @return a WebSettings object that can be used to control this WebView's
1941     *         settings
1942     */
1943    public WebSettings getSettings() {
1944        checkThread();
1945        return mProvider.getSettings();
1946    }
1947
1948    /**
1949     * Enables debugging of web contents (HTML / CSS / JavaScript)
1950     * loaded into any WebViews of this application. This flag can be enabled
1951     * in order to facilitate debugging of web layouts and JavaScript
1952     * code running inside WebViews. Please refer to WebView documentation
1953     * for the debugging guide.
1954     *
1955     * The default is false.
1956     *
1957     * @param enabled whether to enable web contents debugging
1958     */
1959    public static void setWebContentsDebuggingEnabled(boolean enabled) {
1960        getFactory().getStatics().setWebContentsDebuggingEnabled(enabled);
1961    }
1962
1963    /**
1964     * Gets the list of currently loaded plugins.
1965     *
1966     * @return the list of currently loaded plugins
1967     * @deprecated This was used for Gears, which has been deprecated.
1968     * @hide
1969     */
1970    @Deprecated
1971    public static synchronized PluginList getPluginList() {
1972        return new PluginList();
1973    }
1974
1975    /**
1976     * @deprecated This was used for Gears, which has been deprecated.
1977     * @hide
1978     */
1979    @Deprecated
1980    public void refreshPlugins(boolean reloadOpenPages) {
1981        checkThread();
1982    }
1983
1984    /**
1985     * Puts this WebView into text selection mode. Do not rely on this
1986     * functionality; it will be deprecated in the future.
1987     *
1988     * @deprecated This method is now obsolete.
1989     * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}
1990     */
1991    @Deprecated
1992    public void emulateShiftHeld() {
1993        checkThread();
1994    }
1995
1996    /**
1997     * @deprecated WebView no longer needs to implement
1998     * ViewGroup.OnHierarchyChangeListener.  This method does nothing now.
1999     */
2000    @Override
2001    // Cannot add @hide as this can always be accessed via the interface.
2002    @Deprecated
2003    public void onChildViewAdded(View parent, View child) {}
2004
2005    /**
2006     * @deprecated WebView no longer needs to implement
2007     * ViewGroup.OnHierarchyChangeListener.  This method does nothing now.
2008     */
2009    @Override
2010    // Cannot add @hide as this can always be accessed via the interface.
2011    @Deprecated
2012    public void onChildViewRemoved(View p, View child) {}
2013
2014    /**
2015     * @deprecated WebView should not have implemented
2016     * ViewTreeObserver.OnGlobalFocusChangeListener. This method does nothing now.
2017     */
2018    @Override
2019    // Cannot add @hide as this can always be accessed via the interface.
2020    @Deprecated
2021    public void onGlobalFocusChanged(View oldFocus, View newFocus) {
2022    }
2023
2024    /**
2025     * @deprecated Only the default case, true, will be supported in a future version.
2026     */
2027    @Deprecated
2028    public void setMapTrackballToArrowKeys(boolean setMap) {
2029        checkThread();
2030        mProvider.setMapTrackballToArrowKeys(setMap);
2031    }
2032
2033
2034    public void flingScroll(int vx, int vy) {
2035        checkThread();
2036        mProvider.flingScroll(vx, vy);
2037    }
2038
2039    /**
2040     * Gets the zoom controls for this WebView, as a separate View. The caller
2041     * is responsible for inserting this View into the layout hierarchy.
2042     * <p/>
2043     * API level {@link android.os.Build.VERSION_CODES#CUPCAKE} introduced
2044     * built-in zoom mechanisms for the WebView, as opposed to these separate
2045     * zoom controls. The built-in mechanisms are preferred and can be enabled
2046     * using {@link WebSettings#setBuiltInZoomControls}.
2047     *
2048     * @deprecated the built-in zoom mechanisms are preferred
2049     * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN}
2050     */
2051    @Deprecated
2052    public View getZoomControls() {
2053        checkThread();
2054        return mProvider.getZoomControls();
2055    }
2056
2057    /**
2058     * Gets whether this WebView can be zoomed in.
2059     *
2060     * @return true if this WebView can be zoomed in
2061     *
2062     * @deprecated This method is prone to inaccuracy due to race conditions
2063     * between the web rendering and UI threads; prefer
2064     * {@link WebViewClient#onScaleChanged}.
2065     */
2066    @Deprecated
2067    public boolean canZoomIn() {
2068        checkThread();
2069        return mProvider.canZoomIn();
2070    }
2071
2072    /**
2073     * Gets whether this WebView can be zoomed out.
2074     *
2075     * @return true if this WebView can be zoomed out
2076     *
2077     * @deprecated This method is prone to inaccuracy due to race conditions
2078     * between the web rendering and UI threads; prefer
2079     * {@link WebViewClient#onScaleChanged}.
2080     */
2081    @Deprecated
2082    public boolean canZoomOut() {
2083        checkThread();
2084        return mProvider.canZoomOut();
2085    }
2086
2087    /**
2088     * Performs a zoom operation in this WebView.
2089     *
2090     * @param zoomFactor the zoom factor to apply. The zoom factor will be clamped to the WebView's
2091     * zoom limits. This value must be in the range 0.01 to 100.0 inclusive.
2092     */
2093    public void zoomBy(float zoomFactor) {
2094        checkThread();
2095        if (zoomFactor < 0.01)
2096            throw new IllegalArgumentException("zoomFactor must be greater than 0.01.");
2097        if (zoomFactor > 100.0)
2098            throw new IllegalArgumentException("zoomFactor must be less than 100.");
2099        mProvider.zoomBy(zoomFactor);
2100    }
2101
2102    /**
2103     * Performs zoom in in this WebView.
2104     *
2105     * @return true if zoom in succeeds, false if no zoom changes
2106     */
2107    public boolean zoomIn() {
2108        checkThread();
2109        return mProvider.zoomIn();
2110    }
2111
2112    /**
2113     * Performs zoom out in this WebView.
2114     *
2115     * @return true if zoom out succeeds, false if no zoom changes
2116     */
2117    public boolean zoomOut() {
2118        checkThread();
2119        return mProvider.zoomOut();
2120    }
2121
2122    /**
2123     * @deprecated This method is now obsolete.
2124     * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}
2125     */
2126    @Deprecated
2127    public void debugDump() {
2128        checkThread();
2129    }
2130
2131    /**
2132     * See {@link ViewDebug.HierarchyHandler#dumpViewHierarchyWithProperties(BufferedWriter, int)}
2133     * @hide
2134     */
2135    @Override
2136    public void dumpViewHierarchyWithProperties(BufferedWriter out, int level) {
2137        mProvider.dumpViewHierarchyWithProperties(out, level);
2138    }
2139
2140    /**
2141     * See {@link ViewDebug.HierarchyHandler#findHierarchyView(String, int)}
2142     * @hide
2143     */
2144    @Override
2145    public View findHierarchyView(String className, int hashCode) {
2146        return mProvider.findHierarchyView(className, hashCode);
2147    }
2148
2149    //-------------------------------------------------------------------------
2150    // Interface for WebView providers
2151    //-------------------------------------------------------------------------
2152
2153    /**
2154     * Gets the WebViewProvider. Used by providers to obtain the underlying
2155     * implementation, e.g. when the application responds to
2156     * WebViewClient.onCreateWindow() request.
2157     *
2158     * @hide WebViewProvider is not public API.
2159     */
2160    @SystemApi
2161    public WebViewProvider getWebViewProvider() {
2162        return mProvider;
2163    }
2164
2165    /**
2166     * Callback interface, allows the provider implementation to access non-public methods
2167     * and fields, and make super-class calls in this WebView instance.
2168     * @hide Only for use by WebViewProvider implementations
2169     */
2170    @SystemApi
2171    public class PrivateAccess {
2172        // ---- Access to super-class methods ----
2173        public int super_getScrollBarStyle() {
2174            return WebView.super.getScrollBarStyle();
2175        }
2176
2177        public void super_scrollTo(int scrollX, int scrollY) {
2178            WebView.super.scrollTo(scrollX, scrollY);
2179        }
2180
2181        public void super_computeScroll() {
2182            WebView.super.computeScroll();
2183        }
2184
2185        public boolean super_onHoverEvent(MotionEvent event) {
2186            return WebView.super.onHoverEvent(event);
2187        }
2188
2189        public boolean super_performAccessibilityAction(int action, Bundle arguments) {
2190            return WebView.super.performAccessibilityActionInternal(action, arguments);
2191        }
2192
2193        public boolean super_performLongClick() {
2194            return WebView.super.performLongClick();
2195        }
2196
2197        public boolean super_setFrame(int left, int top, int right, int bottom) {
2198            return WebView.super.setFrame(left, top, right, bottom);
2199        }
2200
2201        public boolean super_dispatchKeyEvent(KeyEvent event) {
2202            return WebView.super.dispatchKeyEvent(event);
2203        }
2204
2205        public boolean super_onGenericMotionEvent(MotionEvent event) {
2206            return WebView.super.onGenericMotionEvent(event);
2207        }
2208
2209        public boolean super_requestFocus(int direction, Rect previouslyFocusedRect) {
2210            return WebView.super.requestFocus(direction, previouslyFocusedRect);
2211        }
2212
2213        public void super_setLayoutParams(ViewGroup.LayoutParams params) {
2214            WebView.super.setLayoutParams(params);
2215        }
2216
2217        public void super_startActivityForResult(Intent intent, int requestCode) {
2218            WebView.super.startActivityForResult(intent, requestCode);
2219        }
2220
2221        // ---- Access to non-public methods ----
2222        public void overScrollBy(int deltaX, int deltaY,
2223                int scrollX, int scrollY,
2224                int scrollRangeX, int scrollRangeY,
2225                int maxOverScrollX, int maxOverScrollY,
2226                boolean isTouchEvent) {
2227            WebView.this.overScrollBy(deltaX, deltaY, scrollX, scrollY, scrollRangeX, scrollRangeY,
2228                    maxOverScrollX, maxOverScrollY, isTouchEvent);
2229        }
2230
2231        public void awakenScrollBars(int duration) {
2232            WebView.this.awakenScrollBars(duration);
2233        }
2234
2235        public void awakenScrollBars(int duration, boolean invalidate) {
2236            WebView.this.awakenScrollBars(duration, invalidate);
2237        }
2238
2239        public float getVerticalScrollFactor() {
2240            return WebView.this.getVerticalScrollFactor();
2241        }
2242
2243        public float getHorizontalScrollFactor() {
2244            return WebView.this.getHorizontalScrollFactor();
2245        }
2246
2247        public void setMeasuredDimension(int measuredWidth, int measuredHeight) {
2248            WebView.this.setMeasuredDimension(measuredWidth, measuredHeight);
2249        }
2250
2251        public void onScrollChanged(int l, int t, int oldl, int oldt) {
2252            WebView.this.onScrollChanged(l, t, oldl, oldt);
2253        }
2254
2255        public int getHorizontalScrollbarHeight() {
2256            return WebView.this.getHorizontalScrollbarHeight();
2257        }
2258
2259        public void super_onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
2260                int l, int t, int r, int b) {
2261            WebView.super.onDrawVerticalScrollBar(canvas, scrollBar, l, t, r, b);
2262        }
2263
2264        // ---- Access to (non-public) fields ----
2265        /** Raw setter for the scroll X value, without invoking onScrollChanged handlers etc. */
2266        public void setScrollXRaw(int scrollX) {
2267            WebView.this.mScrollX = scrollX;
2268        }
2269
2270        /** Raw setter for the scroll Y value, without invoking onScrollChanged handlers etc. */
2271        public void setScrollYRaw(int scrollY) {
2272            WebView.this.mScrollY = scrollY;
2273        }
2274
2275    }
2276
2277    //-------------------------------------------------------------------------
2278    // Package-private internal stuff
2279    //-------------------------------------------------------------------------
2280
2281    // Only used by android.webkit.FindActionModeCallback.
2282    void setFindDialogFindListener(FindListener listener) {
2283        checkThread();
2284        setupFindListenerIfNeeded();
2285        mFindListener.mFindDialogFindListener = listener;
2286    }
2287
2288    // Only used by android.webkit.FindActionModeCallback.
2289    void notifyFindDialogDismissed() {
2290        checkThread();
2291        mProvider.notifyFindDialogDismissed();
2292    }
2293
2294    //-------------------------------------------------------------------------
2295    // Private internal stuff
2296    //-------------------------------------------------------------------------
2297
2298    private WebViewProvider mProvider;
2299
2300    /**
2301     * In addition to the FindListener that the user may set via the WebView.setFindListener
2302     * API, FindActionModeCallback will register it's own FindListener. We keep them separate
2303     * via this class so that the two FindListeners can potentially exist at once.
2304     */
2305    private class FindListenerDistributor implements FindListener {
2306        private FindListener mFindDialogFindListener;
2307        private FindListener mUserFindListener;
2308
2309        @Override
2310        public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches,
2311                boolean isDoneCounting) {
2312            if (mFindDialogFindListener != null) {
2313                mFindDialogFindListener.onFindResultReceived(activeMatchOrdinal, numberOfMatches,
2314                        isDoneCounting);
2315            }
2316
2317            if (mUserFindListener != null) {
2318                mUserFindListener.onFindResultReceived(activeMatchOrdinal, numberOfMatches,
2319                        isDoneCounting);
2320            }
2321        }
2322    }
2323    private FindListenerDistributor mFindListener;
2324
2325    private void setupFindListenerIfNeeded() {
2326        if (mFindListener == null) {
2327            mFindListener = new FindListenerDistributor();
2328            mProvider.setFindListener(mFindListener);
2329        }
2330    }
2331
2332    private void ensureProviderCreated() {
2333        checkThread();
2334        if (mProvider == null) {
2335            // As this can get called during the base class constructor chain, pass the minimum
2336            // number of dependencies here; the rest are deferred to init().
2337            mProvider = getFactory().createWebView(this, new PrivateAccess());
2338        }
2339    }
2340
2341    private static WebViewFactoryProvider getFactory() {
2342        return WebViewFactory.getProvider();
2343    }
2344
2345    private final Looper mWebViewThread = Looper.myLooper();
2346
2347    private void checkThread() {
2348        // Ignore mWebViewThread == null because this can be called during in the super class
2349        // constructor, before this class's own constructor has even started.
2350        if (mWebViewThread != null && Looper.myLooper() != mWebViewThread) {
2351            Throwable throwable = new Throwable(
2352                    "A WebView method was called on thread '" +
2353                    Thread.currentThread().getName() + "'. " +
2354                    "All WebView methods must be called on the same thread. " +
2355                    "(Expected Looper " + mWebViewThread + " called on " + Looper.myLooper() +
2356                    ", FYI main Looper is " + Looper.getMainLooper() + ")");
2357            Log.w(LOGTAG, Log.getStackTraceString(throwable));
2358            StrictMode.onWebViewMethodCalledOnWrongThread(throwable);
2359
2360            if (sEnforceThreadChecking) {
2361                throw new RuntimeException(throwable);
2362            }
2363        }
2364    }
2365
2366    //-------------------------------------------------------------------------
2367    // Override View methods
2368    //-------------------------------------------------------------------------
2369
2370    // TODO: Add a test that enumerates all methods in ViewDelegte & ScrollDelegate, and ensures
2371    // there's a corresponding override (or better, caller) for each of them in here.
2372
2373    @Override
2374    protected void onAttachedToWindow() {
2375        super.onAttachedToWindow();
2376        mProvider.getViewDelegate().onAttachedToWindow();
2377    }
2378
2379    /** @hide */
2380    @Override
2381    protected void onDetachedFromWindowInternal() {
2382        mProvider.getViewDelegate().onDetachedFromWindow();
2383        super.onDetachedFromWindowInternal();
2384    }
2385
2386    @Override
2387    public void setLayoutParams(ViewGroup.LayoutParams params) {
2388        mProvider.getViewDelegate().setLayoutParams(params);
2389    }
2390
2391    @Override
2392    public void setOverScrollMode(int mode) {
2393        super.setOverScrollMode(mode);
2394        // This method may be called in the constructor chain, before the WebView provider is
2395        // created.
2396        ensureProviderCreated();
2397        mProvider.getViewDelegate().setOverScrollMode(mode);
2398    }
2399
2400    @Override
2401    public void setScrollBarStyle(int style) {
2402        mProvider.getViewDelegate().setScrollBarStyle(style);
2403        super.setScrollBarStyle(style);
2404    }
2405
2406    @Override
2407    protected int computeHorizontalScrollRange() {
2408        return mProvider.getScrollDelegate().computeHorizontalScrollRange();
2409    }
2410
2411    @Override
2412    protected int computeHorizontalScrollOffset() {
2413        return mProvider.getScrollDelegate().computeHorizontalScrollOffset();
2414    }
2415
2416    @Override
2417    protected int computeVerticalScrollRange() {
2418        return mProvider.getScrollDelegate().computeVerticalScrollRange();
2419    }
2420
2421    @Override
2422    protected int computeVerticalScrollOffset() {
2423        return mProvider.getScrollDelegate().computeVerticalScrollOffset();
2424    }
2425
2426    @Override
2427    protected int computeVerticalScrollExtent() {
2428        return mProvider.getScrollDelegate().computeVerticalScrollExtent();
2429    }
2430
2431    @Override
2432    public void computeScroll() {
2433        mProvider.getScrollDelegate().computeScroll();
2434    }
2435
2436    @Override
2437    public boolean onHoverEvent(MotionEvent event) {
2438        return mProvider.getViewDelegate().onHoverEvent(event);
2439    }
2440
2441    @Override
2442    public boolean onTouchEvent(MotionEvent event) {
2443        return mProvider.getViewDelegate().onTouchEvent(event);
2444    }
2445
2446    @Override
2447    public boolean onGenericMotionEvent(MotionEvent event) {
2448        return mProvider.getViewDelegate().onGenericMotionEvent(event);
2449    }
2450
2451    @Override
2452    public boolean onTrackballEvent(MotionEvent event) {
2453        return mProvider.getViewDelegate().onTrackballEvent(event);
2454    }
2455
2456    @Override
2457    public boolean onKeyDown(int keyCode, KeyEvent event) {
2458        return mProvider.getViewDelegate().onKeyDown(keyCode, event);
2459    }
2460
2461    @Override
2462    public boolean onKeyUp(int keyCode, KeyEvent event) {
2463        return mProvider.getViewDelegate().onKeyUp(keyCode, event);
2464    }
2465
2466    @Override
2467    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
2468        return mProvider.getViewDelegate().onKeyMultiple(keyCode, repeatCount, event);
2469    }
2470
2471    /*
2472    TODO: These are not currently implemented in WebViewClassic, but it seems inconsistent not
2473    to be delegating them too.
2474
2475    @Override
2476    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
2477        return mProvider.getViewDelegate().onKeyPreIme(keyCode, event);
2478    }
2479    @Override
2480    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
2481        return mProvider.getViewDelegate().onKeyLongPress(keyCode, event);
2482    }
2483    @Override
2484    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
2485        return mProvider.getViewDelegate().onKeyShortcut(keyCode, event);
2486    }
2487    */
2488
2489    @Override
2490    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
2491        AccessibilityNodeProvider provider =
2492                mProvider.getViewDelegate().getAccessibilityNodeProvider();
2493        return provider == null ? super.getAccessibilityNodeProvider() : provider;
2494    }
2495
2496    @Deprecated
2497    @Override
2498    public boolean shouldDelayChildPressedState() {
2499        return mProvider.getViewDelegate().shouldDelayChildPressedState();
2500    }
2501
2502    public CharSequence getAccessibilityClassName() {
2503        return WebView.class.getName();
2504    }
2505
2506    @Override
2507    public void onProvideVirtualStructure(ViewStructure structure) {
2508        mProvider.getViewDelegate().onProvideVirtualStructure(structure);
2509    }
2510
2511    /** @hide */
2512    @Override
2513    public void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
2514        super.onInitializeAccessibilityNodeInfoInternal(info);
2515        mProvider.getViewDelegate().onInitializeAccessibilityNodeInfo(info);
2516    }
2517
2518    /** @hide */
2519    @Override
2520    public void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
2521        super.onInitializeAccessibilityEventInternal(event);
2522        mProvider.getViewDelegate().onInitializeAccessibilityEvent(event);
2523    }
2524
2525    /** @hide */
2526    @Override
2527    public boolean performAccessibilityActionInternal(int action, Bundle arguments) {
2528        return mProvider.getViewDelegate().performAccessibilityAction(action, arguments);
2529    }
2530
2531    /** @hide */
2532    @Override
2533    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
2534            int l, int t, int r, int b) {
2535        mProvider.getViewDelegate().onDrawVerticalScrollBar(canvas, scrollBar, l, t, r, b);
2536    }
2537
2538    @Override
2539    protected void onOverScrolled(int scrollX, int scrollY, boolean clampedX, boolean clampedY) {
2540        mProvider.getViewDelegate().onOverScrolled(scrollX, scrollY, clampedX, clampedY);
2541    }
2542
2543    @Override
2544    protected void onWindowVisibilityChanged(int visibility) {
2545        super.onWindowVisibilityChanged(visibility);
2546        mProvider.getViewDelegate().onWindowVisibilityChanged(visibility);
2547    }
2548
2549    @Override
2550    protected void onDraw(Canvas canvas) {
2551        mProvider.getViewDelegate().onDraw(canvas);
2552    }
2553
2554    @Override
2555    public boolean performLongClick() {
2556        return mProvider.getViewDelegate().performLongClick();
2557    }
2558
2559    @Override
2560    protected void onConfigurationChanged(Configuration newConfig) {
2561        mProvider.getViewDelegate().onConfigurationChanged(newConfig);
2562    }
2563
2564    @Override
2565    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
2566        return mProvider.getViewDelegate().onCreateInputConnection(outAttrs);
2567    }
2568
2569    @Override
2570    public boolean onDragEvent(DragEvent event) {
2571        return mProvider.getViewDelegate().onDragEvent(event);
2572    }
2573
2574    @Override
2575    protected void onVisibilityChanged(View changedView, int visibility) {
2576        super.onVisibilityChanged(changedView, visibility);
2577        // This method may be called in the constructor chain, before the WebView provider is
2578        // created.
2579        ensureProviderCreated();
2580        mProvider.getViewDelegate().onVisibilityChanged(changedView, visibility);
2581    }
2582
2583    @Override
2584    public void onWindowFocusChanged(boolean hasWindowFocus) {
2585        mProvider.getViewDelegate().onWindowFocusChanged(hasWindowFocus);
2586        super.onWindowFocusChanged(hasWindowFocus);
2587    }
2588
2589    @Override
2590    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
2591        mProvider.getViewDelegate().onFocusChanged(focused, direction, previouslyFocusedRect);
2592        super.onFocusChanged(focused, direction, previouslyFocusedRect);
2593    }
2594
2595    /** @hide */
2596    @Override
2597    protected boolean setFrame(int left, int top, int right, int bottom) {
2598        return mProvider.getViewDelegate().setFrame(left, top, right, bottom);
2599    }
2600
2601    @Override
2602    protected void onSizeChanged(int w, int h, int ow, int oh) {
2603        super.onSizeChanged(w, h, ow, oh);
2604        mProvider.getViewDelegate().onSizeChanged(w, h, ow, oh);
2605    }
2606
2607    @Override
2608    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
2609        super.onScrollChanged(l, t, oldl, oldt);
2610        mProvider.getViewDelegate().onScrollChanged(l, t, oldl, oldt);
2611    }
2612
2613    @Override
2614    public boolean dispatchKeyEvent(KeyEvent event) {
2615        return mProvider.getViewDelegate().dispatchKeyEvent(event);
2616    }
2617
2618    @Override
2619    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
2620        return mProvider.getViewDelegate().requestFocus(direction, previouslyFocusedRect);
2621    }
2622
2623    @Override
2624    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
2625        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
2626        mProvider.getViewDelegate().onMeasure(widthMeasureSpec, heightMeasureSpec);
2627    }
2628
2629    @Override
2630    public boolean requestChildRectangleOnScreen(View child, Rect rect, boolean immediate) {
2631        return mProvider.getViewDelegate().requestChildRectangleOnScreen(child, rect, immediate);
2632    }
2633
2634    @Override
2635    public void setBackgroundColor(int color) {
2636        mProvider.getViewDelegate().setBackgroundColor(color);
2637    }
2638
2639    @Override
2640    public void setLayerType(int layerType, Paint paint) {
2641        super.setLayerType(layerType, paint);
2642        mProvider.getViewDelegate().setLayerType(layerType, paint);
2643    }
2644
2645    @Override
2646    protected void dispatchDraw(Canvas canvas) {
2647        mProvider.getViewDelegate().preDispatchDraw(canvas);
2648        super.dispatchDraw(canvas);
2649    }
2650
2651    @Override
2652    public void onStartTemporaryDetach() {
2653        super.onStartTemporaryDetach();
2654        mProvider.getViewDelegate().onStartTemporaryDetach();
2655    }
2656
2657    @Override
2658    public void onFinishTemporaryDetach() {
2659        super.onFinishTemporaryDetach();
2660        mProvider.getViewDelegate().onFinishTemporaryDetach();
2661    }
2662
2663    @Override
2664    public Handler getHandler() {
2665        return mProvider.getViewDelegate().getHandler(super.getHandler());
2666    }
2667
2668    @Override
2669    public View findFocus() {
2670        return mProvider.getViewDelegate().findFocus(super.findFocus());
2671    }
2672
2673    /**
2674     * Receive the result from a previous call to {@link #startActivityForResult(Intent, int)}.
2675     *
2676     * @param requestCode The integer request code originally supplied to
2677     *                    startActivityForResult(), allowing you to identify who this
2678     *                    result came from.
2679     * @param resultCode The integer result code returned by the child activity
2680     *                   through its setResult().
2681     * @param data An Intent, which can return result data to the caller
2682     *               (various data can be attached to Intent "extras").
2683     * @hide
2684     */
2685    @Override
2686    public void onActivityResult(int requestCode, int resultCode, Intent data) {
2687        mProvider.getViewDelegate().onActivityResult(requestCode, resultCode, data);
2688    }
2689
2690    /** @hide */
2691    @Override
2692    protected void encodeProperties(@NonNull ViewHierarchyEncoder encoder) {
2693        super.encodeProperties(encoder);
2694
2695        checkThread();
2696        encoder.addProperty("webview:contentHeight", mProvider.getContentHeight());
2697        encoder.addProperty("webview:contentWidth", mProvider.getContentWidth());
2698        encoder.addProperty("webview:scale", mProvider.getScale());
2699        encoder.addProperty("webview:title", mProvider.getTitle());
2700        encoder.addProperty("webview:url", mProvider.getUrl());
2701        encoder.addProperty("webview:originalUrl", mProvider.getOriginalUrl());
2702    }
2703}
2704