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