• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
17 package android.webkit;
18 
19 import android.annotation.Widget;
20 import android.content.Context;
21 import android.content.res.Configuration;
22 import android.graphics.Bitmap;
23 import android.graphics.Canvas;
24 import android.graphics.Paint;
25 import android.graphics.Picture;
26 import android.graphics.Rect;
27 import android.graphics.drawable.Drawable;
28 import android.net.http.SslCertificate;
29 import android.os.Build;
30 import android.os.Bundle;
31 import android.os.Looper;
32 import android.os.Message;
33 import android.os.StrictMode;
34 import android.util.AttributeSet;
35 import android.util.Log;
36 import android.view.KeyEvent;
37 import android.view.MotionEvent;
38 import android.view.View;
39 import android.view.ViewDebug;
40 import android.view.ViewGroup;
41 import android.view.ViewTreeObserver;
42 import android.view.accessibility.AccessibilityEvent;
43 import android.view.accessibility.AccessibilityNodeInfo;
44 import android.view.inputmethod.EditorInfo;
45 import android.view.inputmethod.InputConnection;
46 import android.widget.AbsoluteLayout;
47 
48 import java.io.BufferedWriter;
49 import java.io.File;
50 import java.util.Map;
51 
52 /**
53  * <p>A View that displays web pages. This class is the basis upon which you
54  * can roll your own web browser or simply display some online content within your Activity.
55  * It uses the WebKit rendering engine to display
56  * web pages and includes methods to navigate forward and backward
57  * through a history, zoom in and out, perform text searches and more.</p>
58  * <p>To enable the built-in zoom, set
59  * {@link #getSettings() WebSettings}.{@link WebSettings#setBuiltInZoomControls(boolean)}
60  * (introduced in API level {@link android.os.Build.VERSION_CODES#CUPCAKE}).
61  * <p>Note that, in order for your Activity to access the Internet and load web pages
62  * in a WebView, you must add the {@code INTERNET} permissions to your
63  * Android Manifest file:</p>
64  * <pre>&lt;uses-permission android:name="android.permission.INTERNET" /></pre>
65  *
66  * <p>This must be a child of the <a
67  * href="{@docRoot}guide/topics/manifest/manifest-element.html">{@code <manifest>}</a>
68  * element.</p>
69  *
70  * <p>For more information, read
71  * <a href="{@docRoot}guide/webapps/webview.html">Building Web Apps in WebView</a>.</p>
72  *
73  * <h3>Basic usage</h3>
74  *
75  * <p>By default, a WebView provides no browser-like widgets, does not
76  * enable JavaScript and web page errors are ignored. If your goal is only
77  * to display some HTML as a part of your UI, this is probably fine;
78  * the user won't need to interact with the web page beyond reading
79  * it, and the web page won't need to interact with the user. If you
80  * actually want a full-blown web browser, then you probably want to
81  * invoke the Browser application with a URL Intent rather than show it
82  * with a WebView. For example:
83  * <pre>
84  * Uri uri = Uri.parse("http://www.example.com");
85  * Intent intent = new Intent(Intent.ACTION_VIEW, uri);
86  * startActivity(intent);
87  * </pre>
88  * <p>See {@link android.content.Intent} for more information.</p>
89  *
90  * <p>To provide a WebView in your own Activity, include a {@code <WebView>} in your layout,
91  * or set the entire Activity window as a WebView during {@link
92  * android.app.Activity#onCreate(Bundle) onCreate()}:</p>
93  * <pre class="prettyprint">
94  * WebView webview = new WebView(this);
95  * setContentView(webview);
96  * </pre>
97  *
98  * <p>Then load the desired web page:</p>
99  * <pre>
100  * // Simplest usage: note that an exception will NOT be thrown
101  * // if there is an error loading this page (see below).
102  * webview.loadUrl("http://slashdot.org/");
103  *
104  * // OR, you can also load from an HTML string:
105  * String summary = "&lt;html>&lt;body>You scored &lt;b>192&lt;/b> points.&lt;/body>&lt;/html>";
106  * webview.loadData(summary, "text/html", null);
107  * // ... although note that there are restrictions on what this HTML can do.
108  * // See the JavaDocs for {@link #loadData(String,String,String) loadData()} and {@link
109  * #loadDataWithBaseURL(String,String,String,String,String) loadDataWithBaseURL()} for more info.
110  * </pre>
111  *
112  * <p>A WebView has several customization points where you can add your
113  * own behavior. These are:</p>
114  *
115  * <ul>
116  *   <li>Creating and setting a {@link android.webkit.WebChromeClient} subclass.
117  *       This class is called when something that might impact a
118  *       browser UI happens, for instance, progress updates and
119  *       JavaScript alerts are sent here (see <a
120  * href="{@docRoot}guide/developing/debug-tasks.html#DebuggingWebPages">Debugging Tasks</a>).
121  *   </li>
122  *   <li>Creating and setting a {@link android.webkit.WebViewClient} subclass.
123  *       It will be called when things happen that impact the
124  *       rendering of the content, eg, errors or form submissions. You
125  *       can also intercept URL loading here (via {@link
126  * android.webkit.WebViewClient#shouldOverrideUrlLoading(WebView,String)
127  * shouldOverrideUrlLoading()}).</li>
128  *   <li>Modifying the {@link android.webkit.WebSettings}, such as
129  * enabling JavaScript with {@link android.webkit.WebSettings#setJavaScriptEnabled(boolean)
130  * setJavaScriptEnabled()}. </li>
131  *   <li>Injecting Java objects into the WebView using the
132  *       {@link android.webkit.WebView#addJavascriptInterface} method. This
133  *       method allows you to inject Java objects into a page's JavaScript
134  *       context, so that they can be accessed by JavaScript in the page.</li>
135  * </ul>
136  *
137  * <p>Here's a more complicated example, showing error handling,
138  *    settings, and progress notification:</p>
139  *
140  * <pre class="prettyprint">
141  * // Let's display the progress in the activity title bar, like the
142  * // browser app does.
143  * getWindow().requestFeature(Window.FEATURE_PROGRESS);
144  *
145  * webview.getSettings().setJavaScriptEnabled(true);
146  *
147  * final Activity activity = this;
148  * webview.setWebChromeClient(new WebChromeClient() {
149  *   public void onProgressChanged(WebView view, int progress) {
150  *     // Activities and WebViews measure progress with different scales.
151  *     // The progress meter will automatically disappear when we reach 100%
152  *     activity.setProgress(progress * 1000);
153  *   }
154  * });
155  * webview.setWebViewClient(new WebViewClient() {
156  *   public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
157  *     Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
158  *   }
159  * });
160  *
161  * webview.loadUrl("http://slashdot.org/");
162  * </pre>
163  *
164  * <h3>Cookie and window management</h3>
165  *
166  * <p>For obvious security reasons, your application has its own
167  * cache, cookie store etc.&mdash;it does not share the Browser
168  * application's data.
169  * </p>
170  *
171  * <p>By default, requests by the HTML to open new windows are
172  * ignored. This is true whether they be opened by JavaScript or by
173  * the target attribute on a link. You can customize your
174  * {@link WebChromeClient} to provide your own behaviour for opening multiple windows,
175  * and render them in whatever manner you want.</p>
176  *
177  * <p>The standard behavior for an Activity is to be destroyed and
178  * recreated when the device orientation or any other configuration changes. This will cause
179  * the WebView to reload the current page. If you don't want that, you
180  * can set your Activity to handle the {@code orientation} and {@code keyboardHidden}
181  * changes, and then just leave the WebView alone. It'll automatically
182  * re-orient itself as appropriate. Read <a
183  * href="{@docRoot}guide/topics/resources/runtime-changes.html">Handling Runtime Changes</a> for
184  * more information about how to handle configuration changes during runtime.</p>
185  *
186  *
187  * <h3>Building web pages to support different screen densities</h3>
188  *
189  * <p>The screen density of a device is based on the screen resolution. A screen with low density
190  * has fewer available pixels per inch, where a screen with high density
191  * has more &mdash; sometimes significantly more &mdash; pixels per inch. The density of a
192  * screen is important because, other things being equal, a UI element (such as a button) whose
193  * height and width are defined in terms of screen pixels will appear larger on the lower density
194  * screen and smaller on the higher density screen.
195  * For simplicity, Android collapses all actual screen densities into three generalized densities:
196  * high, medium, and low.</p>
197  * <p>By default, WebView scales a web page so that it is drawn at a size that matches the default
198  * appearance on a medium density screen. So, it applies 1.5x scaling on a high density screen
199  * (because its pixels are smaller) and 0.75x scaling on a low density screen (because its pixels
200  * are bigger).
201  * Starting with API level {@link android.os.Build.VERSION_CODES#ECLAIR}, WebView supports DOM, CSS,
202  * and meta tag features to help you (as a web developer) target screens with different screen
203  * densities.</p>
204  * <p>Here's a summary of the features you can use to handle different screen densities:</p>
205  * <ul>
206  * <li>The {@code window.devicePixelRatio} DOM property. The value of this property specifies the
207  * default scaling factor used for the current device. For example, if the value of {@code
208  * window.devicePixelRatio} is "1.0", then the device is considered a medium density (mdpi) device
209  * and default scaling is not applied to the web page; if the value is "1.5", then the device is
210  * considered a high density device (hdpi) and the page content is scaled 1.5x; if the
211  * value is "0.75", then the device is considered a low density device (ldpi) and the content is
212  * scaled 0.75x.</li>
213  * <li>The {@code -webkit-device-pixel-ratio} CSS media query. Use this to specify the screen
214  * densities for which this style sheet is to be used. The corresponding value should be either
215  * "0.75", "1", or "1.5", to indicate that the styles are for devices with low density, medium
216  * density, or high density screens, respectively. For example:
217  * <pre>
218  * &lt;link rel="stylesheet" media="screen and (-webkit-device-pixel-ratio:1.5)" href="hdpi.css" /&gt;</pre>
219  * <p>The {@code hdpi.css} stylesheet is only used for devices with a screen pixel ration of 1.5,
220  * which is the high density pixel ratio.</p>
221  * </li>
222  *
223  * <h3>HTML5 Video support</h3>
224  *
225  * <p>In order to support inline HTML5 video in your application, you need to have hardware
226  * acceleration turned on, and set a {@link android.webkit.WebChromeClient}. For full screen support,
227  * implementations of {@link WebChromeClient#onShowCustomView(View, WebChromeClient.CustomViewCallback)}
228  * and {@link WebChromeClient#onHideCustomView()} are required,
229  * {@link WebChromeClient#getVideoLoadingProgressView()} is optional.
230  * </p>
231  */
232 // Implementation notes.
233 // The WebView is a thin API class that delegates its public API to a backend WebViewProvider
234 // class instance. WebView extends {@link AbsoluteLayout} for backward compatibility reasons.
235 // Methods are delegated to the provider implementation: all public API methods introduced in this
236 // file are fully delegated, whereas public and protected methods from the View base classes are
237 // only delegated where a specific need exists for them to do so.
238 @Widget
239 public class WebView extends AbsoluteLayout
240         implements ViewTreeObserver.OnGlobalFocusChangeListener,
241         ViewGroup.OnHierarchyChangeListener, ViewDebug.HierarchyHandler {
242 
243     private static final String LOGTAG = "webview_proxy";
244 
245     // Throwing an exception for incorrect thread usage if the
246     // build target is JB MR2 or newer. Defaults to false, and is
247     // set in the WebView constructor.
248     private static Boolean sEnforceThreadChecking = false;
249 
250     /**
251      *  Transportation object for returning WebView across thread boundaries.
252      */
253     public class WebViewTransport {
254         private WebView mWebview;
255 
256         /**
257          * Sets the WebView to the transportation object.
258          *
259          * @param webview the WebView to transport
260          */
setWebView(WebView webview)261         public synchronized void setWebView(WebView webview) {
262             mWebview = webview;
263         }
264 
265         /**
266          * Gets the WebView object.
267          *
268          * @return the transported WebView object
269          */
getWebView()270         public synchronized WebView getWebView() {
271             return mWebview;
272         }
273     }
274 
275     /**
276      * URI scheme for telephone number.
277      */
278     public static final String SCHEME_TEL = "tel:";
279     /**
280      * URI scheme for email address.
281      */
282     public static final String SCHEME_MAILTO = "mailto:";
283     /**
284      * URI scheme for map address.
285      */
286     public static final String SCHEME_GEO = "geo:0,0?q=";
287 
288     /**
289      * Interface to listen for find results.
290      */
291     public interface FindListener {
292         /**
293          * Notifies the listener about progress made by a find operation.
294          *
295          * @param activeMatchOrdinal the zero-based ordinal of the currently selected match
296          * @param numberOfMatches how many matches have been found
297          * @param isDoneCounting whether the find operation has actually completed. The listener
298          *                       may be notified multiple times while the
299          *                       operation is underway, and the numberOfMatches
300          *                       value should not be considered final unless
301          *                       isDoneCounting is true.
302          */
onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting)303         public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches,
304             boolean isDoneCounting);
305     }
306 
307     /**
308      * Interface to listen for new pictures as they change.
309      *
310      * @deprecated This interface is now obsolete.
311      */
312     @Deprecated
313     public interface PictureListener {
314         /**
315          * Used to provide notification that the WebView's picture has changed.
316          * See {@link WebView#capturePicture} for details of the picture.
317          *
318          * @param view the WebView that owns the picture
319          * @param picture the new picture. Applications targeting
320          *     {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2} or above
321          *     will always receive a null Picture.
322          * @deprecated Deprecated due to internal changes.
323          */
324         @Deprecated
onNewPicture(WebView view, Picture picture)325         public void onNewPicture(WebView view, Picture picture);
326     }
327 
328     public static class HitTestResult {
329         /**
330          * Default HitTestResult, where the target is unknown.
331          */
332         public static final int UNKNOWN_TYPE = 0;
333         /**
334          * @deprecated This type is no longer used.
335          */
336         @Deprecated
337         public static final int ANCHOR_TYPE = 1;
338         /**
339          * HitTestResult for hitting a phone number.
340          */
341         public static final int PHONE_TYPE = 2;
342         /**
343          * HitTestResult for hitting a map address.
344          */
345         public static final int GEO_TYPE = 3;
346         /**
347          * HitTestResult for hitting an email address.
348          */
349         public static final int EMAIL_TYPE = 4;
350         /**
351          * HitTestResult for hitting an HTML::img tag.
352          */
353         public static final int IMAGE_TYPE = 5;
354         /**
355          * @deprecated This type is no longer used.
356          */
357         @Deprecated
358         public static final int IMAGE_ANCHOR_TYPE = 6;
359         /**
360          * HitTestResult for hitting a HTML::a tag with src=http.
361          */
362         public static final int SRC_ANCHOR_TYPE = 7;
363         /**
364          * HitTestResult for hitting a HTML::a tag with src=http + HTML::img.
365          */
366         public static final int SRC_IMAGE_ANCHOR_TYPE = 8;
367         /**
368          * HitTestResult for hitting an edit text area.
369          */
370         public static final int EDIT_TEXT_TYPE = 9;
371 
372         private int mType;
373         private String mExtra;
374 
375         /**
376          * @hide Only for use by WebViewProvider implementations
377          */
HitTestResult()378         public HitTestResult() {
379             mType = UNKNOWN_TYPE;
380         }
381 
382         /**
383          * @hide Only for use by WebViewProvider implementations
384          */
setType(int type)385         public void setType(int type) {
386             mType = type;
387         }
388 
389         /**
390          * @hide Only for use by WebViewProvider implementations
391          */
setExtra(String extra)392         public void setExtra(String extra) {
393             mExtra = extra;
394         }
395 
396         /**
397          * Gets the type of the hit test result. See the XXX_TYPE constants
398          * defined in this class.
399          *
400          * @return the type of the hit test result
401          */
getType()402         public int getType() {
403             return mType;
404         }
405 
406         /**
407          * Gets additional type-dependant information about the result. See
408          * {@link WebView#getHitTestResult()} for details. May either be null
409          * or contain extra information about this result.
410          *
411          * @return additional type-dependant information about the result
412          */
getExtra()413         public String getExtra() {
414             return mExtra;
415         }
416     }
417 
418     /**
419      * Constructs a new WebView with a Context object.
420      *
421      * @param context a Context object used to access application assets
422      */
WebView(Context context)423     public WebView(Context context) {
424         this(context, null);
425     }
426 
427     /**
428      * Constructs a new WebView with layout parameters.
429      *
430      * @param context a Context object used to access application assets
431      * @param attrs an AttributeSet passed to our parent
432      */
WebView(Context context, AttributeSet attrs)433     public WebView(Context context, AttributeSet attrs) {
434         this(context, attrs, com.android.internal.R.attr.webViewStyle);
435     }
436 
437     /**
438      * Constructs a new WebView with layout parameters and a default style.
439      *
440      * @param context a Context object used to access application assets
441      * @param attrs an AttributeSet passed to our parent
442      * @param defStyle the default style resource ID
443      */
WebView(Context context, AttributeSet attrs, int defStyle)444     public WebView(Context context, AttributeSet attrs, int defStyle) {
445         this(context, attrs, defStyle, false);
446     }
447 
448     /**
449      * Constructs a new WebView with layout parameters and a default style.
450      *
451      * @param context a Context object used to access application assets
452      * @param attrs an AttributeSet passed to our parent
453      * @param defStyle the default style resource ID
454      * @param privateBrowsing whether this WebView will be initialized in
455      *                        private mode
456      *
457      * @deprecated Private browsing is no longer supported directly via
458      * WebView and will be removed in a future release. Prefer using
459      * {@link WebSettings}, {@link WebViewDatabase}, {@link CookieManager}
460      * and {@link WebStorage} for fine-grained control of privacy data.
461      */
462     @Deprecated
WebView(Context context, AttributeSet attrs, int defStyle, boolean privateBrowsing)463     public WebView(Context context, AttributeSet attrs, int defStyle,
464             boolean privateBrowsing) {
465         this(context, attrs, defStyle, null, privateBrowsing);
466     }
467 
468     /**
469      * Constructs a new WebView with layout parameters, a default style and a set
470      * of custom Javscript interfaces to be added to this WebView at initialization
471      * time. This guarantees that these interfaces will be available when the JS
472      * context is initialized.
473      *
474      * @param context a Context object used to access application assets
475      * @param attrs an AttributeSet passed to our parent
476      * @param defStyle the default style resource ID
477      * @param javaScriptInterfaces a Map of interface names, as keys, and
478      *                             object implementing those interfaces, as
479      *                             values
480      * @param privateBrowsing whether this WebView will be initialized in
481      *                        private mode
482      * @hide This is used internally by dumprendertree, as it requires the javaScript interfaces to
483      *       be added synchronously, before a subsequent loadUrl call takes effect.
484      */
485     @SuppressWarnings("deprecation")  // for super() call into deprecated base class constructor.
WebView(Context context, AttributeSet attrs, int defStyle, Map<String, Object> javaScriptInterfaces, boolean privateBrowsing)486     protected WebView(Context context, AttributeSet attrs, int defStyle,
487             Map<String, Object> javaScriptInterfaces, boolean privateBrowsing) {
488         super(context, attrs, defStyle);
489         if (context == null) {
490             throw new IllegalArgumentException("Invalid context argument");
491         }
492         sEnforceThreadChecking = context.getApplicationInfo().targetSdkVersion >=
493                 Build.VERSION_CODES.JELLY_BEAN_MR2;
494         checkThread();
495 
496         ensureProviderCreated();
497         mProvider.init(javaScriptInterfaces, privateBrowsing);
498     }
499 
500     /**
501      * Specifies whether the horizontal scrollbar has overlay style.
502      *
503      * @param overlay true if horizontal scrollbar should have overlay style
504      */
setHorizontalScrollbarOverlay(boolean overlay)505     public void setHorizontalScrollbarOverlay(boolean overlay) {
506         checkThread();
507         mProvider.setHorizontalScrollbarOverlay(overlay);
508     }
509 
510     /**
511      * Specifies whether the vertical scrollbar has overlay style.
512      *
513      * @param overlay true if vertical scrollbar should have overlay style
514      */
setVerticalScrollbarOverlay(boolean overlay)515     public void setVerticalScrollbarOverlay(boolean overlay) {
516         checkThread();
517         mProvider.setVerticalScrollbarOverlay(overlay);
518     }
519 
520     /**
521      * Gets whether horizontal scrollbar has overlay style.
522      *
523      * @return true if horizontal scrollbar has overlay style
524      */
overlayHorizontalScrollbar()525     public boolean overlayHorizontalScrollbar() {
526         checkThread();
527         return mProvider.overlayHorizontalScrollbar();
528     }
529 
530     /**
531      * Gets whether vertical scrollbar has overlay style.
532      *
533      * @return true if vertical scrollbar has overlay style
534      */
overlayVerticalScrollbar()535     public boolean overlayVerticalScrollbar() {
536         checkThread();
537         return mProvider.overlayVerticalScrollbar();
538     }
539 
540     /**
541      * Gets the visible height (in pixels) of the embedded title bar (if any).
542      *
543      * @deprecated This method is now obsolete.
544      * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}
545      */
getVisibleTitleHeight()546     public int getVisibleTitleHeight() {
547         checkThread();
548         return mProvider.getVisibleTitleHeight();
549     }
550 
551     /**
552      * Gets the SSL certificate for the main top-level page or null if there is
553      * no certificate (the site is not secure).
554      *
555      * @return the SSL certificate for the main top-level page
556      */
getCertificate()557     public SslCertificate getCertificate() {
558         checkThread();
559         return mProvider.getCertificate();
560     }
561 
562     /**
563      * Sets the SSL certificate for the main top-level page.
564      *
565      * @deprecated Calling this function has no useful effect, and will be
566      * ignored in future releases.
567      */
568     @Deprecated
setCertificate(SslCertificate certificate)569     public void setCertificate(SslCertificate certificate) {
570         checkThread();
571         mProvider.setCertificate(certificate);
572     }
573 
574     //-------------------------------------------------------------------------
575     // Methods called by activity
576     //-------------------------------------------------------------------------
577 
578     /**
579      * Sets a username and password pair for the specified host. This data is
580      * used by the Webview to autocomplete username and password fields in web
581      * forms. Note that this is unrelated to the credentials used for HTTP
582      * authentication.
583      *
584      * @param host the host that required the credentials
585      * @param username the username for the given host
586      * @param password the password for the given host
587      * @see WebViewDatabase#clearUsernamePassword
588      * @see WebViewDatabase#hasUsernamePassword
589      * @deprecated Saving passwords in WebView will not be supported in future versions.
590      */
591     @Deprecated
savePassword(String host, String username, String password)592     public void savePassword(String host, String username, String password) {
593         checkThread();
594         mProvider.savePassword(host, username, password);
595     }
596 
597     /**
598      * Stores HTTP authentication credentials for a given host and realm. This
599      * method is intended to be used with
600      * {@link WebViewClient#onReceivedHttpAuthRequest}.
601      *
602      * @param host the host to which the credentials apply
603      * @param realm the realm to which the credentials apply
604      * @param username the username
605      * @param password the password
606      * @see #getHttpAuthUsernamePassword
607      * @see WebViewDatabase#hasHttpAuthUsernamePassword
608      * @see WebViewDatabase#clearHttpAuthUsernamePassword
609      */
setHttpAuthUsernamePassword(String host, String realm, String username, String password)610     public void setHttpAuthUsernamePassword(String host, String realm,
611             String username, String password) {
612         checkThread();
613         mProvider.setHttpAuthUsernamePassword(host, realm, username, password);
614     }
615 
616     /**
617      * Retrieves HTTP authentication credentials for a given host and realm.
618      * This method is intended to be used with
619      * {@link WebViewClient#onReceivedHttpAuthRequest}.
620      *
621      * @param host the host to which the credentials apply
622      * @param realm the realm to which the credentials apply
623      * @return the credentials as a String array, if found. The first element
624      *         is the username and the second element is the password. Null if
625      *         no credentials are found.
626      * @see #setHttpAuthUsernamePassword
627      * @see WebViewDatabase#hasHttpAuthUsernamePassword
628      * @see WebViewDatabase#clearHttpAuthUsernamePassword
629      */
getHttpAuthUsernamePassword(String host, String realm)630     public String[] getHttpAuthUsernamePassword(String host, String realm) {
631         checkThread();
632         return mProvider.getHttpAuthUsernamePassword(host, realm);
633     }
634 
635     /**
636      * Destroys the internal state of this WebView. This method should be called
637      * after this WebView has been removed from the view system. No other
638      * methods may be called on this WebView after destroy.
639      */
destroy()640     public void destroy() {
641         checkThread();
642         mProvider.destroy();
643     }
644 
645     /**
646      * Enables platform notifications of data state and proxy changes.
647      * Notifications are enabled by default.
648      *
649      * @deprecated This method is now obsolete.
650      * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}
651      */
652     @Deprecated
enablePlatformNotifications()653     public static void enablePlatformNotifications() {
654         checkThread();
655         getFactory().getStatics().setPlatformNotificationsEnabled(true);
656     }
657 
658     /**
659      * Disables platform notifications of data state and proxy changes.
660      * Notifications are enabled by default.
661      *
662      * @deprecated This method is now obsolete.
663      * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}
664      */
665     @Deprecated
disablePlatformNotifications()666     public static void disablePlatformNotifications() {
667         checkThread();
668         getFactory().getStatics().setPlatformNotificationsEnabled(false);
669     }
670 
671     /**
672      * Informs WebView of the network state. This is used to set
673      * the JavaScript property window.navigator.isOnline and
674      * generates the online/offline event as specified in HTML5, sec. 5.7.7
675      *
676      * @param networkUp a boolean indicating if network is available
677      */
setNetworkAvailable(boolean networkUp)678     public void setNetworkAvailable(boolean networkUp) {
679         checkThread();
680         mProvider.setNetworkAvailable(networkUp);
681     }
682 
683     /**
684      * Saves the state of this WebView used in
685      * {@link android.app.Activity#onSaveInstanceState}. Please note that this
686      * method no longer stores the display data for this WebView. The previous
687      * behavior could potentially leak files if {@link #restoreState} was never
688      * called.
689      *
690      * @param outState the Bundle to store this WebView's state
691      * @return the same copy of the back/forward list used to save the state. If
692      *         saveState fails, the returned list will be null.
693      */
saveState(Bundle outState)694     public WebBackForwardList saveState(Bundle outState) {
695         checkThread();
696         return mProvider.saveState(outState);
697     }
698 
699     /**
700      * Saves the current display data to the Bundle given. Used in conjunction
701      * with {@link #saveState}.
702      * @param b a Bundle to store the display data
703      * @param dest the file to store the serialized picture data. Will be
704      *             overwritten with this WebView's picture data.
705      * @return true if the picture was successfully saved
706      * @deprecated This method is now obsolete.
707      * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}
708      */
709     @Deprecated
savePicture(Bundle b, final File dest)710     public boolean savePicture(Bundle b, final File dest) {
711         checkThread();
712         return mProvider.savePicture(b, dest);
713     }
714 
715     /**
716      * Restores the display data that was saved in {@link #savePicture}. Used in
717      * conjunction with {@link #restoreState}. Note that this will not work if
718      * this WebView is hardware accelerated.
719      *
720      * @param b a Bundle containing the saved display data
721      * @param src the file where the picture data was stored
722      * @return true if the picture was successfully restored
723      * @deprecated This method is now obsolete.
724      * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}
725      */
726     @Deprecated
restorePicture(Bundle b, File src)727     public boolean restorePicture(Bundle b, File src) {
728         checkThread();
729         return mProvider.restorePicture(b, src);
730     }
731 
732     /**
733      * Restores the state of this WebView from the given Bundle. This method is
734      * intended for use in {@link android.app.Activity#onRestoreInstanceState}
735      * and should be called to restore the state of this WebView. If
736      * it is called after this WebView has had a chance to build state (load
737      * pages, create a back/forward list, etc.) there may be undesirable
738      * side-effects. Please note that this method no longer restores the
739      * display data for this WebView.
740      *
741      * @param inState the incoming Bundle of state
742      * @return the restored back/forward list or null if restoreState failed
743      */
restoreState(Bundle inState)744     public WebBackForwardList restoreState(Bundle inState) {
745         checkThread();
746         return mProvider.restoreState(inState);
747     }
748 
749     /**
750      * Loads the given URL with the specified additional HTTP headers.
751      *
752      * @param url the URL of the resource to load
753      * @param additionalHttpHeaders the additional headers to be used in the
754      *            HTTP request for this URL, specified as a map from name to
755      *            value. Note that if this map contains any of the headers
756      *            that are set by default by this WebView, such as those
757      *            controlling caching, accept types or the User-Agent, their
758      *            values may be overriden by this WebView's defaults.
759      */
loadUrl(String url, Map<String, String> additionalHttpHeaders)760     public void loadUrl(String url, Map<String, String> additionalHttpHeaders) {
761         checkThread();
762         mProvider.loadUrl(url, additionalHttpHeaders);
763     }
764 
765     /**
766      * Loads the given URL.
767      *
768      * @param url the URL of the resource to load
769      */
loadUrl(String url)770     public void loadUrl(String url) {
771         checkThread();
772         mProvider.loadUrl(url);
773     }
774 
775     /**
776      * Loads the URL with postData using "POST" method into this WebView. If url
777      * is not a network URL, it will be loaded with {link
778      * {@link #loadUrl(String)} instead.
779      *
780      * @param url the URL of the resource to load
781      * @param postData the data will be passed to "POST" request
782      */
postUrl(String url, byte[] postData)783     public void postUrl(String url, byte[] postData) {
784         checkThread();
785         mProvider.postUrl(url, postData);
786     }
787 
788     /**
789      * Loads the given data into this WebView using a 'data' scheme URL.
790      * <p>
791      * Note that JavaScript's same origin policy means that script running in a
792      * page loaded using this method will be unable to access content loaded
793      * using any scheme other than 'data', including 'http(s)'. To avoid this
794      * restriction, use {@link
795      * #loadDataWithBaseURL(String,String,String,String,String)
796      * loadDataWithBaseURL()} with an appropriate base URL.
797      * <p>
798      * The encoding parameter specifies whether the data is base64 or URL
799      * encoded. If the data is base64 encoded, the value of the encoding
800      * parameter must be 'base64'. For all other values of the parameter,
801      * including null, it is assumed that the data uses ASCII encoding for
802      * octets inside the range of safe URL characters and use the standard %xx
803      * hex encoding of URLs for octets outside that range. For example, '#',
804      * '%', '\', '?' should be replaced by %23, %25, %27, %3f respectively.
805      * <p>
806      * The 'data' scheme URL formed by this method uses the default US-ASCII
807      * charset. If you need need to set a different charset, you should form a
808      * 'data' scheme URL which explicitly specifies a charset parameter in the
809      * mediatype portion of the URL and call {@link #loadUrl(String)} instead.
810      * Note that the charset obtained from the mediatype portion of a data URL
811      * always overrides that specified in the HTML or XML document itself.
812      *
813      * @param data a String of data in the given encoding
814      * @param mimeType the MIME type of the data, e.g. 'text/html'
815      * @param encoding the encoding of the data
816      */
loadData(String data, String mimeType, String encoding)817     public void loadData(String data, String mimeType, String encoding) {
818         checkThread();
819         mProvider.loadData(data, mimeType, encoding);
820     }
821 
822     /**
823      * Loads the given data into this WebView, using baseUrl as the base URL for
824      * the content. The base URL is used both to resolve relative URLs and when
825      * applying JavaScript's same origin policy. The historyUrl is used for the
826      * history entry.
827      * <p>
828      * Note that content specified in this way can access local device files
829      * (via 'file' scheme URLs) only if baseUrl specifies a scheme other than
830      * 'http', 'https', 'ftp', 'ftps', 'about' or 'javascript'.
831      * <p>
832      * If the base URL uses the data scheme, this method is equivalent to
833      * calling {@link #loadData(String,String,String) loadData()} and the
834      * historyUrl is ignored.
835      *
836      * @param baseUrl the URL to use as the page's base URL. If null defaults to
837      *                'about:blank'.
838      * @param data a String of data in the given encoding
839      * @param mimeType the MIMEType of the data, e.g. 'text/html'. If null,
840      *                 defaults to 'text/html'.
841      * @param encoding the encoding of the data
842      * @param historyUrl the URL to use as the history entry. If null defaults
843      *                   to 'about:blank'. If non-null, this must be a valid URL.
844      */
loadDataWithBaseURL(String baseUrl, String data, String mimeType, String encoding, String historyUrl)845     public void loadDataWithBaseURL(String baseUrl, String data,
846             String mimeType, String encoding, String historyUrl) {
847         checkThread();
848         mProvider.loadDataWithBaseURL(baseUrl, data, mimeType, encoding, historyUrl);
849     }
850 
851     /**
852      * Saves the current view as a web archive.
853      *
854      * @param filename the filename where the archive should be placed
855      */
saveWebArchive(String filename)856     public void saveWebArchive(String filename) {
857         checkThread();
858         mProvider.saveWebArchive(filename);
859     }
860 
861     /**
862      * Saves the current view as a web archive.
863      *
864      * @param basename the filename where the archive should be placed
865      * @param autoname if false, takes basename to be a file. If true, basename
866      *                 is assumed to be a directory in which a filename will be
867      *                 chosen according to the URL of the current page.
868      * @param callback called after the web archive has been saved. The
869      *                 parameter for onReceiveValue will either be the filename
870      *                 under which the file was saved, or null if saving the
871      *                 file failed.
872      */
saveWebArchive(String basename, boolean autoname, ValueCallback<String> callback)873     public void saveWebArchive(String basename, boolean autoname, ValueCallback<String> callback) {
874         checkThread();
875         mProvider.saveWebArchive(basename, autoname, callback);
876     }
877 
878     /**
879      * Stops the current load.
880      */
stopLoading()881     public void stopLoading() {
882         checkThread();
883         mProvider.stopLoading();
884     }
885 
886     /**
887      * Reloads the current URL.
888      */
reload()889     public void reload() {
890         checkThread();
891         mProvider.reload();
892     }
893 
894     /**
895      * Gets whether this WebView has a back history item.
896      *
897      * @return true iff this WebView has a back history item
898      */
canGoBack()899     public boolean canGoBack() {
900         checkThread();
901         return mProvider.canGoBack();
902     }
903 
904     /**
905      * Goes back in the history of this WebView.
906      */
goBack()907     public void goBack() {
908         checkThread();
909         mProvider.goBack();
910     }
911 
912     /**
913      * Gets whether this WebView has a forward history item.
914      *
915      * @return true iff this Webview has a forward history item
916      */
canGoForward()917     public boolean canGoForward() {
918         checkThread();
919         return mProvider.canGoForward();
920     }
921 
922     /**
923      * Goes forward in the history of this WebView.
924      */
goForward()925     public void goForward() {
926         checkThread();
927         mProvider.goForward();
928     }
929 
930     /**
931      * Gets whether the page can go back or forward the given
932      * number of steps.
933      *
934      * @param steps the negative or positive number of steps to move the
935      *              history
936      */
canGoBackOrForward(int steps)937     public boolean canGoBackOrForward(int steps) {
938         checkThread();
939         return mProvider.canGoBackOrForward(steps);
940     }
941 
942     /**
943      * Goes to the history item that is the number of steps away from
944      * the current item. Steps is negative if backward and positive
945      * if forward.
946      *
947      * @param steps the number of steps to take back or forward in the back
948      *              forward list
949      */
goBackOrForward(int steps)950     public void goBackOrForward(int steps) {
951         checkThread();
952         mProvider.goBackOrForward(steps);
953     }
954 
955     /**
956      * Gets whether private browsing is enabled in this WebView.
957      */
isPrivateBrowsingEnabled()958     public boolean isPrivateBrowsingEnabled() {
959         checkThread();
960         return mProvider.isPrivateBrowsingEnabled();
961     }
962 
963     /**
964      * Scrolls the contents of this WebView up by half the view size.
965      *
966      * @param top true to jump to the top of the page
967      * @return true if the page was scrolled
968      */
pageUp(boolean top)969     public boolean pageUp(boolean top) {
970         checkThread();
971         return mProvider.pageUp(top);
972     }
973 
974     /**
975      * Scrolls the contents of this WebView down by half the page size.
976      *
977      * @param bottom true to jump to bottom of page
978      * @return true if the page was scrolled
979      */
pageDown(boolean bottom)980     public boolean pageDown(boolean bottom) {
981         checkThread();
982         return mProvider.pageDown(bottom);
983     }
984 
985     /**
986      * Clears this WebView so that onDraw() will draw nothing but white background,
987      * and onMeasure() will return 0 if MeasureSpec is not MeasureSpec.EXACTLY.
988      * @deprecated Use WebView.loadUrl("about:blank") to reliably reset the view state
989      *             and release page resources (including any running JavaScript).
990      */
991     @Deprecated
clearView()992     public void clearView() {
993         checkThread();
994         mProvider.clearView();
995     }
996 
997     /**
998      * Gets a new picture that captures the current contents of this WebView.
999      * The picture is of the entire document being displayed, and is not
1000      * limited to the area currently displayed by this WebView. Also, the
1001      * picture is a static copy and is unaffected by later changes to the
1002      * content being displayed.
1003      * <p>
1004      * Note that due to internal changes, for API levels between
1005      * {@link android.os.Build.VERSION_CODES#HONEYCOMB} and
1006      * {@link android.os.Build.VERSION_CODES#ICE_CREAM_SANDWICH} inclusive, the
1007      * picture does not include fixed position elements or scrollable divs.
1008      *
1009      * @return a picture that captures the current contents of this WebView
1010      */
capturePicture()1011     public Picture capturePicture() {
1012         checkThread();
1013         return mProvider.capturePicture();
1014     }
1015 
1016     /**
1017      * Gets the current scale of this WebView.
1018      *
1019      * @return the current scale
1020      *
1021      * @deprecated This method is prone to inaccuracy due to race conditions
1022      * between the web rendering and UI threads; prefer
1023      * {@link WebViewClient#onScaleChanged}.
1024      */
1025     @Deprecated
1026     @ViewDebug.ExportedProperty(category = "webview")
getScale()1027     public float getScale() {
1028         checkThread();
1029         return mProvider.getScale();
1030     }
1031 
1032     /**
1033      * Sets the initial scale for this WebView. 0 means default. If
1034      * {@link WebSettings#getUseWideViewPort()} is true, it zooms out all the
1035      * way. Otherwise it starts with 100%. If initial scale is greater than 0,
1036      * WebView starts with this value as initial scale.
1037      * Please note that unlike the scale properties in the viewport meta tag,
1038      * this method doesn't take the screen density into account.
1039      *
1040      * @param scaleInPercent the initial scale in percent
1041      */
setInitialScale(int scaleInPercent)1042     public void setInitialScale(int scaleInPercent) {
1043         checkThread();
1044         mProvider.setInitialScale(scaleInPercent);
1045     }
1046 
1047     /**
1048      * Invokes the graphical zoom picker widget for this WebView. This will
1049      * result in the zoom widget appearing on the screen to control the zoom
1050      * level of this WebView.
1051      */
invokeZoomPicker()1052     public void invokeZoomPicker() {
1053         checkThread();
1054         mProvider.invokeZoomPicker();
1055     }
1056 
1057     /**
1058      * Gets a HitTestResult based on the current cursor node. If a HTML::a
1059      * tag is found and the anchor has a non-JavaScript URL, the HitTestResult
1060      * type is set to SRC_ANCHOR_TYPE and the URL is set in the "extra" field.
1061      * If the anchor does not have a URL or if it is a JavaScript URL, the type
1062      * will be UNKNOWN_TYPE and the URL has to be retrieved through
1063      * {@link #requestFocusNodeHref} asynchronously. If a HTML::img tag is
1064      * found, the HitTestResult type is set to IMAGE_TYPE and the URL is set in
1065      * the "extra" field. A type of
1066      * SRC_IMAGE_ANCHOR_TYPE indicates an anchor with a URL that has an image as
1067      * a child node. If a phone number is found, the HitTestResult type is set
1068      * to PHONE_TYPE and the phone number is set in the "extra" field of
1069      * HitTestResult. If a map address is found, the HitTestResult type is set
1070      * to GEO_TYPE and the address is set in the "extra" field of HitTestResult.
1071      * If an email address is found, the HitTestResult type is set to EMAIL_TYPE
1072      * and the email is set in the "extra" field of HitTestResult. Otherwise,
1073      * HitTestResult type is set to UNKNOWN_TYPE.
1074      */
getHitTestResult()1075     public HitTestResult getHitTestResult() {
1076         checkThread();
1077         return mProvider.getHitTestResult();
1078     }
1079 
1080     /**
1081      * Requests the anchor or image element URL at the last tapped point.
1082      * If hrefMsg is null, this method returns immediately and does not
1083      * dispatch hrefMsg to its target. If the tapped point hits an image,
1084      * an anchor, or an image in an anchor, the message associates
1085      * strings in named keys in its data. The value paired with the key
1086      * may be an empty string.
1087      *
1088      * @param hrefMsg the message to be dispatched with the result of the
1089      *                request. The message data contains three keys. "url"
1090      *                returns the anchor's href attribute. "title" returns the
1091      *                anchor's text. "src" returns the image's src attribute.
1092      */
requestFocusNodeHref(Message hrefMsg)1093     public void requestFocusNodeHref(Message hrefMsg) {
1094         checkThread();
1095         mProvider.requestFocusNodeHref(hrefMsg);
1096     }
1097 
1098     /**
1099      * Requests the URL of the image last touched by the user. msg will be sent
1100      * to its target with a String representing the URL as its object.
1101      *
1102      * @param msg the message to be dispatched with the result of the request
1103      *            as the data member with "url" as key. The result can be null.
1104      */
requestImageRef(Message msg)1105     public void requestImageRef(Message msg) {
1106         checkThread();
1107         mProvider.requestImageRef(msg);
1108     }
1109 
1110     /**
1111      * Gets the URL for the current page. This is not always the same as the URL
1112      * passed to WebViewClient.onPageStarted because although the load for
1113      * that URL has begun, the current page may not have changed.
1114      *
1115      * @return the URL for the current page
1116      */
1117     @ViewDebug.ExportedProperty(category = "webview")
getUrl()1118     public String getUrl() {
1119         checkThread();
1120         return mProvider.getUrl();
1121     }
1122 
1123     /**
1124      * Gets the original URL for the current page. This is not always the same
1125      * as the URL passed to WebViewClient.onPageStarted because although the
1126      * load for that URL has begun, the current page may not have changed.
1127      * Also, there may have been redirects resulting in a different URL to that
1128      * originally requested.
1129      *
1130      * @return the URL that was originally requested for the current page
1131      */
1132     @ViewDebug.ExportedProperty(category = "webview")
getOriginalUrl()1133     public String getOriginalUrl() {
1134         checkThread();
1135         return mProvider.getOriginalUrl();
1136     }
1137 
1138     /**
1139      * Gets the title for the current page. This is the title of the current page
1140      * until WebViewClient.onReceivedTitle is called.
1141      *
1142      * @return the title for the current page
1143      */
1144     @ViewDebug.ExportedProperty(category = "webview")
getTitle()1145     public String getTitle() {
1146         checkThread();
1147         return mProvider.getTitle();
1148     }
1149 
1150     /**
1151      * Gets the favicon for the current page. This is the favicon of the current
1152      * page until WebViewClient.onReceivedIcon is called.
1153      *
1154      * @return the favicon for the current page
1155      */
getFavicon()1156     public Bitmap getFavicon() {
1157         checkThread();
1158         return mProvider.getFavicon();
1159     }
1160 
1161     /**
1162      * Gets the touch icon URL for the apple-touch-icon <link> element, or
1163      * a URL on this site's server pointing to the standard location of a
1164      * touch icon.
1165      *
1166      * @hide
1167      */
getTouchIconUrl()1168     public String getTouchIconUrl() {
1169         return mProvider.getTouchIconUrl();
1170     }
1171 
1172     /**
1173      * Gets the progress for the current page.
1174      *
1175      * @return the progress for the current page between 0 and 100
1176      */
getProgress()1177     public int getProgress() {
1178         checkThread();
1179         return mProvider.getProgress();
1180     }
1181 
1182     /**
1183      * Gets the height of the HTML content.
1184      *
1185      * @return the height of the HTML content
1186      */
1187     @ViewDebug.ExportedProperty(category = "webview")
getContentHeight()1188     public int getContentHeight() {
1189         checkThread();
1190         return mProvider.getContentHeight();
1191     }
1192 
1193     /**
1194      * Gets the width of the HTML content.
1195      *
1196      * @return the width of the HTML content
1197      * @hide
1198      */
1199     @ViewDebug.ExportedProperty(category = "webview")
getContentWidth()1200     public int getContentWidth() {
1201         return mProvider.getContentWidth();
1202     }
1203 
1204     /**
1205      * Pauses all layout, parsing, and JavaScript timers for all WebViews. This
1206      * is a global requests, not restricted to just this WebView. This can be
1207      * useful if the application has been paused.
1208      */
pauseTimers()1209     public void pauseTimers() {
1210         checkThread();
1211         mProvider.pauseTimers();
1212     }
1213 
1214     /**
1215      * Resumes all layout, parsing, and JavaScript timers for all WebViews.
1216      * This will resume dispatching all timers.
1217      */
resumeTimers()1218     public void resumeTimers() {
1219         checkThread();
1220         mProvider.resumeTimers();
1221     }
1222 
1223     /**
1224      * Pauses any extra processing associated with this WebView and its
1225      * associated DOM, plugins, JavaScript etc. For example, if this WebView is
1226      * taken offscreen, this could be called to reduce unnecessary CPU or
1227      * network traffic. When this WebView is again "active", call onResume().
1228      * Note that this differs from pauseTimers(), which affects all WebViews.
1229      */
onPause()1230     public void onPause() {
1231         checkThread();
1232         mProvider.onPause();
1233     }
1234 
1235     /**
1236      * Resumes a WebView after a previous call to onPause().
1237      */
onResume()1238     public void onResume() {
1239         checkThread();
1240         mProvider.onResume();
1241     }
1242 
1243     /**
1244      * Gets whether this WebView is paused, meaning onPause() was called.
1245      * Calling onResume() sets the paused state back to false.
1246      *
1247      * @hide
1248      */
isPaused()1249     public boolean isPaused() {
1250         return mProvider.isPaused();
1251     }
1252 
1253     /**
1254      * Informs this WebView that memory is low so that it can free any available
1255      * memory.
1256      */
freeMemory()1257     public void freeMemory() {
1258         checkThread();
1259         mProvider.freeMemory();
1260     }
1261 
1262     /**
1263      * Clears the resource cache. Note that the cache is per-application, so
1264      * this will clear the cache for all WebViews used.
1265      *
1266      * @param includeDiskFiles if false, only the RAM cache is cleared
1267      */
clearCache(boolean includeDiskFiles)1268     public void clearCache(boolean includeDiskFiles) {
1269         checkThread();
1270         mProvider.clearCache(includeDiskFiles);
1271     }
1272 
1273     /**
1274      * Removes the autocomplete popup from the currently focused form field, if
1275      * present. Note this only affects the display of the autocomplete popup,
1276      * it does not remove any saved form data from this WebView's store. To do
1277      * that, use {@link WebViewDatabase#clearFormData}.
1278      */
clearFormData()1279     public void clearFormData() {
1280         checkThread();
1281         mProvider.clearFormData();
1282     }
1283 
1284     /**
1285      * Tells this WebView to clear its internal back/forward list.
1286      */
clearHistory()1287     public void clearHistory() {
1288         checkThread();
1289         mProvider.clearHistory();
1290     }
1291 
1292     /**
1293      * Clears the SSL preferences table stored in response to proceeding with
1294      * SSL certificate errors.
1295      */
clearSslPreferences()1296     public void clearSslPreferences() {
1297         checkThread();
1298         mProvider.clearSslPreferences();
1299     }
1300 
1301     /**
1302      * Gets the WebBackForwardList for this WebView. This contains the
1303      * back/forward list for use in querying each item in the history stack.
1304      * This is a copy of the private WebBackForwardList so it contains only a
1305      * snapshot of the current state. Multiple calls to this method may return
1306      * different objects. The object returned from this method will not be
1307      * updated to reflect any new state.
1308      */
copyBackForwardList()1309     public WebBackForwardList copyBackForwardList() {
1310         checkThread();
1311         return mProvider.copyBackForwardList();
1312 
1313     }
1314 
1315     /**
1316      * Registers the listener to be notified as find-on-page operations
1317      * progress. This will replace the current listener.
1318      *
1319      * @param listener an implementation of {@link FindListener}
1320      */
setFindListener(FindListener listener)1321     public void setFindListener(FindListener listener) {
1322         checkThread();
1323         setupFindListenerIfNeeded();
1324         mFindListener.mUserFindListener = listener;
1325     }
1326 
1327     /**
1328      * Highlights and scrolls to the next match found by
1329      * {@link #findAllAsync}, wrapping around page boundaries as necessary.
1330      * Notifies any registered {@link FindListener}. If {@link #findAllAsync(String)}
1331      * has not been called yet, or if {@link #clearMatches} has been called since the
1332      * last find operation, this function does nothing.
1333      *
1334      * @param forward the direction to search
1335      * @see #setFindListener
1336      */
findNext(boolean forward)1337     public void findNext(boolean forward) {
1338         checkThread();
1339         mProvider.findNext(forward);
1340     }
1341 
1342     /**
1343      * Finds all instances of find on the page and highlights them.
1344      * Notifies any registered {@link FindListener}.
1345      *
1346      * @param find the string to find
1347      * @return the number of occurances of the String "find" that were found
1348      * @deprecated {@link #findAllAsync} is preferred.
1349      * @see #setFindListener
1350      */
1351     @Deprecated
findAll(String find)1352     public int findAll(String find) {
1353         checkThread();
1354         StrictMode.noteSlowCall("findAll blocks UI: prefer findAllAsync");
1355         return mProvider.findAll(find);
1356     }
1357 
1358     /**
1359      * Finds all instances of find on the page and highlights them,
1360      * asynchronously. Notifies any registered {@link FindListener}.
1361      * Successive calls to this will cancel any pending searches.
1362      *
1363      * @param find the string to find.
1364      * @see #setFindListener
1365      */
findAllAsync(String find)1366     public void findAllAsync(String find) {
1367         checkThread();
1368         mProvider.findAllAsync(find);
1369     }
1370 
1371     /**
1372      * Starts an ActionMode for finding text in this WebView.  Only works if this
1373      * WebView is attached to the view system.
1374      *
1375      * @param text if non-null, will be the initial text to search for.
1376      *             Otherwise, the last String searched for in this WebView will
1377      *             be used to start.
1378      * @param showIme if true, show the IME, assuming the user will begin typing.
1379      *                If false and text is non-null, perform a find all.
1380      * @return true if the find dialog is shown, false otherwise
1381      * @deprecated This method does not work reliably on all Android versions;
1382      *             implementing a custom find dialog using WebView.findAllAsync()
1383      *             provides a more robust solution.
1384      */
1385     @Deprecated
showFindDialog(String text, boolean showIme)1386     public boolean showFindDialog(String text, boolean showIme) {
1387         checkThread();
1388         return mProvider.showFindDialog(text, showIme);
1389     }
1390 
1391     /**
1392      * Gets the first substring consisting of the address of a physical
1393      * location. Currently, only addresses in the United States are detected,
1394      * and consist of:
1395      * <ul>
1396      *   <li>a house number</li>
1397      *   <li>a street name</li>
1398      *   <li>a street type (Road, Circle, etc), either spelled out or
1399      *       abbreviated</li>
1400      *   <li>a city name</li>
1401      *   <li>a state or territory, either spelled out or two-letter abbr</li>
1402      *   <li>an optional 5 digit or 9 digit zip code</li>
1403      * </ul>
1404      * All names must be correctly capitalized, and the zip code, if present,
1405      * must be valid for the state. The street type must be a standard USPS
1406      * spelling or abbreviation. The state or territory must also be spelled
1407      * or abbreviated using USPS standards. The house number may not exceed
1408      * five digits.
1409      *
1410      * @param addr the string to search for addresses
1411      * @return the address, or if no address is found, null
1412      */
findAddress(String addr)1413     public static String findAddress(String addr) {
1414         return getFactory().getStatics().findAddress(addr);
1415     }
1416 
1417     /**
1418      * Clears the highlighting surrounding text matches created by
1419      * {@link #findAllAsync}.
1420      */
clearMatches()1421     public void clearMatches() {
1422         checkThread();
1423         mProvider.clearMatches();
1424     }
1425 
1426     /**
1427      * Queries the document to see if it contains any image references. The
1428      * message object will be dispatched with arg1 being set to 1 if images
1429      * were found and 0 if the document does not reference any images.
1430      *
1431      * @param response the message that will be dispatched with the result
1432      */
documentHasImages(Message response)1433     public void documentHasImages(Message response) {
1434         checkThread();
1435         mProvider.documentHasImages(response);
1436     }
1437 
1438     /**
1439      * Sets the WebViewClient that will receive various notifications and
1440      * requests. This will replace the current handler.
1441      *
1442      * @param client an implementation of WebViewClient
1443      */
setWebViewClient(WebViewClient client)1444     public void setWebViewClient(WebViewClient client) {
1445         checkThread();
1446         mProvider.setWebViewClient(client);
1447     }
1448 
1449     /**
1450      * Registers the interface to be used when content can not be handled by
1451      * the rendering engine, and should be downloaded instead. This will replace
1452      * the current handler.
1453      *
1454      * @param listener an implementation of DownloadListener
1455      */
setDownloadListener(DownloadListener listener)1456     public void setDownloadListener(DownloadListener listener) {
1457         checkThread();
1458         mProvider.setDownloadListener(listener);
1459     }
1460 
1461     /**
1462      * Sets the chrome handler. This is an implementation of WebChromeClient for
1463      * use in handling JavaScript dialogs, favicons, titles, and the progress.
1464      * This will replace the current handler.
1465      *
1466      * @param client an implementation of WebChromeClient
1467      */
setWebChromeClient(WebChromeClient client)1468     public void setWebChromeClient(WebChromeClient client) {
1469         checkThread();
1470         mProvider.setWebChromeClient(client);
1471     }
1472 
1473     /**
1474      * Sets the Picture listener. This is an interface used to receive
1475      * notifications of a new Picture.
1476      *
1477      * @param listener an implementation of WebView.PictureListener
1478      * @deprecated This method is now obsolete.
1479      */
1480     @Deprecated
setPictureListener(PictureListener listener)1481     public void setPictureListener(PictureListener listener) {
1482         checkThread();
1483         mProvider.setPictureListener(listener);
1484     }
1485 
1486     /**
1487      * Injects the supplied Java object into this WebView. The object is
1488      * injected into the JavaScript context of the main frame, using the
1489      * supplied name. This allows the Java object's methods to be
1490      * accessed from JavaScript. For applications targeted to API
1491      * level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}
1492      * and above, only public methods that are annotated with
1493      * {@link android.webkit.JavascriptInterface} can be accessed from JavaScript.
1494      * For applications targeted to API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN} or below,
1495      * all public methods (including the inherited ones) can be accessed, see the
1496      * important security note below for implications.
1497      * <p> Note that injected objects will not
1498      * appear in JavaScript until the page is next (re)loaded. For example:
1499      * <pre>
1500      * class JsObject {
1501      *    {@literal @}JavascriptInterface
1502      *    public String toString() { return "injectedObject"; }
1503      * }
1504      * webView.addJavascriptInterface(new JsObject(), "injectedObject");
1505      * webView.loadData("<!DOCTYPE html><title></title>", "text/html", null);
1506      * webView.loadUrl("javascript:alert(injectedObject.toString())");</pre>
1507      * <p>
1508      * <strong>IMPORTANT:</strong>
1509      * <ul>
1510      * <li> This method can be used to allow JavaScript to control the host
1511      * application. This is a powerful feature, but also presents a security
1512      * risk for applications targeted to API level
1513      * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} or below, because
1514      * JavaScript could use reflection to access an
1515      * injected object's public fields. Use of this method in a WebView
1516      * containing untrusted content could allow an attacker to manipulate the
1517      * host application in unintended ways, executing Java code with the
1518      * permissions of the host application. Use extreme care when using this
1519      * method in a WebView which could contain untrusted content.</li>
1520      * <li> JavaScript interacts with Java object on a private, background
1521      * thread of this WebView. Care is therefore required to maintain thread
1522      * safety.</li>
1523      * <li> The Java object's fields are not accessible.</li>
1524      * </ul>
1525      *
1526      * @param object the Java object to inject into this WebView's JavaScript
1527      *               context. Null values are ignored.
1528      * @param name the name used to expose the object in JavaScript
1529      */
addJavascriptInterface(Object object, String name)1530     public void addJavascriptInterface(Object object, String name) {
1531         checkThread();
1532         mProvider.addJavascriptInterface(object, name);
1533     }
1534 
1535     /**
1536      * Removes a previously injected Java object from this WebView. Note that
1537      * the removal will not be reflected in JavaScript until the page is next
1538      * (re)loaded. See {@link #addJavascriptInterface}.
1539      *
1540      * @param name the name used to expose the object in JavaScript
1541      */
removeJavascriptInterface(String name)1542     public void removeJavascriptInterface(String name) {
1543         checkThread();
1544         mProvider.removeJavascriptInterface(name);
1545     }
1546 
1547     /**
1548      * Gets the WebSettings object used to control the settings for this
1549      * WebView.
1550      *
1551      * @return a WebSettings object that can be used to control this WebView's
1552      *         settings
1553      */
getSettings()1554     public WebSettings getSettings() {
1555         checkThread();
1556         return mProvider.getSettings();
1557     }
1558 
1559     /**
1560      * Gets the list of currently loaded plugins.
1561      *
1562      * @return the list of currently loaded plugins
1563      * @deprecated This was used for Gears, which has been deprecated.
1564      * @hide
1565      */
1566     @Deprecated
getPluginList()1567     public static synchronized PluginList getPluginList() {
1568         checkThread();
1569         return new PluginList();
1570     }
1571 
1572     /**
1573      * @deprecated This was used for Gears, which has been deprecated.
1574      * @hide
1575      */
1576     @Deprecated
refreshPlugins(boolean reloadOpenPages)1577     public void refreshPlugins(boolean reloadOpenPages) {
1578         checkThread();
1579     }
1580 
1581     /**
1582      * Puts this WebView into text selection mode. Do not rely on this
1583      * functionality; it will be deprecated in the future.
1584      *
1585      * @deprecated This method is now obsolete.
1586      * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}
1587      */
1588     @Deprecated
emulateShiftHeld()1589     public void emulateShiftHeld() {
1590         checkThread();
1591     }
1592 
1593     /**
1594      * @deprecated WebView no longer needs to implement
1595      * ViewGroup.OnHierarchyChangeListener.  This method does nothing now.
1596      */
1597     @Override
1598     // Cannot add @hide as this can always be accessed via the interface.
1599     @Deprecated
onChildViewAdded(View parent, View child)1600     public void onChildViewAdded(View parent, View child) {}
1601 
1602     /**
1603      * @deprecated WebView no longer needs to implement
1604      * ViewGroup.OnHierarchyChangeListener.  This method does nothing now.
1605      */
1606     @Override
1607     // Cannot add @hide as this can always be accessed via the interface.
1608     @Deprecated
onChildViewRemoved(View p, View child)1609     public void onChildViewRemoved(View p, View child) {}
1610 
1611     /**
1612      * @deprecated WebView should not have implemented
1613      * ViewTreeObserver.OnGlobalFocusChangeListener. This method does nothing now.
1614      */
1615     @Override
1616     // Cannot add @hide as this can always be accessed via the interface.
1617     @Deprecated
onGlobalFocusChanged(View oldFocus, View newFocus)1618     public void onGlobalFocusChanged(View oldFocus, View newFocus) {
1619     }
1620 
1621     /**
1622      * @deprecated Only the default case, true, will be supported in a future version.
1623      */
1624     @Deprecated
setMapTrackballToArrowKeys(boolean setMap)1625     public void setMapTrackballToArrowKeys(boolean setMap) {
1626         checkThread();
1627         mProvider.setMapTrackballToArrowKeys(setMap);
1628     }
1629 
1630 
flingScroll(int vx, int vy)1631     public void flingScroll(int vx, int vy) {
1632         checkThread();
1633         mProvider.flingScroll(vx, vy);
1634     }
1635 
1636     /**
1637      * Gets the zoom controls for this WebView, as a separate View. The caller
1638      * is responsible for inserting this View into the layout hierarchy.
1639      * <p/>
1640      * API level {@link android.os.Build.VERSION_CODES#CUPCAKE} introduced
1641      * built-in zoom mechanisms for the WebView, as opposed to these separate
1642      * zoom controls. The built-in mechanisms are preferred and can be enabled
1643      * using {@link WebSettings#setBuiltInZoomControls}.
1644      *
1645      * @deprecated the built-in zoom mechanisms are preferred
1646      * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN}
1647      */
1648     @Deprecated
getZoomControls()1649     public View getZoomControls() {
1650         checkThread();
1651         return mProvider.getZoomControls();
1652     }
1653 
1654     /**
1655      * Gets whether this WebView can be zoomed in.
1656      *
1657      * @return true if this WebView can be zoomed in
1658      *
1659      * @deprecated This method is prone to inaccuracy due to race conditions
1660      * between the web rendering and UI threads; prefer
1661      * {@link WebViewClient#onScaleChanged}.
1662      */
1663     @Deprecated
canZoomIn()1664     public boolean canZoomIn() {
1665         checkThread();
1666         return mProvider.canZoomIn();
1667     }
1668 
1669     /**
1670      * Gets whether this WebView can be zoomed out.
1671      *
1672      * @return true if this WebView can be zoomed out
1673      *
1674      * @deprecated This method is prone to inaccuracy due to race conditions
1675      * between the web rendering and UI threads; prefer
1676      * {@link WebViewClient#onScaleChanged}.
1677      */
1678     @Deprecated
canZoomOut()1679     public boolean canZoomOut() {
1680         checkThread();
1681         return mProvider.canZoomOut();
1682     }
1683 
1684     /**
1685      * Performs zoom in in this WebView.
1686      *
1687      * @return true if zoom in succeeds, false if no zoom changes
1688      */
zoomIn()1689     public boolean zoomIn() {
1690         checkThread();
1691         return mProvider.zoomIn();
1692     }
1693 
1694     /**
1695      * Performs zoom out in this WebView.
1696      *
1697      * @return true if zoom out succeeds, false if no zoom changes
1698      */
zoomOut()1699     public boolean zoomOut() {
1700         checkThread();
1701         return mProvider.zoomOut();
1702     }
1703 
1704     /**
1705      * @deprecated This method is now obsolete.
1706      * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}
1707      */
1708     @Deprecated
debugDump()1709     public void debugDump() {
1710         checkThread();
1711     }
1712 
1713     /**
1714      * See {@link ViewDebug.HierarchyHandler#dumpViewHierarchyWithProperties(BufferedWriter, int)}
1715      * @hide
1716      */
1717     @Override
dumpViewHierarchyWithProperties(BufferedWriter out, int level)1718     public void dumpViewHierarchyWithProperties(BufferedWriter out, int level) {
1719         mProvider.dumpViewHierarchyWithProperties(out, level);
1720     }
1721 
1722     /**
1723      * See {@link ViewDebug.HierarchyHandler#findHierarchyView(String, int)}
1724      * @hide
1725      */
1726     @Override
findHierarchyView(String className, int hashCode)1727     public View findHierarchyView(String className, int hashCode) {
1728         return mProvider.findHierarchyView(className, hashCode);
1729     }
1730 
1731     //-------------------------------------------------------------------------
1732     // Interface for WebView providers
1733     //-------------------------------------------------------------------------
1734 
1735     /**
1736      * Gets the WebViewProvider. Used by providers to obtain the underlying
1737      * implementation, e.g. when the appliction responds to
1738      * WebViewClient.onCreateWindow() request.
1739      *
1740      * @hide WebViewProvider is not public API.
1741      */
getWebViewProvider()1742     public WebViewProvider getWebViewProvider() {
1743         return mProvider;
1744     }
1745 
1746     /**
1747      * Callback interface, allows the provider implementation to access non-public methods
1748      * and fields, and make super-class calls in this WebView instance.
1749      * @hide Only for use by WebViewProvider implementations
1750      */
1751     public class PrivateAccess {
1752         // ---- Access to super-class methods ----
super_getScrollBarStyle()1753         public int super_getScrollBarStyle() {
1754             return WebView.super.getScrollBarStyle();
1755         }
1756 
super_scrollTo(int scrollX, int scrollY)1757         public void super_scrollTo(int scrollX, int scrollY) {
1758             WebView.super.scrollTo(scrollX, scrollY);
1759         }
1760 
super_computeScroll()1761         public void super_computeScroll() {
1762             WebView.super.computeScroll();
1763         }
1764 
super_onHoverEvent(MotionEvent event)1765         public boolean super_onHoverEvent(MotionEvent event) {
1766             return WebView.super.onHoverEvent(event);
1767         }
1768 
super_performAccessibilityAction(int action, Bundle arguments)1769         public boolean super_performAccessibilityAction(int action, Bundle arguments) {
1770             return WebView.super.performAccessibilityAction(action, arguments);
1771         }
1772 
super_performLongClick()1773         public boolean super_performLongClick() {
1774             return WebView.super.performLongClick();
1775         }
1776 
super_setFrame(int left, int top, int right, int bottom)1777         public boolean super_setFrame(int left, int top, int right, int bottom) {
1778             return WebView.super.setFrame(left, top, right, bottom);
1779         }
1780 
super_dispatchKeyEvent(KeyEvent event)1781         public boolean super_dispatchKeyEvent(KeyEvent event) {
1782             return WebView.super.dispatchKeyEvent(event);
1783         }
1784 
super_onGenericMotionEvent(MotionEvent event)1785         public boolean super_onGenericMotionEvent(MotionEvent event) {
1786             return WebView.super.onGenericMotionEvent(event);
1787         }
1788 
super_requestFocus(int direction, Rect previouslyFocusedRect)1789         public boolean super_requestFocus(int direction, Rect previouslyFocusedRect) {
1790             return WebView.super.requestFocus(direction, previouslyFocusedRect);
1791         }
1792 
super_setLayoutParams(ViewGroup.LayoutParams params)1793         public void super_setLayoutParams(ViewGroup.LayoutParams params) {
1794             WebView.super.setLayoutParams(params);
1795         }
1796 
1797         // ---- Access to non-public methods ----
overScrollBy(int deltaX, int deltaY, int scrollX, int scrollY, int scrollRangeX, int scrollRangeY, int maxOverScrollX, int maxOverScrollY, boolean isTouchEvent)1798         public void overScrollBy(int deltaX, int deltaY,
1799                 int scrollX, int scrollY,
1800                 int scrollRangeX, int scrollRangeY,
1801                 int maxOverScrollX, int maxOverScrollY,
1802                 boolean isTouchEvent) {
1803             WebView.this.overScrollBy(deltaX, deltaY, scrollX, scrollY, scrollRangeX, scrollRangeY,
1804                     maxOverScrollX, maxOverScrollY, isTouchEvent);
1805         }
1806 
awakenScrollBars(int duration)1807         public void awakenScrollBars(int duration) {
1808             WebView.this.awakenScrollBars(duration);
1809         }
1810 
awakenScrollBars(int duration, boolean invalidate)1811         public void awakenScrollBars(int duration, boolean invalidate) {
1812             WebView.this.awakenScrollBars(duration, invalidate);
1813         }
1814 
getVerticalScrollFactor()1815         public float getVerticalScrollFactor() {
1816             return WebView.this.getVerticalScrollFactor();
1817         }
1818 
getHorizontalScrollFactor()1819         public float getHorizontalScrollFactor() {
1820             return WebView.this.getHorizontalScrollFactor();
1821         }
1822 
setMeasuredDimension(int measuredWidth, int measuredHeight)1823         public void setMeasuredDimension(int measuredWidth, int measuredHeight) {
1824             WebView.this.setMeasuredDimension(measuredWidth, measuredHeight);
1825         }
1826 
onScrollChanged(int l, int t, int oldl, int oldt)1827         public void onScrollChanged(int l, int t, int oldl, int oldt) {
1828             WebView.this.onScrollChanged(l, t, oldl, oldt);
1829         }
1830 
getHorizontalScrollbarHeight()1831         public int getHorizontalScrollbarHeight() {
1832             return WebView.this.getHorizontalScrollbarHeight();
1833         }
1834 
1835         // ---- Access to (non-public) fields ----
1836         /** Raw setter for the scroll X value, without invoking onScrollChanged handlers etc. */
setScrollXRaw(int scrollX)1837         public void setScrollXRaw(int scrollX) {
1838             WebView.this.mScrollX = scrollX;
1839         }
1840 
1841         /** Raw setter for the scroll Y value, without invoking onScrollChanged handlers etc. */
setScrollYRaw(int scrollY)1842         public void setScrollYRaw(int scrollY) {
1843             WebView.this.mScrollY = scrollY;
1844         }
1845 
1846     }
1847 
1848     //-------------------------------------------------------------------------
1849     // Package-private internal stuff
1850     //-------------------------------------------------------------------------
1851 
1852     // Only used by android.webkit.FindActionModeCallback.
setFindDialogFindListener(FindListener listener)1853     void setFindDialogFindListener(FindListener listener) {
1854         checkThread();
1855         setupFindListenerIfNeeded();
1856         mFindListener.mFindDialogFindListener = listener;
1857     }
1858 
1859     // Only used by android.webkit.FindActionModeCallback.
notifyFindDialogDismissed()1860     void notifyFindDialogDismissed() {
1861         checkThread();
1862         mProvider.notifyFindDialogDismissed();
1863     }
1864 
1865     //-------------------------------------------------------------------------
1866     // Private internal stuff
1867     //-------------------------------------------------------------------------
1868 
1869     private WebViewProvider mProvider;
1870 
1871     /**
1872      * In addition to the FindListener that the user may set via the WebView.setFindListener
1873      * API, FindActionModeCallback will register it's own FindListener. We keep them separate
1874      * via this class so that that the two FindListeners can potentially exist at once.
1875      */
1876     private class FindListenerDistributor implements FindListener {
1877         private FindListener mFindDialogFindListener;
1878         private FindListener mUserFindListener;
1879 
1880         @Override
onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting)1881         public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches,
1882                 boolean isDoneCounting) {
1883             if (mFindDialogFindListener != null) {
1884                 mFindDialogFindListener.onFindResultReceived(activeMatchOrdinal, numberOfMatches,
1885                         isDoneCounting);
1886             }
1887 
1888             if (mUserFindListener != null) {
1889                 mUserFindListener.onFindResultReceived(activeMatchOrdinal, numberOfMatches,
1890                         isDoneCounting);
1891             }
1892         }
1893     }
1894     private FindListenerDistributor mFindListener;
1895 
setupFindListenerIfNeeded()1896     private void setupFindListenerIfNeeded() {
1897         if (mFindListener == null) {
1898             mFindListener = new FindListenerDistributor();
1899             mProvider.setFindListener(mFindListener);
1900         }
1901     }
1902 
ensureProviderCreated()1903     private void ensureProviderCreated() {
1904         checkThread();
1905         if (mProvider == null) {
1906             // As this can get called during the base class constructor chain, pass the minimum
1907             // number of dependencies here; the rest are deferred to init().
1908             mProvider = getFactory().createWebView(this, new PrivateAccess());
1909         }
1910     }
1911 
getFactory()1912     private static synchronized WebViewFactoryProvider getFactory() {
1913         return WebViewFactory.getProvider();
1914     }
1915 
checkThread()1916     private static void checkThread() {
1917         if (Looper.myLooper() != Looper.getMainLooper()) {
1918             Throwable throwable = new Throwable(
1919                     "Warning: A WebView method was called on thread '" +
1920                     Thread.currentThread().getName() + "'. " +
1921                     "All WebView methods must be called on the UI thread. " +
1922                     "Future versions of WebView may not support use on other threads.");
1923             Log.w(LOGTAG, Log.getStackTraceString(throwable));
1924             StrictMode.onWebViewMethodCalledOnWrongThread(throwable);
1925 
1926             if (sEnforceThreadChecking) {
1927                 throw new RuntimeException(throwable);
1928             }
1929         }
1930     }
1931 
1932     //-------------------------------------------------------------------------
1933     // Override View methods
1934     //-------------------------------------------------------------------------
1935 
1936     // TODO: Add a test that enumerates all methods in ViewDelegte & ScrollDelegate, and ensures
1937     // there's a corresponding override (or better, caller) for each of them in here.
1938 
1939     @Override
onAttachedToWindow()1940     protected void onAttachedToWindow() {
1941         super.onAttachedToWindow();
1942         mProvider.getViewDelegate().onAttachedToWindow();
1943     }
1944 
1945     @Override
onDetachedFromWindow()1946     protected void onDetachedFromWindow() {
1947         mProvider.getViewDelegate().onDetachedFromWindow();
1948         super.onDetachedFromWindow();
1949     }
1950 
1951     @Override
setLayoutParams(ViewGroup.LayoutParams params)1952     public void setLayoutParams(ViewGroup.LayoutParams params) {
1953         mProvider.getViewDelegate().setLayoutParams(params);
1954     }
1955 
1956     @Override
setOverScrollMode(int mode)1957     public void setOverScrollMode(int mode) {
1958         super.setOverScrollMode(mode);
1959         // This method may be called in the constructor chain, before the WebView provider is
1960         // created.
1961         ensureProviderCreated();
1962         mProvider.getViewDelegate().setOverScrollMode(mode);
1963     }
1964 
1965     @Override
setScrollBarStyle(int style)1966     public void setScrollBarStyle(int style) {
1967         mProvider.getViewDelegate().setScrollBarStyle(style);
1968         super.setScrollBarStyle(style);
1969     }
1970 
1971     @Override
computeHorizontalScrollRange()1972     protected int computeHorizontalScrollRange() {
1973         return mProvider.getScrollDelegate().computeHorizontalScrollRange();
1974     }
1975 
1976     @Override
computeHorizontalScrollOffset()1977     protected int computeHorizontalScrollOffset() {
1978         return mProvider.getScrollDelegate().computeHorizontalScrollOffset();
1979     }
1980 
1981     @Override
computeVerticalScrollRange()1982     protected int computeVerticalScrollRange() {
1983         return mProvider.getScrollDelegate().computeVerticalScrollRange();
1984     }
1985 
1986     @Override
computeVerticalScrollOffset()1987     protected int computeVerticalScrollOffset() {
1988         return mProvider.getScrollDelegate().computeVerticalScrollOffset();
1989     }
1990 
1991     @Override
computeVerticalScrollExtent()1992     protected int computeVerticalScrollExtent() {
1993         return mProvider.getScrollDelegate().computeVerticalScrollExtent();
1994     }
1995 
1996     @Override
computeScroll()1997     public void computeScroll() {
1998         mProvider.getScrollDelegate().computeScroll();
1999     }
2000 
2001     @Override
onHoverEvent(MotionEvent event)2002     public boolean onHoverEvent(MotionEvent event) {
2003         return mProvider.getViewDelegate().onHoverEvent(event);
2004     }
2005 
2006     @Override
onTouchEvent(MotionEvent event)2007     public boolean onTouchEvent(MotionEvent event) {
2008         return mProvider.getViewDelegate().onTouchEvent(event);
2009     }
2010 
2011     @Override
onGenericMotionEvent(MotionEvent event)2012     public boolean onGenericMotionEvent(MotionEvent event) {
2013         return mProvider.getViewDelegate().onGenericMotionEvent(event);
2014     }
2015 
2016     @Override
onTrackballEvent(MotionEvent event)2017     public boolean onTrackballEvent(MotionEvent event) {
2018         return mProvider.getViewDelegate().onTrackballEvent(event);
2019     }
2020 
2021     @Override
onKeyDown(int keyCode, KeyEvent event)2022     public boolean onKeyDown(int keyCode, KeyEvent event) {
2023         return mProvider.getViewDelegate().onKeyDown(keyCode, event);
2024     }
2025 
2026     @Override
onKeyUp(int keyCode, KeyEvent event)2027     public boolean onKeyUp(int keyCode, KeyEvent event) {
2028         return mProvider.getViewDelegate().onKeyUp(keyCode, event);
2029     }
2030 
2031     @Override
onKeyMultiple(int keyCode, int repeatCount, KeyEvent event)2032     public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
2033         return mProvider.getViewDelegate().onKeyMultiple(keyCode, repeatCount, event);
2034     }
2035 
2036     /*
2037     TODO: These are not currently implemented in WebViewClassic, but it seems inconsistent not
2038     to be delegating them too.
2039 
2040     @Override
2041     public boolean onKeyPreIme(int keyCode, KeyEvent event) {
2042         return mProvider.getViewDelegate().onKeyPreIme(keyCode, event);
2043     }
2044     @Override
2045     public boolean onKeyLongPress(int keyCode, KeyEvent event) {
2046         return mProvider.getViewDelegate().onKeyLongPress(keyCode, event);
2047     }
2048     @Override
2049     public boolean onKeyShortcut(int keyCode, KeyEvent event) {
2050         return mProvider.getViewDelegate().onKeyShortcut(keyCode, event);
2051     }
2052     */
2053 
2054     @Deprecated
2055     @Override
shouldDelayChildPressedState()2056     public boolean shouldDelayChildPressedState() {
2057         return mProvider.getViewDelegate().shouldDelayChildPressedState();
2058     }
2059 
2060     @Override
onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info)2061     public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
2062         super.onInitializeAccessibilityNodeInfo(info);
2063         info.setClassName(WebView.class.getName());
2064         mProvider.getViewDelegate().onInitializeAccessibilityNodeInfo(info);
2065     }
2066 
2067     @Override
onInitializeAccessibilityEvent(AccessibilityEvent event)2068     public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
2069         super.onInitializeAccessibilityEvent(event);
2070         event.setClassName(WebView.class.getName());
2071         mProvider.getViewDelegate().onInitializeAccessibilityEvent(event);
2072     }
2073 
2074     @Override
performAccessibilityAction(int action, Bundle arguments)2075     public boolean performAccessibilityAction(int action, Bundle arguments) {
2076         return mProvider.getViewDelegate().performAccessibilityAction(action, arguments);
2077     }
2078 
2079     /** @hide */
2080     @Override
onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, int l, int t, int r, int b)2081     protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
2082             int l, int t, int r, int b) {
2083         mProvider.getViewDelegate().onDrawVerticalScrollBar(canvas, scrollBar, l, t, r, b);
2084     }
2085 
2086     @Override
onOverScrolled(int scrollX, int scrollY, boolean clampedX, boolean clampedY)2087     protected void onOverScrolled(int scrollX, int scrollY, boolean clampedX, boolean clampedY) {
2088         mProvider.getViewDelegate().onOverScrolled(scrollX, scrollY, clampedX, clampedY);
2089     }
2090 
2091     @Override
onWindowVisibilityChanged(int visibility)2092     protected void onWindowVisibilityChanged(int visibility) {
2093         super.onWindowVisibilityChanged(visibility);
2094         mProvider.getViewDelegate().onWindowVisibilityChanged(visibility);
2095     }
2096 
2097     @Override
onDraw(Canvas canvas)2098     protected void onDraw(Canvas canvas) {
2099         mProvider.getViewDelegate().onDraw(canvas);
2100     }
2101 
2102     @Override
performLongClick()2103     public boolean performLongClick() {
2104         return mProvider.getViewDelegate().performLongClick();
2105     }
2106 
2107     @Override
onConfigurationChanged(Configuration newConfig)2108     protected void onConfigurationChanged(Configuration newConfig) {
2109         mProvider.getViewDelegate().onConfigurationChanged(newConfig);
2110     }
2111 
2112     @Override
onCreateInputConnection(EditorInfo outAttrs)2113     public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
2114         return mProvider.getViewDelegate().onCreateInputConnection(outAttrs);
2115     }
2116 
2117     @Override
onVisibilityChanged(View changedView, int visibility)2118     protected void onVisibilityChanged(View changedView, int visibility) {
2119         super.onVisibilityChanged(changedView, visibility);
2120         // This method may be called in the constructor chain, before the WebView provider is
2121         // created.
2122         ensureProviderCreated();
2123         mProvider.getViewDelegate().onVisibilityChanged(changedView, visibility);
2124     }
2125 
2126     @Override
onWindowFocusChanged(boolean hasWindowFocus)2127     public void onWindowFocusChanged(boolean hasWindowFocus) {
2128         mProvider.getViewDelegate().onWindowFocusChanged(hasWindowFocus);
2129         super.onWindowFocusChanged(hasWindowFocus);
2130     }
2131 
2132     @Override
onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect)2133     protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
2134         mProvider.getViewDelegate().onFocusChanged(focused, direction, previouslyFocusedRect);
2135         super.onFocusChanged(focused, direction, previouslyFocusedRect);
2136     }
2137 
2138     /** @hide */
2139     @Override
setFrame(int left, int top, int right, int bottom)2140     protected boolean setFrame(int left, int top, int right, int bottom) {
2141         return mProvider.getViewDelegate().setFrame(left, top, right, bottom);
2142     }
2143 
2144     @Override
onSizeChanged(int w, int h, int ow, int oh)2145     protected void onSizeChanged(int w, int h, int ow, int oh) {
2146         super.onSizeChanged(w, h, ow, oh);
2147         mProvider.getViewDelegate().onSizeChanged(w, h, ow, oh);
2148     }
2149 
2150     @Override
onScrollChanged(int l, int t, int oldl, int oldt)2151     protected void onScrollChanged(int l, int t, int oldl, int oldt) {
2152         super.onScrollChanged(l, t, oldl, oldt);
2153         mProvider.getViewDelegate().onScrollChanged(l, t, oldl, oldt);
2154     }
2155 
2156     @Override
dispatchKeyEvent(KeyEvent event)2157     public boolean dispatchKeyEvent(KeyEvent event) {
2158         return mProvider.getViewDelegate().dispatchKeyEvent(event);
2159     }
2160 
2161     @Override
requestFocus(int direction, Rect previouslyFocusedRect)2162     public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
2163         return mProvider.getViewDelegate().requestFocus(direction, previouslyFocusedRect);
2164     }
2165 
2166     @Deprecated
2167     @Override
onMeasure(int widthMeasureSpec, int heightMeasureSpec)2168     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
2169         super.onMeasure(widthMeasureSpec, heightMeasureSpec);
2170         mProvider.getViewDelegate().onMeasure(widthMeasureSpec, heightMeasureSpec);
2171     }
2172 
2173     @Override
requestChildRectangleOnScreen(View child, Rect rect, boolean immediate)2174     public boolean requestChildRectangleOnScreen(View child, Rect rect, boolean immediate) {
2175         return mProvider.getViewDelegate().requestChildRectangleOnScreen(child, rect, immediate);
2176     }
2177 
2178     @Override
setBackgroundColor(int color)2179     public void setBackgroundColor(int color) {
2180         mProvider.getViewDelegate().setBackgroundColor(color);
2181     }
2182 
2183     @Override
setLayerType(int layerType, Paint paint)2184     public void setLayerType(int layerType, Paint paint) {
2185         super.setLayerType(layerType, paint);
2186         mProvider.getViewDelegate().setLayerType(layerType, paint);
2187     }
2188 
2189     @Override
dispatchDraw(Canvas canvas)2190     protected void dispatchDraw(Canvas canvas) {
2191         mProvider.getViewDelegate().preDispatchDraw(canvas);
2192         super.dispatchDraw(canvas);
2193     }
2194 }
2195