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