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