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