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