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