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