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