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