WebView.java revision e5b7c95b8a247e9962710dca127c56a78d4faca5
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.webkit; 18 19import android.annotation.Widget; 20import android.content.Context; 21import android.content.res.Configuration; 22import android.graphics.Bitmap; 23import android.graphics.Canvas; 24import android.graphics.Paint; 25import android.graphics.Picture; 26import android.graphics.Rect; 27import android.graphics.drawable.Drawable; 28import android.net.Uri; 29import android.net.http.SslCertificate; 30import android.os.Build; 31import android.os.Bundle; 32import android.os.Looper; 33import android.os.Message; 34import android.os.StrictMode; 35import android.print.PrintDocumentAdapter; 36import android.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 volatile 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 defStyleAttr an attribute in the current theme that contains a 453 * reference to a style resource that supplies default values for 454 * the view. Can be 0 to not look for defaults. 455 */ 456 public WebView(Context context, AttributeSet attrs, int defStyleAttr) { 457 this(context, attrs, defStyleAttr, 0); 458 } 459 460 /** 461 * Constructs a new WebView with layout parameters and a default style. 462 * 463 * @param context a Context object used to access application assets 464 * @param attrs an AttributeSet passed to our parent 465 * @param defStyleAttr an attribute in the current theme that contains a 466 * reference to a style resource that supplies default values for 467 * the view. Can be 0 to not look for defaults. 468 * @param defStyleRes a resource identifier of a style resource that 469 * supplies default values for the view, used only if 470 * defStyleAttr is 0 or can not be found in the theme. Can be 0 471 * to not look for defaults. 472 */ 473 public WebView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { 474 this(context, attrs, defStyleAttr, defStyleRes, null, false); 475 } 476 477 /** 478 * Constructs a new WebView with layout parameters and a default style. 479 * 480 * @param context a Context object used to access application assets 481 * @param attrs an AttributeSet passed to our parent 482 * @param defStyleAttr an attribute in the current theme that contains a 483 * reference to a style resource that supplies default values for 484 * the view. Can be 0 to not look for defaults. 485 * @param privateBrowsing whether this WebView will be initialized in 486 * private mode 487 * 488 * @deprecated Private browsing is no longer supported directly via 489 * WebView and will be removed in a future release. Prefer using 490 * {@link WebSettings}, {@link WebViewDatabase}, {@link CookieManager} 491 * and {@link WebStorage} for fine-grained control of privacy data. 492 */ 493 @Deprecated 494 public WebView(Context context, AttributeSet attrs, int defStyleAttr, 495 boolean privateBrowsing) { 496 this(context, attrs, defStyleAttr, 0, null, privateBrowsing); 497 } 498 499 /** 500 * Constructs a new WebView with layout parameters, a default style and a set 501 * of custom Javscript interfaces to be added to this WebView at initialization 502 * time. This guarantees that these interfaces will be available when the JS 503 * context is initialized. 504 * 505 * @param context a Context object used to access application assets 506 * @param attrs an AttributeSet passed to our parent 507 * @param defStyleAttr an attribute in the current theme that contains a 508 * reference to a style resource that supplies default values for 509 * the view. Can be 0 to not look for defaults. 510 * @param javaScriptInterfaces a Map of interface names, as keys, and 511 * object implementing those interfaces, as 512 * values 513 * @param privateBrowsing whether this WebView will be initialized in 514 * private mode 515 * @hide This is used internally by dumprendertree, as it requires the javaScript interfaces to 516 * be added synchronously, before a subsequent loadUrl call takes effect. 517 */ 518 protected WebView(Context context, AttributeSet attrs, int defStyleAttr, 519 Map<String, Object> javaScriptInterfaces, boolean privateBrowsing) { 520 this(context, attrs, defStyleAttr, 0, javaScriptInterfaces, privateBrowsing); 521 } 522 523 /** 524 * @hide 525 */ 526 @SuppressWarnings("deprecation") // for super() call into deprecated base class constructor. 527 protected WebView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes, 528 Map<String, Object> javaScriptInterfaces, boolean privateBrowsing) { 529 super(context, attrs, defStyleAttr, defStyleRes); 530 if (context == null) { 531 throw new IllegalArgumentException("Invalid context argument"); 532 } 533 sEnforceThreadChecking = context.getApplicationInfo().targetSdkVersion >= 534 Build.VERSION_CODES.JELLY_BEAN_MR2; 535 checkThread(); 536 if (DebugFlags.TRACE_API) Log.d(LOGTAG, "WebView<init>"); 537 538 ensureProviderCreated(); 539 mProvider.init(javaScriptInterfaces, privateBrowsing); 540 // Post condition of creating a webview is the CookieSyncManager.getInstance() is allowed. 541 CookieSyncManager.setGetInstanceIsAllowed(); 542 } 543 544 /** 545 * Specifies whether the horizontal scrollbar has overlay style. 546 * 547 * @param overlay true if horizontal scrollbar should have overlay style 548 */ 549 public void setHorizontalScrollbarOverlay(boolean overlay) { 550 checkThread(); 551 if (DebugFlags.TRACE_API) Log.d(LOGTAG, "setHorizontalScrollbarOverlay=" + overlay); 552 mProvider.setHorizontalScrollbarOverlay(overlay); 553 } 554 555 /** 556 * Specifies whether the vertical scrollbar has overlay style. 557 * 558 * @param overlay true if vertical scrollbar should have overlay style 559 */ 560 public void setVerticalScrollbarOverlay(boolean overlay) { 561 checkThread(); 562 if (DebugFlags.TRACE_API) Log.d(LOGTAG, "setVerticalScrollbarOverlay=" + overlay); 563 mProvider.setVerticalScrollbarOverlay(overlay); 564 } 565 566 /** 567 * Gets whether horizontal scrollbar has overlay style. 568 * 569 * @return true if horizontal scrollbar has overlay style 570 */ 571 public boolean overlayHorizontalScrollbar() { 572 checkThread(); 573 return mProvider.overlayHorizontalScrollbar(); 574 } 575 576 /** 577 * Gets whether vertical scrollbar has overlay style. 578 * 579 * @return true if vertical scrollbar has overlay style 580 */ 581 public boolean overlayVerticalScrollbar() { 582 checkThread(); 583 return mProvider.overlayVerticalScrollbar(); 584 } 585 586 /** 587 * Gets the visible height (in pixels) of the embedded title bar (if any). 588 * 589 * @deprecated This method is now obsolete. 590 * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1} 591 */ 592 public int getVisibleTitleHeight() { 593 checkThread(); 594 return mProvider.getVisibleTitleHeight(); 595 } 596 597 /** 598 * Gets the SSL certificate for the main top-level page or null if there is 599 * no certificate (the site is not secure). 600 * 601 * @return the SSL certificate for the main top-level page 602 */ 603 public SslCertificate getCertificate() { 604 checkThread(); 605 return mProvider.getCertificate(); 606 } 607 608 /** 609 * Sets the SSL certificate for the main top-level page. 610 * 611 * @deprecated Calling this function has no useful effect, and will be 612 * ignored in future releases. 613 */ 614 @Deprecated 615 public void setCertificate(SslCertificate certificate) { 616 checkThread(); 617 if (DebugFlags.TRACE_API) Log.d(LOGTAG, "setCertificate=" + certificate); 618 mProvider.setCertificate(certificate); 619 } 620 621 //------------------------------------------------------------------------- 622 // Methods called by activity 623 //------------------------------------------------------------------------- 624 625 /** 626 * Sets a username and password pair for the specified host. This data is 627 * used by the Webview to autocomplete username and password fields in web 628 * forms. Note that this is unrelated to the credentials used for HTTP 629 * authentication. 630 * 631 * @param host the host that required the credentials 632 * @param username the username for the given host 633 * @param password the password for the given host 634 * @see WebViewDatabase#clearUsernamePassword 635 * @see WebViewDatabase#hasUsernamePassword 636 * @deprecated Saving passwords in WebView will not be supported in future versions. 637 */ 638 @Deprecated 639 public void savePassword(String host, String username, String password) { 640 checkThread(); 641 if (DebugFlags.TRACE_API) Log.d(LOGTAG, "savePassword=" + host); 642 mProvider.savePassword(host, username, password); 643 } 644 645 /** 646 * Stores HTTP authentication credentials for a given host and realm. This 647 * method is intended to be used with 648 * {@link WebViewClient#onReceivedHttpAuthRequest}. 649 * 650 * @param host the host to which the credentials apply 651 * @param realm the realm to which the credentials apply 652 * @param username the username 653 * @param password the password 654 * @see #getHttpAuthUsernamePassword 655 * @see WebViewDatabase#hasHttpAuthUsernamePassword 656 * @see WebViewDatabase#clearHttpAuthUsernamePassword 657 */ 658 public void setHttpAuthUsernamePassword(String host, String realm, 659 String username, String password) { 660 checkThread(); 661 if (DebugFlags.TRACE_API) Log.d(LOGTAG, "setHttpAuthUsernamePassword=" + host); 662 mProvider.setHttpAuthUsernamePassword(host, realm, username, password); 663 } 664 665 /** 666 * Retrieves HTTP authentication credentials for a given host and realm. 667 * This method is intended to be used with 668 * {@link WebViewClient#onReceivedHttpAuthRequest}. 669 * 670 * @param host the host to which the credentials apply 671 * @param realm the realm to which the credentials apply 672 * @return the credentials as a String array, if found. The first element 673 * is the username and the second element is the password. Null if 674 * no credentials are found. 675 * @see #setHttpAuthUsernamePassword 676 * @see WebViewDatabase#hasHttpAuthUsernamePassword 677 * @see WebViewDatabase#clearHttpAuthUsernamePassword 678 */ 679 public String[] getHttpAuthUsernamePassword(String host, String realm) { 680 checkThread(); 681 return mProvider.getHttpAuthUsernamePassword(host, realm); 682 } 683 684 /** 685 * Destroys the internal state of this WebView. This method should be called 686 * after this WebView has been removed from the view system. No other 687 * methods may be called on this WebView after destroy. 688 */ 689 public void destroy() { 690 checkThread(); 691 if (DebugFlags.TRACE_API) Log.d(LOGTAG, "destroy"); 692 mProvider.destroy(); 693 } 694 695 /** 696 * Enables platform notifications of data state and proxy changes. 697 * Notifications are enabled by default. 698 * 699 * @deprecated This method is now obsolete. 700 * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1} 701 */ 702 @Deprecated 703 public static void enablePlatformNotifications() { 704 getFactory().getStatics().setPlatformNotificationsEnabled(true); 705 } 706 707 /** 708 * Disables platform notifications of data state and proxy changes. 709 * Notifications are enabled by default. 710 * 711 * @deprecated This method is now obsolete. 712 * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1} 713 */ 714 @Deprecated 715 public static void disablePlatformNotifications() { 716 getFactory().getStatics().setPlatformNotificationsEnabled(false); 717 } 718 719 /** 720 * Used only by internal tests to free up memory. 721 * 722 * @hide 723 */ 724 public static void freeMemoryForTests() { 725 getFactory().getStatics().freeMemoryForTests(); 726 } 727 728 /** 729 * Informs WebView of the network state. This is used to set 730 * the JavaScript property window.navigator.isOnline and 731 * generates the online/offline event as specified in HTML5, sec. 5.7.7 732 * 733 * @param networkUp a boolean indicating if network is available 734 */ 735 public void setNetworkAvailable(boolean networkUp) { 736 checkThread(); 737 if (DebugFlags.TRACE_API) Log.d(LOGTAG, "setNetworkAvailable=" + networkUp); 738 mProvider.setNetworkAvailable(networkUp); 739 } 740 741 /** 742 * Saves the state of this WebView used in 743 * {@link android.app.Activity#onSaveInstanceState}. Please note that this 744 * method no longer stores the display data for this WebView. The previous 745 * behavior could potentially leak files if {@link #restoreState} was never 746 * called. 747 * 748 * @param outState the Bundle to store this WebView's state 749 * @return the same copy of the back/forward list used to save the state. If 750 * saveState fails, the returned list will be null. 751 */ 752 public WebBackForwardList saveState(Bundle outState) { 753 checkThread(); 754 if (DebugFlags.TRACE_API) Log.d(LOGTAG, "saveState"); 755 return mProvider.saveState(outState); 756 } 757 758 /** 759 * Saves the current display data to the Bundle given. Used in conjunction 760 * with {@link #saveState}. 761 * @param b a Bundle to store the display data 762 * @param dest the file to store the serialized picture data. Will be 763 * overwritten with this WebView's picture data. 764 * @return true if the picture was successfully saved 765 * @deprecated This method is now obsolete. 766 * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1} 767 */ 768 @Deprecated 769 public boolean savePicture(Bundle b, final File dest) { 770 checkThread(); 771 if (DebugFlags.TRACE_API) Log.d(LOGTAG, "savePicture=" + dest.getName()); 772 return mProvider.savePicture(b, dest); 773 } 774 775 /** 776 * Restores the display data that was saved in {@link #savePicture}. Used in 777 * conjunction with {@link #restoreState}. Note that this will not work if 778 * this WebView is hardware accelerated. 779 * 780 * @param b a Bundle containing the saved display data 781 * @param src the file where the picture data was stored 782 * @return true if the picture was successfully restored 783 * @deprecated This method is now obsolete. 784 * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1} 785 */ 786 @Deprecated 787 public boolean restorePicture(Bundle b, File src) { 788 checkThread(); 789 if (DebugFlags.TRACE_API) Log.d(LOGTAG, "restorePicture=" + src.getName()); 790 return mProvider.restorePicture(b, src); 791 } 792 793 /** 794 * Restores the state of this WebView from the given Bundle. This method is 795 * intended for use in {@link android.app.Activity#onRestoreInstanceState} 796 * and should be called to restore the state of this WebView. If 797 * it is called after this WebView has had a chance to build state (load 798 * pages, create a back/forward list, etc.) there may be undesirable 799 * side-effects. Please note that this method no longer restores the 800 * display data for this WebView. 801 * 802 * @param inState the incoming Bundle of state 803 * @return the restored back/forward list or null if restoreState failed 804 */ 805 public WebBackForwardList restoreState(Bundle inState) { 806 checkThread(); 807 if (DebugFlags.TRACE_API) Log.d(LOGTAG, "restoreState"); 808 return mProvider.restoreState(inState); 809 } 810 811 /** 812 * Loads the given URL with the specified additional HTTP headers. 813 * 814 * @param url the URL of the resource to load 815 * @param additionalHttpHeaders the additional headers to be used in the 816 * HTTP request for this URL, specified as a map from name to 817 * value. Note that if this map contains any of the headers 818 * that are set by default by this WebView, such as those 819 * controlling caching, accept types or the User-Agent, their 820 * values may be overriden by this WebView's defaults. 821 */ 822 public void loadUrl(String url, Map<String, String> additionalHttpHeaders) { 823 checkThread(); 824 if (DebugFlags.TRACE_API) { 825 StringBuilder headers = new StringBuilder(); 826 if (additionalHttpHeaders != null) { 827 for (Map.Entry<String, String> entry : additionalHttpHeaders.entrySet()) { 828 headers.append(entry.getKey() + ":" + entry.getValue() + "\n"); 829 } 830 } 831 Log.d(LOGTAG, "loadUrl(extra headers)=" + url + "\n" + headers); 832 } 833 mProvider.loadUrl(url, additionalHttpHeaders); 834 } 835 836 /** 837 * Loads the given URL. 838 * 839 * @param url the URL of the resource to load 840 */ 841 public void loadUrl(String url) { 842 checkThread(); 843 if (DebugFlags.TRACE_API) Log.d(LOGTAG, "loadUrl=" + url); 844 mProvider.loadUrl(url); 845 } 846 847 /** 848 * Loads the URL with postData using "POST" method into this WebView. If url 849 * is not a network URL, it will be loaded with {@link #loadUrl(String)} 850 * instead, ignoring the postData param. 851 * 852 * @param url the URL of the resource to load 853 * @param postData the data will be passed to "POST" request, which must be 854 * be "application/x-www-form-urlencoded" encoded. 855 */ 856 public void postUrl(String url, byte[] postData) { 857 checkThread(); 858 if (DebugFlags.TRACE_API) Log.d(LOGTAG, "postUrl=" + url); 859 if (URLUtil.isNetworkUrl(url)) { 860 mProvider.postUrl(url, postData); 861 } else { 862 mProvider.loadUrl(url); 863 } 864 } 865 866 /** 867 * Loads the given data into this WebView using a 'data' scheme URL. 868 * <p> 869 * Note that JavaScript's same origin policy means that script running in a 870 * page loaded using this method will be unable to access content loaded 871 * using any scheme other than 'data', including 'http(s)'. To avoid this 872 * restriction, use {@link 873 * #loadDataWithBaseURL(String,String,String,String,String) 874 * loadDataWithBaseURL()} with an appropriate base URL. 875 * <p> 876 * The encoding parameter specifies whether the data is base64 or URL 877 * encoded. If the data is base64 encoded, the value of the encoding 878 * parameter must be 'base64'. For all other values of the parameter, 879 * including null, it is assumed that the data uses ASCII encoding for 880 * octets inside the range of safe URL characters and use the standard %xx 881 * hex encoding of URLs for octets outside that range. For example, '#', 882 * '%', '\', '?' should be replaced by %23, %25, %27, %3f respectively. 883 * <p> 884 * The 'data' scheme URL formed by this method uses the default US-ASCII 885 * charset. If you need need to set a different charset, you should form a 886 * 'data' scheme URL which explicitly specifies a charset parameter in the 887 * mediatype portion of the URL and call {@link #loadUrl(String)} instead. 888 * Note that the charset obtained from the mediatype portion of a data URL 889 * always overrides that specified in the HTML or XML document itself. 890 * 891 * @param data a String of data in the given encoding 892 * @param mimeType the MIME type of the data, e.g. 'text/html' 893 * @param encoding the encoding of the data 894 */ 895 public void loadData(String data, String mimeType, String encoding) { 896 checkThread(); 897 if (DebugFlags.TRACE_API) Log.d(LOGTAG, "loadData"); 898 mProvider.loadData(data, mimeType, encoding); 899 } 900 901 /** 902 * Loads the given data into this WebView, using baseUrl as the base URL for 903 * the content. The base URL is used both to resolve relative URLs and when 904 * applying JavaScript's same origin policy. The historyUrl is used for the 905 * history entry. 906 * <p> 907 * Note that content specified in this way can access local device files 908 * (via 'file' scheme URLs) only if baseUrl specifies a scheme other than 909 * 'http', 'https', 'ftp', 'ftps', 'about' or 'javascript'. 910 * <p> 911 * If the base URL uses the data scheme, this method is equivalent to 912 * calling {@link #loadData(String,String,String) loadData()} and the 913 * historyUrl is ignored, and the data will be treated as part of a data: URL. 914 * If the base URL uses any other scheme, then the data will be loaded into 915 * the WebView as a plain string (i.e. not part of a data URL) and any URL-encoded 916 * entities in the string will not be decoded. 917 * 918 * @param baseUrl the URL to use as the page's base URL. If null defaults to 919 * 'about:blank'. 920 * @param data a String of data in the given encoding 921 * @param mimeType the MIMEType of the data, e.g. 'text/html'. If null, 922 * defaults to 'text/html'. 923 * @param encoding the encoding of the data 924 * @param historyUrl the URL to use as the history entry. If null defaults 925 * to 'about:blank'. If non-null, this must be a valid URL. 926 */ 927 public void loadDataWithBaseURL(String baseUrl, String data, 928 String mimeType, String encoding, String historyUrl) { 929 checkThread(); 930 if (DebugFlags.TRACE_API) Log.d(LOGTAG, "loadDataWithBaseURL=" + baseUrl); 931 mProvider.loadDataWithBaseURL(baseUrl, data, mimeType, encoding, historyUrl); 932 } 933 934 /** 935 * Asynchronously evaluates JavaScript in the context of the currently displayed page. 936 * If non-null, |resultCallback| will be invoked with any result returned from that 937 * execution. This method must be called on the UI thread and the callback will 938 * be made on the UI thread. 939 * 940 * @param script the JavaScript to execute. 941 * @param resultCallback A callback to be invoked when the script execution 942 * completes with the result of the execution (if any). 943 * May be null if no notificaion of the result is required. 944 */ 945 public void evaluateJavascript(String script, ValueCallback<String> resultCallback) { 946 checkThread(); 947 if (DebugFlags.TRACE_API) Log.d(LOGTAG, "evaluateJavascript=" + script); 948 mProvider.evaluateJavaScript(script, resultCallback); 949 } 950 951 /** 952 * Saves the current view as a web archive. 953 * 954 * @param filename the filename where the archive should be placed 955 */ 956 public void saveWebArchive(String filename) { 957 checkThread(); 958 if (DebugFlags.TRACE_API) Log.d(LOGTAG, "saveWebArchive=" + filename); 959 mProvider.saveWebArchive(filename); 960 } 961 962 /** 963 * Saves the current view as a web archive. 964 * 965 * @param basename the filename where the archive should be placed 966 * @param autoname if false, takes basename to be a file. If true, basename 967 * is assumed to be a directory in which a filename will be 968 * chosen according to the URL of the current page. 969 * @param callback called after the web archive has been saved. The 970 * parameter for onReceiveValue will either be the filename 971 * under which the file was saved, or null if saving the 972 * file failed. 973 */ 974 public void saveWebArchive(String basename, boolean autoname, ValueCallback<String> callback) { 975 checkThread(); 976 if (DebugFlags.TRACE_API) Log.d(LOGTAG, "saveWebArchive(auto)=" + basename); 977 mProvider.saveWebArchive(basename, autoname, callback); 978 } 979 980 /** 981 * Stops the current load. 982 */ 983 public void stopLoading() { 984 checkThread(); 985 if (DebugFlags.TRACE_API) Log.d(LOGTAG, "stopLoading"); 986 mProvider.stopLoading(); 987 } 988 989 /** 990 * Reloads the current URL. 991 */ 992 public void reload() { 993 checkThread(); 994 if (DebugFlags.TRACE_API) Log.d(LOGTAG, "reload"); 995 mProvider.reload(); 996 } 997 998 /** 999 * Gets whether this WebView has a back history item. 1000 * 1001 * @return true iff this WebView has a back history item 1002 */ 1003 public boolean canGoBack() { 1004 checkThread(); 1005 return mProvider.canGoBack(); 1006 } 1007 1008 /** 1009 * Goes back in the history of this WebView. 1010 */ 1011 public void goBack() { 1012 checkThread(); 1013 if (DebugFlags.TRACE_API) Log.d(LOGTAG, "goBack"); 1014 mProvider.goBack(); 1015 } 1016 1017 /** 1018 * Gets whether this WebView has a forward history item. 1019 * 1020 * @return true iff this Webview has a forward history item 1021 */ 1022 public boolean canGoForward() { 1023 checkThread(); 1024 return mProvider.canGoForward(); 1025 } 1026 1027 /** 1028 * Goes forward in the history of this WebView. 1029 */ 1030 public void goForward() { 1031 checkThread(); 1032 if (DebugFlags.TRACE_API) Log.d(LOGTAG, "goForward"); 1033 mProvider.goForward(); 1034 } 1035 1036 /** 1037 * Gets whether the page can go back or forward the given 1038 * number of steps. 1039 * 1040 * @param steps the negative or positive number of steps to move the 1041 * history 1042 */ 1043 public boolean canGoBackOrForward(int steps) { 1044 checkThread(); 1045 return mProvider.canGoBackOrForward(steps); 1046 } 1047 1048 /** 1049 * Goes to the history item that is the number of steps away from 1050 * the current item. Steps is negative if backward and positive 1051 * if forward. 1052 * 1053 * @param steps the number of steps to take back or forward in the back 1054 * forward list 1055 */ 1056 public void goBackOrForward(int steps) { 1057 checkThread(); 1058 if (DebugFlags.TRACE_API) Log.d(LOGTAG, "goBackOrForwad=" + steps); 1059 mProvider.goBackOrForward(steps); 1060 } 1061 1062 /** 1063 * Gets whether private browsing is enabled in this WebView. 1064 */ 1065 public boolean isPrivateBrowsingEnabled() { 1066 checkThread(); 1067 return mProvider.isPrivateBrowsingEnabled(); 1068 } 1069 1070 /** 1071 * Scrolls the contents of this WebView up by half the view size. 1072 * 1073 * @param top true to jump to the top of the page 1074 * @return true if the page was scrolled 1075 */ 1076 public boolean pageUp(boolean top) { 1077 checkThread(); 1078 if (DebugFlags.TRACE_API) Log.d(LOGTAG, "pageUp"); 1079 return mProvider.pageUp(top); 1080 } 1081 1082 /** 1083 * Scrolls the contents of this WebView down by half the page size. 1084 * 1085 * @param bottom true to jump to bottom of page 1086 * @return true if the page was scrolled 1087 */ 1088 public boolean pageDown(boolean bottom) { 1089 checkThread(); 1090 if (DebugFlags.TRACE_API) Log.d(LOGTAG, "pageDown"); 1091 return mProvider.pageDown(bottom); 1092 } 1093 1094 /** 1095 * Clears this WebView so that onDraw() will draw nothing but white background, 1096 * and onMeasure() will return 0 if MeasureSpec is not MeasureSpec.EXACTLY. 1097 * @deprecated Use WebView.loadUrl("about:blank") to reliably reset the view state 1098 * and release page resources (including any running JavaScript). 1099 */ 1100 @Deprecated 1101 public void clearView() { 1102 checkThread(); 1103 if (DebugFlags.TRACE_API) Log.d(LOGTAG, "clearView"); 1104 mProvider.clearView(); 1105 } 1106 1107 /** 1108 * Gets a new picture that captures the current contents of this WebView. 1109 * The picture is of the entire document being displayed, and is not 1110 * limited to the area currently displayed by this WebView. Also, the 1111 * picture is a static copy and is unaffected by later changes to the 1112 * content being displayed. 1113 * <p> 1114 * Note that due to internal changes, for API levels between 1115 * {@link android.os.Build.VERSION_CODES#HONEYCOMB} and 1116 * {@link android.os.Build.VERSION_CODES#ICE_CREAM_SANDWICH} inclusive, the 1117 * picture does not include fixed position elements or scrollable divs. 1118 * <p> 1119 * Note that from {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1} the returned picture 1120 * should only be drawn into bitmap-backed Canvas - using any other type of Canvas will involve 1121 * additional conversion at a cost in memory and performance. Also the 1122 * {@link android.graphics.Picture#createFromStream} and 1123 * {@link android.graphics.Picture#writeToStream} methods are not supported on the 1124 * returned object. 1125 * 1126 * @deprecated Use {@link #onDraw} to obtain a bitmap snapshot of the WebView, or 1127 * {@link #saveWebArchive} to save the content to a file. 1128 * 1129 * @return a picture that captures the current contents of this WebView 1130 */ 1131 @Deprecated 1132 public Picture capturePicture() { 1133 checkThread(); 1134 if (DebugFlags.TRACE_API) Log.d(LOGTAG, "capturePicture"); 1135 return mProvider.capturePicture(); 1136 } 1137 1138 /** 1139 * Creates a PrintDocumentAdapter that provides the content of this Webview for printing. 1140 * Only supported for API levels 1141 * {@link android.os.Build.VERSION_CODES#KITKAT} and above. 1142 * 1143 * The adapter works by converting the Webview contents to a PDF stream. The Webview cannot 1144 * be drawn during the conversion process - any such draws are undefined. It is recommended 1145 * to use a dedicated off screen Webview for the printing. If necessary, an application may 1146 * temporarily hide a visible WebView by using a custom PrintDocumentAdapter instance 1147 * wrapped around the object returned and observing the onStart and onFinish methods. See 1148 * {@link android.print.PrintDocumentAdapter} for more information. 1149 */ 1150 public PrintDocumentAdapter createPrintDocumentAdapter() { 1151 checkThread(); 1152 if (DebugFlags.TRACE_API) Log.d(LOGTAG, "createPrintDocumentAdapter"); 1153 return mProvider.createPrintDocumentAdapter(); 1154 } 1155 1156 /** 1157 * Gets the current scale of this WebView. 1158 * 1159 * @return the current scale 1160 * 1161 * @deprecated This method is prone to inaccuracy due to race conditions 1162 * between the web rendering and UI threads; prefer 1163 * {@link WebViewClient#onScaleChanged}. 1164 */ 1165 @Deprecated 1166 @ViewDebug.ExportedProperty(category = "webview") 1167 public float getScale() { 1168 checkThread(); 1169 return mProvider.getScale(); 1170 } 1171 1172 /** 1173 * Sets the initial scale for this WebView. 0 means default. 1174 * The behavior for the default scale depends on the state of 1175 * {@link WebSettings#getUseWideViewPort()} and 1176 * {@link WebSettings#getLoadWithOverviewMode()}. 1177 * If the content fits into the WebView control by width, then 1178 * the zoom is set to 100%. For wide content, the behavor 1179 * depends on the state of {@link WebSettings#getLoadWithOverviewMode()}. 1180 * If its value is true, the content will be zoomed out to be fit 1181 * by width into the WebView control, otherwise not. 1182 * 1183 * If initial scale is greater than 0, WebView starts with this value 1184 * as initial scale. 1185 * Please note that unlike the scale properties in the viewport meta tag, 1186 * this method doesn't take the screen density into account. 1187 * 1188 * @param scaleInPercent the initial scale in percent 1189 */ 1190 public void setInitialScale(int scaleInPercent) { 1191 checkThread(); 1192 if (DebugFlags.TRACE_API) Log.d(LOGTAG, "setInitialScale=" + scaleInPercent); 1193 mProvider.setInitialScale(scaleInPercent); 1194 } 1195 1196 /** 1197 * Invokes the graphical zoom picker widget for this WebView. This will 1198 * result in the zoom widget appearing on the screen to control the zoom 1199 * level of this WebView. 1200 */ 1201 public void invokeZoomPicker() { 1202 checkThread(); 1203 if (DebugFlags.TRACE_API) Log.d(LOGTAG, "invokeZoomPicker"); 1204 mProvider.invokeZoomPicker(); 1205 } 1206 1207 /** 1208 * Gets a HitTestResult based on the current cursor node. If a HTML::a 1209 * tag is found and the anchor has a non-JavaScript URL, the HitTestResult 1210 * type is set to SRC_ANCHOR_TYPE and the URL is set in the "extra" field. 1211 * If the anchor does not have a URL or if it is a JavaScript URL, the type 1212 * will be UNKNOWN_TYPE and the URL has to be retrieved through 1213 * {@link #requestFocusNodeHref} asynchronously. If a HTML::img tag is 1214 * found, the HitTestResult type is set to IMAGE_TYPE and the URL is set in 1215 * the "extra" field. A type of 1216 * SRC_IMAGE_ANCHOR_TYPE indicates an anchor with a URL that has an image as 1217 * a child node. If a phone number is found, the HitTestResult type is set 1218 * to PHONE_TYPE and the phone number is set in the "extra" field of 1219 * HitTestResult. If a map address is found, the HitTestResult type is set 1220 * to GEO_TYPE and the address is set in the "extra" field of HitTestResult. 1221 * If an email address is found, the HitTestResult type is set to EMAIL_TYPE 1222 * and the email is set in the "extra" field of HitTestResult. Otherwise, 1223 * HitTestResult type is set to UNKNOWN_TYPE. 1224 */ 1225 public HitTestResult getHitTestResult() { 1226 checkThread(); 1227 if (DebugFlags.TRACE_API) Log.d(LOGTAG, "getHitTestResult"); 1228 return mProvider.getHitTestResult(); 1229 } 1230 1231 /** 1232 * Requests the anchor or image element URL at the last tapped point. 1233 * If hrefMsg is null, this method returns immediately and does not 1234 * dispatch hrefMsg to its target. If the tapped point hits an image, 1235 * an anchor, or an image in an anchor, the message associates 1236 * strings in named keys in its data. The value paired with the key 1237 * may be an empty string. 1238 * 1239 * @param hrefMsg the message to be dispatched with the result of the 1240 * request. The message data contains three keys. "url" 1241 * returns the anchor's href attribute. "title" returns the 1242 * anchor's text. "src" returns the image's src attribute. 1243 */ 1244 public void requestFocusNodeHref(Message hrefMsg) { 1245 checkThread(); 1246 if (DebugFlags.TRACE_API) Log.d(LOGTAG, "requestFocusNodeHref"); 1247 mProvider.requestFocusNodeHref(hrefMsg); 1248 } 1249 1250 /** 1251 * Requests the URL of the image last touched by the user. msg will be sent 1252 * to its target with a String representing the URL as its object. 1253 * 1254 * @param msg the message to be dispatched with the result of the request 1255 * as the data member with "url" as key. The result can be null. 1256 */ 1257 public void requestImageRef(Message msg) { 1258 checkThread(); 1259 if (DebugFlags.TRACE_API) Log.d(LOGTAG, "requestImageRef"); 1260 mProvider.requestImageRef(msg); 1261 } 1262 1263 /** 1264 * Gets the URL for the current page. This is not always the same as the URL 1265 * passed to WebViewClient.onPageStarted because although the load for 1266 * that URL has begun, the current page may not have changed. 1267 * 1268 * @return the URL for the current page 1269 */ 1270 @ViewDebug.ExportedProperty(category = "webview") 1271 public String getUrl() { 1272 checkThread(); 1273 return mProvider.getUrl(); 1274 } 1275 1276 /** 1277 * Gets the original URL for the current page. This is not always the same 1278 * as the URL passed to WebViewClient.onPageStarted because although the 1279 * load for that URL has begun, the current page may not have changed. 1280 * Also, there may have been redirects resulting in a different URL to that 1281 * originally requested. 1282 * 1283 * @return the URL that was originally requested for the current page 1284 */ 1285 @ViewDebug.ExportedProperty(category = "webview") 1286 public String getOriginalUrl() { 1287 checkThread(); 1288 return mProvider.getOriginalUrl(); 1289 } 1290 1291 /** 1292 * Gets the title for the current page. This is the title of the current page 1293 * until WebViewClient.onReceivedTitle is called. 1294 * 1295 * @return the title for the current page 1296 */ 1297 @ViewDebug.ExportedProperty(category = "webview") 1298 public String getTitle() { 1299 checkThread(); 1300 return mProvider.getTitle(); 1301 } 1302 1303 /** 1304 * Gets the favicon for the current page. This is the favicon of the current 1305 * page until WebViewClient.onReceivedIcon is called. 1306 * 1307 * @return the favicon for the current page 1308 */ 1309 public Bitmap getFavicon() { 1310 checkThread(); 1311 return mProvider.getFavicon(); 1312 } 1313 1314 /** 1315 * Gets the touch icon URL for the apple-touch-icon <link> element, or 1316 * a URL on this site's server pointing to the standard location of a 1317 * touch icon. 1318 * 1319 * @hide 1320 */ 1321 public String getTouchIconUrl() { 1322 return mProvider.getTouchIconUrl(); 1323 } 1324 1325 /** 1326 * Gets the progress for the current page. 1327 * 1328 * @return the progress for the current page between 0 and 100 1329 */ 1330 public int getProgress() { 1331 checkThread(); 1332 return mProvider.getProgress(); 1333 } 1334 1335 /** 1336 * Gets the height of the HTML content. 1337 * 1338 * @return the height of the HTML content 1339 */ 1340 @ViewDebug.ExportedProperty(category = "webview") 1341 public int getContentHeight() { 1342 checkThread(); 1343 return mProvider.getContentHeight(); 1344 } 1345 1346 /** 1347 * Gets the width of the HTML content. 1348 * 1349 * @return the width of the HTML content 1350 * @hide 1351 */ 1352 @ViewDebug.ExportedProperty(category = "webview") 1353 public int getContentWidth() { 1354 return mProvider.getContentWidth(); 1355 } 1356 1357 /** 1358 * Pauses all layout, parsing, and JavaScript timers for all WebViews. This 1359 * is a global requests, not restricted to just this WebView. This can be 1360 * useful if the application has been paused. 1361 */ 1362 public void pauseTimers() { 1363 checkThread(); 1364 if (DebugFlags.TRACE_API) Log.d(LOGTAG, "pauseTimers"); 1365 mProvider.pauseTimers(); 1366 } 1367 1368 /** 1369 * Resumes all layout, parsing, and JavaScript timers for all WebViews. 1370 * This will resume dispatching all timers. 1371 */ 1372 public void resumeTimers() { 1373 checkThread(); 1374 if (DebugFlags.TRACE_API) Log.d(LOGTAG, "resumeTimers"); 1375 mProvider.resumeTimers(); 1376 } 1377 1378 /** 1379 * Pauses any extra processing associated with this WebView and its 1380 * associated DOM, plugins, JavaScript etc. For example, if this WebView is 1381 * taken offscreen, this could be called to reduce unnecessary CPU or 1382 * network traffic. When this WebView is again "active", call onResume(). 1383 * Note that this differs from pauseTimers(), which affects all WebViews. 1384 */ 1385 public void onPause() { 1386 checkThread(); 1387 if (DebugFlags.TRACE_API) Log.d(LOGTAG, "onPause"); 1388 mProvider.onPause(); 1389 } 1390 1391 /** 1392 * Resumes a WebView after a previous call to onPause(). 1393 */ 1394 public void onResume() { 1395 checkThread(); 1396 if (DebugFlags.TRACE_API) Log.d(LOGTAG, "onResume"); 1397 mProvider.onResume(); 1398 } 1399 1400 /** 1401 * Gets whether this WebView is paused, meaning onPause() was called. 1402 * Calling onResume() sets the paused state back to false. 1403 * 1404 * @hide 1405 */ 1406 public boolean isPaused() { 1407 return mProvider.isPaused(); 1408 } 1409 1410 /** 1411 * Informs this WebView that memory is low so that it can free any available 1412 * memory. 1413 * @deprecated Memory caches are automatically dropped when no longer needed, and in response 1414 * to system memory pressure. 1415 */ 1416 @Deprecated 1417 public void freeMemory() { 1418 checkThread(); 1419 if (DebugFlags.TRACE_API) Log.d(LOGTAG, "freeMemory"); 1420 mProvider.freeMemory(); 1421 } 1422 1423 /** 1424 * Clears the resource cache. Note that the cache is per-application, so 1425 * this will clear the cache for all WebViews used. 1426 * 1427 * @param includeDiskFiles if false, only the RAM cache is cleared 1428 */ 1429 public void clearCache(boolean includeDiskFiles) { 1430 checkThread(); 1431 if (DebugFlags.TRACE_API) Log.d(LOGTAG, "clearCache"); 1432 mProvider.clearCache(includeDiskFiles); 1433 } 1434 1435 /** 1436 * Removes the autocomplete popup from the currently focused form field, if 1437 * present. Note this only affects the display of the autocomplete popup, 1438 * it does not remove any saved form data from this WebView's store. To do 1439 * that, use {@link WebViewDatabase#clearFormData}. 1440 */ 1441 public void clearFormData() { 1442 checkThread(); 1443 if (DebugFlags.TRACE_API) Log.d(LOGTAG, "clearFormData"); 1444 mProvider.clearFormData(); 1445 } 1446 1447 /** 1448 * Tells this WebView to clear its internal back/forward list. 1449 */ 1450 public void clearHistory() { 1451 checkThread(); 1452 if (DebugFlags.TRACE_API) Log.d(LOGTAG, "clearHistory"); 1453 mProvider.clearHistory(); 1454 } 1455 1456 /** 1457 * Clears the SSL preferences table stored in response to proceeding with 1458 * SSL certificate errors. 1459 */ 1460 public void clearSslPreferences() { 1461 checkThread(); 1462 if (DebugFlags.TRACE_API) Log.d(LOGTAG, "clearSslPreferences"); 1463 mProvider.clearSslPreferences(); 1464 } 1465 1466 /** 1467 * Gets the WebBackForwardList for this WebView. This contains the 1468 * back/forward list for use in querying each item in the history stack. 1469 * This is a copy of the private WebBackForwardList so it contains only a 1470 * snapshot of the current state. Multiple calls to this method may return 1471 * different objects. The object returned from this method will not be 1472 * updated to reflect any new state. 1473 */ 1474 public WebBackForwardList copyBackForwardList() { 1475 checkThread(); 1476 return mProvider.copyBackForwardList(); 1477 1478 } 1479 1480 /** 1481 * Registers the listener to be notified as find-on-page operations 1482 * progress. This will replace the current listener. 1483 * 1484 * @param listener an implementation of {@link FindListener} 1485 */ 1486 public void setFindListener(FindListener listener) { 1487 checkThread(); 1488 setupFindListenerIfNeeded(); 1489 mFindListener.mUserFindListener = listener; 1490 } 1491 1492 /** 1493 * Highlights and scrolls to the next match found by 1494 * {@link #findAllAsync}, wrapping around page boundaries as necessary. 1495 * Notifies any registered {@link FindListener}. If {@link #findAllAsync(String)} 1496 * has not been called yet, or if {@link #clearMatches} has been called since the 1497 * last find operation, this function does nothing. 1498 * 1499 * @param forward the direction to search 1500 * @see #setFindListener 1501 */ 1502 public void findNext(boolean forward) { 1503 checkThread(); 1504 if (DebugFlags.TRACE_API) Log.d(LOGTAG, "findNext"); 1505 mProvider.findNext(forward); 1506 } 1507 1508 /** 1509 * Finds all instances of find on the page and highlights them. 1510 * Notifies any registered {@link FindListener}. 1511 * 1512 * @param find the string to find 1513 * @return the number of occurances of the String "find" that were found 1514 * @deprecated {@link #findAllAsync} is preferred. 1515 * @see #setFindListener 1516 */ 1517 @Deprecated 1518 public int findAll(String find) { 1519 checkThread(); 1520 if (DebugFlags.TRACE_API) Log.d(LOGTAG, "findAll"); 1521 StrictMode.noteSlowCall("findAll blocks UI: prefer findAllAsync"); 1522 return mProvider.findAll(find); 1523 } 1524 1525 /** 1526 * Finds all instances of find on the page and highlights them, 1527 * asynchronously. Notifies any registered {@link FindListener}. 1528 * Successive calls to this will cancel any pending searches. 1529 * 1530 * @param find the string to find. 1531 * @see #setFindListener 1532 */ 1533 public void findAllAsync(String find) { 1534 checkThread(); 1535 if (DebugFlags.TRACE_API) Log.d(LOGTAG, "findAllAsync"); 1536 mProvider.findAllAsync(find); 1537 } 1538 1539 /** 1540 * Starts an ActionMode for finding text in this WebView. Only works if this 1541 * WebView is attached to the view system. 1542 * 1543 * @param text if non-null, will be the initial text to search for. 1544 * Otherwise, the last String searched for in this WebView will 1545 * be used to start. 1546 * @param showIme if true, show the IME, assuming the user will begin typing. 1547 * If false and text is non-null, perform a find all. 1548 * @return true if the find dialog is shown, false otherwise 1549 * @deprecated This method does not work reliably on all Android versions; 1550 * implementing a custom find dialog using WebView.findAllAsync() 1551 * provides a more robust solution. 1552 */ 1553 @Deprecated 1554 public boolean showFindDialog(String text, boolean showIme) { 1555 checkThread(); 1556 if (DebugFlags.TRACE_API) Log.d(LOGTAG, "showFindDialog"); 1557 return mProvider.showFindDialog(text, showIme); 1558 } 1559 1560 /** 1561 * Gets the first substring consisting of the address of a physical 1562 * location. Currently, only addresses in the United States are detected, 1563 * and consist of: 1564 * <ul> 1565 * <li>a house number</li> 1566 * <li>a street name</li> 1567 * <li>a street type (Road, Circle, etc), either spelled out or 1568 * abbreviated</li> 1569 * <li>a city name</li> 1570 * <li>a state or territory, either spelled out or two-letter abbr</li> 1571 * <li>an optional 5 digit or 9 digit zip code</li> 1572 * </ul> 1573 * All names must be correctly capitalized, and the zip code, if present, 1574 * must be valid for the state. The street type must be a standard USPS 1575 * spelling or abbreviation. The state or territory must also be spelled 1576 * or abbreviated using USPS standards. The house number may not exceed 1577 * five digits. 1578 * 1579 * @param addr the string to search for addresses 1580 * @return the address, or if no address is found, null 1581 */ 1582 public static String findAddress(String addr) { 1583 return getFactory().getStatics().findAddress(addr); 1584 } 1585 1586 /** 1587 * Clears the highlighting surrounding text matches created by 1588 * {@link #findAllAsync}. 1589 */ 1590 public void clearMatches() { 1591 checkThread(); 1592 if (DebugFlags.TRACE_API) Log.d(LOGTAG, "clearMatches"); 1593 mProvider.clearMatches(); 1594 } 1595 1596 /** 1597 * Queries the document to see if it contains any image references. The 1598 * message object will be dispatched with arg1 being set to 1 if images 1599 * were found and 0 if the document does not reference any images. 1600 * 1601 * @param response the message that will be dispatched with the result 1602 */ 1603 public void documentHasImages(Message response) { 1604 checkThread(); 1605 mProvider.documentHasImages(response); 1606 } 1607 1608 /** 1609 * Sets the WebViewClient that will receive various notifications and 1610 * requests. This will replace the current handler. 1611 * 1612 * @param client an implementation of WebViewClient 1613 */ 1614 public void setWebViewClient(WebViewClient client) { 1615 checkThread(); 1616 mProvider.setWebViewClient(client); 1617 } 1618 1619 /** 1620 * Registers the interface to be used when content can not be handled by 1621 * the rendering engine, and should be downloaded instead. This will replace 1622 * the current handler. 1623 * 1624 * @param listener an implementation of DownloadListener 1625 */ 1626 public void setDownloadListener(DownloadListener listener) { 1627 checkThread(); 1628 mProvider.setDownloadListener(listener); 1629 } 1630 1631 /** 1632 * Sets the chrome handler. This is an implementation of WebChromeClient for 1633 * use in handling JavaScript dialogs, favicons, titles, and the progress. 1634 * This will replace the current handler. 1635 * 1636 * @param client an implementation of WebChromeClient 1637 */ 1638 public void setWebChromeClient(WebChromeClient client) { 1639 checkThread(); 1640 mProvider.setWebChromeClient(client); 1641 } 1642 1643 /** 1644 * Preauthorize the given origin to access resources. 1645 * This authorization only valid for this WebView instance life cycle and 1646 * will not retained. 1647 * 1648 * @param origin the origin authorized to access resources 1649 * @param resources the resource authorized to be accessed by origin. 1650 * 1651 * @hide 1652 */ 1653 public void preauthorizePermission(Uri origin, long resources) { 1654 checkThread(); 1655 mProvider.preauthorizePermission(origin, resources); 1656 } 1657 1658 /** 1659 * Sets the Picture listener. This is an interface used to receive 1660 * notifications of a new Picture. 1661 * 1662 * @param listener an implementation of WebView.PictureListener 1663 * @deprecated This method is now obsolete. 1664 */ 1665 @Deprecated 1666 public void setPictureListener(PictureListener listener) { 1667 checkThread(); 1668 if (DebugFlags.TRACE_API) Log.d(LOGTAG, "setPictureListener=" + listener); 1669 mProvider.setPictureListener(listener); 1670 } 1671 1672 /** 1673 * Injects the supplied Java object into this WebView. The object is 1674 * injected into the JavaScript context of the main frame, using the 1675 * supplied name. This allows the Java object's methods to be 1676 * accessed from JavaScript. For applications targeted to API 1677 * level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1} 1678 * and above, only public methods that are annotated with 1679 * {@link android.webkit.JavascriptInterface} can be accessed from JavaScript. 1680 * For applications targeted to API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN} or below, 1681 * all public methods (including the inherited ones) can be accessed, see the 1682 * important security note below for implications. 1683 * <p> Note that injected objects will not 1684 * appear in JavaScript until the page is next (re)loaded. For example: 1685 * <pre> 1686 * class JsObject { 1687 * {@literal @}JavascriptInterface 1688 * public String toString() { return "injectedObject"; } 1689 * } 1690 * webView.addJavascriptInterface(new JsObject(), "injectedObject"); 1691 * webView.loadData("<!DOCTYPE html><title></title>", "text/html", null); 1692 * webView.loadUrl("javascript:alert(injectedObject.toString())");</pre> 1693 * <p> 1694 * <strong>IMPORTANT:</strong> 1695 * <ul> 1696 * <li> This method can be used to allow JavaScript to control the host 1697 * application. This is a powerful feature, but also presents a security 1698 * risk for applications targeted to API level 1699 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} or below, because 1700 * JavaScript could use reflection to access an 1701 * injected object's public fields. Use of this method in a WebView 1702 * containing untrusted content could allow an attacker to manipulate the 1703 * host application in unintended ways, executing Java code with the 1704 * permissions of the host application. Use extreme care when using this 1705 * method in a WebView which could contain untrusted content.</li> 1706 * <li> JavaScript interacts with Java object on a private, background 1707 * thread of this WebView. Care is therefore required to maintain thread 1708 * safety.</li> 1709 * <li> The Java object's fields are not accessible.</li> 1710 * <li> For applications targeted to API level {@link android.os.Build.VERSION_CODES#L} 1711 * and above, methods of injected Java objects are enumerable from 1712 * JavaScript.</li> 1713 * </ul> 1714 * 1715 * @param object the Java object to inject into this WebView's JavaScript 1716 * context. Null values are ignored. 1717 * @param name the name used to expose the object in JavaScript 1718 */ 1719 public void addJavascriptInterface(Object object, String name) { 1720 checkThread(); 1721 if (DebugFlags.TRACE_API) Log.d(LOGTAG, "addJavascriptInterface=" + name); 1722 mProvider.addJavascriptInterface(object, name); 1723 } 1724 1725 /** 1726 * Removes a previously injected Java object from this WebView. Note that 1727 * the removal will not be reflected in JavaScript until the page is next 1728 * (re)loaded. See {@link #addJavascriptInterface}. 1729 * 1730 * @param name the name used to expose the object in JavaScript 1731 */ 1732 public void removeJavascriptInterface(String name) { 1733 checkThread(); 1734 if (DebugFlags.TRACE_API) Log.d(LOGTAG, "removeJavascriptInterface=" + name); 1735 mProvider.removeJavascriptInterface(name); 1736 } 1737 1738 /** 1739 * Gets the WebSettings object used to control the settings for this 1740 * WebView. 1741 * 1742 * @return a WebSettings object that can be used to control this WebView's 1743 * settings 1744 */ 1745 public WebSettings getSettings() { 1746 checkThread(); 1747 return mProvider.getSettings(); 1748 } 1749 1750 /** 1751 * Enables debugging of web contents (HTML / CSS / JavaScript) 1752 * loaded into any WebViews of this application. This flag can be enabled 1753 * in order to facilitate debugging of web layouts and JavaScript 1754 * code running inside WebViews. Please refer to WebView documentation 1755 * for the debugging guide. 1756 * 1757 * The default is false. 1758 * 1759 * @param enabled whether to enable web contents debugging 1760 */ 1761 public static void setWebContentsDebuggingEnabled(boolean enabled) { 1762 getFactory().getStatics().setWebContentsDebuggingEnabled(enabled); 1763 } 1764 1765 /** 1766 * Gets the list of currently loaded plugins. 1767 * 1768 * @return the list of currently loaded plugins 1769 * @deprecated This was used for Gears, which has been deprecated. 1770 * @hide 1771 */ 1772 @Deprecated 1773 public static synchronized PluginList getPluginList() { 1774 return new PluginList(); 1775 } 1776 1777 /** 1778 * @deprecated This was used for Gears, which has been deprecated. 1779 * @hide 1780 */ 1781 @Deprecated 1782 public void refreshPlugins(boolean reloadOpenPages) { 1783 checkThread(); 1784 } 1785 1786 /** 1787 * Puts this WebView into text selection mode. Do not rely on this 1788 * functionality; it will be deprecated in the future. 1789 * 1790 * @deprecated This method is now obsolete. 1791 * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1} 1792 */ 1793 @Deprecated 1794 public void emulateShiftHeld() { 1795 checkThread(); 1796 } 1797 1798 /** 1799 * @deprecated WebView no longer needs to implement 1800 * ViewGroup.OnHierarchyChangeListener. This method does nothing now. 1801 */ 1802 @Override 1803 // Cannot add @hide as this can always be accessed via the interface. 1804 @Deprecated 1805 public void onChildViewAdded(View parent, View child) {} 1806 1807 /** 1808 * @deprecated WebView no longer needs to implement 1809 * ViewGroup.OnHierarchyChangeListener. This method does nothing now. 1810 */ 1811 @Override 1812 // Cannot add @hide as this can always be accessed via the interface. 1813 @Deprecated 1814 public void onChildViewRemoved(View p, View child) {} 1815 1816 /** 1817 * @deprecated WebView should not have implemented 1818 * ViewTreeObserver.OnGlobalFocusChangeListener. This method does nothing now. 1819 */ 1820 @Override 1821 // Cannot add @hide as this can always be accessed via the interface. 1822 @Deprecated 1823 public void onGlobalFocusChanged(View oldFocus, View newFocus) { 1824 } 1825 1826 /** 1827 * @deprecated Only the default case, true, will be supported in a future version. 1828 */ 1829 @Deprecated 1830 public void setMapTrackballToArrowKeys(boolean setMap) { 1831 checkThread(); 1832 mProvider.setMapTrackballToArrowKeys(setMap); 1833 } 1834 1835 1836 public void flingScroll(int vx, int vy) { 1837 checkThread(); 1838 if (DebugFlags.TRACE_API) Log.d(LOGTAG, "flingScroll"); 1839 mProvider.flingScroll(vx, vy); 1840 } 1841 1842 /** 1843 * Gets the zoom controls for this WebView, as a separate View. The caller 1844 * is responsible for inserting this View into the layout hierarchy. 1845 * <p/> 1846 * API level {@link android.os.Build.VERSION_CODES#CUPCAKE} introduced 1847 * built-in zoom mechanisms for the WebView, as opposed to these separate 1848 * zoom controls. The built-in mechanisms are preferred and can be enabled 1849 * using {@link WebSettings#setBuiltInZoomControls}. 1850 * 1851 * @deprecated the built-in zoom mechanisms are preferred 1852 * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN} 1853 */ 1854 @Deprecated 1855 public View getZoomControls() { 1856 checkThread(); 1857 return mProvider.getZoomControls(); 1858 } 1859 1860 /** 1861 * Gets whether this WebView can be zoomed in. 1862 * 1863 * @return true if this WebView can be zoomed in 1864 * 1865 * @deprecated This method is prone to inaccuracy due to race conditions 1866 * between the web rendering and UI threads; prefer 1867 * {@link WebViewClient#onScaleChanged}. 1868 */ 1869 @Deprecated 1870 public boolean canZoomIn() { 1871 checkThread(); 1872 return mProvider.canZoomIn(); 1873 } 1874 1875 /** 1876 * Gets whether this WebView can be zoomed out. 1877 * 1878 * @return true if this WebView can be zoomed out 1879 * 1880 * @deprecated This method is prone to inaccuracy due to race conditions 1881 * between the web rendering and UI threads; prefer 1882 * {@link WebViewClient#onScaleChanged}. 1883 */ 1884 @Deprecated 1885 public boolean canZoomOut() { 1886 checkThread(); 1887 return mProvider.canZoomOut(); 1888 } 1889 1890 /** 1891 * Performs zoom in in this WebView. 1892 * 1893 * @return true if zoom in succeeds, false if no zoom changes 1894 */ 1895 public boolean zoomIn() { 1896 checkThread(); 1897 return mProvider.zoomIn(); 1898 } 1899 1900 /** 1901 * Performs zoom out in this WebView. 1902 * 1903 * @return true if zoom out succeeds, false if no zoom changes 1904 */ 1905 public boolean zoomOut() { 1906 checkThread(); 1907 return mProvider.zoomOut(); 1908 } 1909 1910 /** 1911 * @deprecated This method is now obsolete. 1912 * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1} 1913 */ 1914 @Deprecated 1915 public void debugDump() { 1916 checkThread(); 1917 } 1918 1919 /** 1920 * See {@link ViewDebug.HierarchyHandler#dumpViewHierarchyWithProperties(BufferedWriter, int)} 1921 * @hide 1922 */ 1923 @Override 1924 public void dumpViewHierarchyWithProperties(BufferedWriter out, int level) { 1925 mProvider.dumpViewHierarchyWithProperties(out, level); 1926 } 1927 1928 /** 1929 * See {@link ViewDebug.HierarchyHandler#findHierarchyView(String, int)} 1930 * @hide 1931 */ 1932 @Override 1933 public View findHierarchyView(String className, int hashCode) { 1934 return mProvider.findHierarchyView(className, hashCode); 1935 } 1936 1937 //------------------------------------------------------------------------- 1938 // Interface for WebView providers 1939 //------------------------------------------------------------------------- 1940 1941 /** 1942 * Gets the WebViewProvider. Used by providers to obtain the underlying 1943 * implementation, e.g. when the appliction responds to 1944 * WebViewClient.onCreateWindow() request. 1945 * 1946 * @hide WebViewProvider is not public API. 1947 */ 1948 public WebViewProvider getWebViewProvider() { 1949 return mProvider; 1950 } 1951 1952 /** 1953 * Callback interface, allows the provider implementation to access non-public methods 1954 * and fields, and make super-class calls in this WebView instance. 1955 * @hide Only for use by WebViewProvider implementations 1956 */ 1957 public class PrivateAccess { 1958 // ---- Access to super-class methods ---- 1959 public int super_getScrollBarStyle() { 1960 return WebView.super.getScrollBarStyle(); 1961 } 1962 1963 public void super_scrollTo(int scrollX, int scrollY) { 1964 WebView.super.scrollTo(scrollX, scrollY); 1965 } 1966 1967 public void super_computeScroll() { 1968 WebView.super.computeScroll(); 1969 } 1970 1971 public boolean super_onHoverEvent(MotionEvent event) { 1972 return WebView.super.onHoverEvent(event); 1973 } 1974 1975 public boolean super_performAccessibilityAction(int action, Bundle arguments) { 1976 return WebView.super.performAccessibilityAction(action, arguments); 1977 } 1978 1979 public boolean super_performLongClick() { 1980 return WebView.super.performLongClick(); 1981 } 1982 1983 public boolean super_setFrame(int left, int top, int right, int bottom) { 1984 return WebView.super.setFrame(left, top, right, bottom); 1985 } 1986 1987 public boolean super_dispatchKeyEvent(KeyEvent event) { 1988 return WebView.super.dispatchKeyEvent(event); 1989 } 1990 1991 public boolean super_onGenericMotionEvent(MotionEvent event) { 1992 return WebView.super.onGenericMotionEvent(event); 1993 } 1994 1995 public boolean super_requestFocus(int direction, Rect previouslyFocusedRect) { 1996 return WebView.super.requestFocus(direction, previouslyFocusedRect); 1997 } 1998 1999 public void super_setLayoutParams(ViewGroup.LayoutParams params) { 2000 WebView.super.setLayoutParams(params); 2001 } 2002 2003 // ---- Access to non-public methods ---- 2004 public void overScrollBy(int deltaX, int deltaY, 2005 int scrollX, int scrollY, 2006 int scrollRangeX, int scrollRangeY, 2007 int maxOverScrollX, int maxOverScrollY, 2008 boolean isTouchEvent) { 2009 WebView.this.overScrollBy(deltaX, deltaY, scrollX, scrollY, scrollRangeX, scrollRangeY, 2010 maxOverScrollX, maxOverScrollY, isTouchEvent); 2011 } 2012 2013 public void awakenScrollBars(int duration) { 2014 WebView.this.awakenScrollBars(duration); 2015 } 2016 2017 public void awakenScrollBars(int duration, boolean invalidate) { 2018 WebView.this.awakenScrollBars(duration, invalidate); 2019 } 2020 2021 public float getVerticalScrollFactor() { 2022 return WebView.this.getVerticalScrollFactor(); 2023 } 2024 2025 public float getHorizontalScrollFactor() { 2026 return WebView.this.getHorizontalScrollFactor(); 2027 } 2028 2029 public void setMeasuredDimension(int measuredWidth, int measuredHeight) { 2030 WebView.this.setMeasuredDimension(measuredWidth, measuredHeight); 2031 } 2032 2033 public void onScrollChanged(int l, int t, int oldl, int oldt) { 2034 WebView.this.onScrollChanged(l, t, oldl, oldt); 2035 } 2036 2037 public int getHorizontalScrollbarHeight() { 2038 return WebView.this.getHorizontalScrollbarHeight(); 2039 } 2040 2041 public void super_onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 2042 int l, int t, int r, int b) { 2043 WebView.super.onDrawVerticalScrollBar(canvas, scrollBar, l, t, r, b); 2044 } 2045 2046 // ---- Access to (non-public) fields ---- 2047 /** Raw setter for the scroll X value, without invoking onScrollChanged handlers etc. */ 2048 public void setScrollXRaw(int scrollX) { 2049 WebView.this.mScrollX = scrollX; 2050 } 2051 2052 /** Raw setter for the scroll Y value, without invoking onScrollChanged handlers etc. */ 2053 public void setScrollYRaw(int scrollY) { 2054 WebView.this.mScrollY = scrollY; 2055 } 2056 2057 } 2058 2059 //------------------------------------------------------------------------- 2060 // Package-private internal stuff 2061 //------------------------------------------------------------------------- 2062 2063 // Only used by android.webkit.FindActionModeCallback. 2064 void setFindDialogFindListener(FindListener listener) { 2065 checkThread(); 2066 setupFindListenerIfNeeded(); 2067 mFindListener.mFindDialogFindListener = listener; 2068 } 2069 2070 // Only used by android.webkit.FindActionModeCallback. 2071 void notifyFindDialogDismissed() { 2072 checkThread(); 2073 mProvider.notifyFindDialogDismissed(); 2074 } 2075 2076 //------------------------------------------------------------------------- 2077 // Private internal stuff 2078 //------------------------------------------------------------------------- 2079 2080 private WebViewProvider mProvider; 2081 2082 /** 2083 * In addition to the FindListener that the user may set via the WebView.setFindListener 2084 * API, FindActionModeCallback will register it's own FindListener. We keep them separate 2085 * via this class so that that the two FindListeners can potentially exist at once. 2086 */ 2087 private class FindListenerDistributor implements FindListener { 2088 private FindListener mFindDialogFindListener; 2089 private FindListener mUserFindListener; 2090 2091 @Override 2092 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, 2093 boolean isDoneCounting) { 2094 if (mFindDialogFindListener != null) { 2095 mFindDialogFindListener.onFindResultReceived(activeMatchOrdinal, numberOfMatches, 2096 isDoneCounting); 2097 } 2098 2099 if (mUserFindListener != null) { 2100 mUserFindListener.onFindResultReceived(activeMatchOrdinal, numberOfMatches, 2101 isDoneCounting); 2102 } 2103 } 2104 } 2105 private FindListenerDistributor mFindListener; 2106 2107 private void setupFindListenerIfNeeded() { 2108 if (mFindListener == null) { 2109 mFindListener = new FindListenerDistributor(); 2110 mProvider.setFindListener(mFindListener); 2111 } 2112 } 2113 2114 private void ensureProviderCreated() { 2115 checkThread(); 2116 if (mProvider == null) { 2117 // As this can get called during the base class constructor chain, pass the minimum 2118 // number of dependencies here; the rest are deferred to init(). 2119 mProvider = getFactory().createWebView(this, new PrivateAccess()); 2120 } 2121 } 2122 2123 private static synchronized WebViewFactoryProvider getFactory() { 2124 return WebViewFactory.getProvider(); 2125 } 2126 2127 private final Looper mWebViewThread = Looper.myLooper(); 2128 2129 private void checkThread() { 2130 // Ignore mWebViewThread == null because this can be called during in the super class 2131 // constructor, before this class's own constructor has even started. 2132 if (mWebViewThread != null && Looper.myLooper() != mWebViewThread) { 2133 Throwable throwable = new Throwable( 2134 "A WebView method was called on thread '" + 2135 Thread.currentThread().getName() + "'. " + 2136 "All WebView methods must be called on the same thread. " + 2137 "(Expected Looper " + mWebViewThread + " called on " + Looper.myLooper() + 2138 ", FYI main Looper is " + Looper.getMainLooper() + ")"); 2139 Log.w(LOGTAG, Log.getStackTraceString(throwable)); 2140 StrictMode.onWebViewMethodCalledOnWrongThread(throwable); 2141 2142 if (sEnforceThreadChecking) { 2143 throw new RuntimeException(throwable); 2144 } 2145 } 2146 } 2147 2148 //------------------------------------------------------------------------- 2149 // Override View methods 2150 //------------------------------------------------------------------------- 2151 2152 // TODO: Add a test that enumerates all methods in ViewDelegte & ScrollDelegate, and ensures 2153 // there's a corresponding override (or better, caller) for each of them in here. 2154 2155 @Override 2156 protected void onAttachedToWindow() { 2157 super.onAttachedToWindow(); 2158 mProvider.getViewDelegate().onAttachedToWindow(); 2159 } 2160 2161 /** @hide */ 2162 @Override 2163 protected void onDetachedFromWindowInternal() { 2164 mProvider.getViewDelegate().onDetachedFromWindow(); 2165 super.onDetachedFromWindowInternal(); 2166 } 2167 2168 @Override 2169 public void setLayoutParams(ViewGroup.LayoutParams params) { 2170 mProvider.getViewDelegate().setLayoutParams(params); 2171 } 2172 2173 @Override 2174 public void setOverScrollMode(int mode) { 2175 super.setOverScrollMode(mode); 2176 // This method may be called in the constructor chain, before the WebView provider is 2177 // created. 2178 ensureProviderCreated(); 2179 mProvider.getViewDelegate().setOverScrollMode(mode); 2180 } 2181 2182 @Override 2183 public void setScrollBarStyle(int style) { 2184 mProvider.getViewDelegate().setScrollBarStyle(style); 2185 super.setScrollBarStyle(style); 2186 } 2187 2188 @Override 2189 protected int computeHorizontalScrollRange() { 2190 return mProvider.getScrollDelegate().computeHorizontalScrollRange(); 2191 } 2192 2193 @Override 2194 protected int computeHorizontalScrollOffset() { 2195 return mProvider.getScrollDelegate().computeHorizontalScrollOffset(); 2196 } 2197 2198 @Override 2199 protected int computeVerticalScrollRange() { 2200 return mProvider.getScrollDelegate().computeVerticalScrollRange(); 2201 } 2202 2203 @Override 2204 protected int computeVerticalScrollOffset() { 2205 return mProvider.getScrollDelegate().computeVerticalScrollOffset(); 2206 } 2207 2208 @Override 2209 protected int computeVerticalScrollExtent() { 2210 return mProvider.getScrollDelegate().computeVerticalScrollExtent(); 2211 } 2212 2213 @Override 2214 public void computeScroll() { 2215 mProvider.getScrollDelegate().computeScroll(); 2216 } 2217 2218 @Override 2219 public boolean onHoverEvent(MotionEvent event) { 2220 return mProvider.getViewDelegate().onHoverEvent(event); 2221 } 2222 2223 @Override 2224 public boolean onTouchEvent(MotionEvent event) { 2225 return mProvider.getViewDelegate().onTouchEvent(event); 2226 } 2227 2228 @Override 2229 public boolean onGenericMotionEvent(MotionEvent event) { 2230 return mProvider.getViewDelegate().onGenericMotionEvent(event); 2231 } 2232 2233 @Override 2234 public boolean onTrackballEvent(MotionEvent event) { 2235 return mProvider.getViewDelegate().onTrackballEvent(event); 2236 } 2237 2238 @Override 2239 public boolean onKeyDown(int keyCode, KeyEvent event) { 2240 return mProvider.getViewDelegate().onKeyDown(keyCode, event); 2241 } 2242 2243 @Override 2244 public boolean onKeyUp(int keyCode, KeyEvent event) { 2245 return mProvider.getViewDelegate().onKeyUp(keyCode, event); 2246 } 2247 2248 @Override 2249 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 2250 return mProvider.getViewDelegate().onKeyMultiple(keyCode, repeatCount, event); 2251 } 2252 2253 /* 2254 TODO: These are not currently implemented in WebViewClassic, but it seems inconsistent not 2255 to be delegating them too. 2256 2257 @Override 2258 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 2259 return mProvider.getViewDelegate().onKeyPreIme(keyCode, event); 2260 } 2261 @Override 2262 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 2263 return mProvider.getViewDelegate().onKeyLongPress(keyCode, event); 2264 } 2265 @Override 2266 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 2267 return mProvider.getViewDelegate().onKeyShortcut(keyCode, event); 2268 } 2269 */ 2270 2271 @Override 2272 public AccessibilityNodeProvider getAccessibilityNodeProvider() { 2273 AccessibilityNodeProvider provider = 2274 mProvider.getViewDelegate().getAccessibilityNodeProvider(); 2275 return provider == null ? super.getAccessibilityNodeProvider() : provider; 2276 } 2277 2278 @Deprecated 2279 @Override 2280 public boolean shouldDelayChildPressedState() { 2281 return mProvider.getViewDelegate().shouldDelayChildPressedState(); 2282 } 2283 2284 @Override 2285 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 2286 super.onInitializeAccessibilityNodeInfo(info); 2287 info.setClassName(WebView.class.getName()); 2288 mProvider.getViewDelegate().onInitializeAccessibilityNodeInfo(info); 2289 } 2290 2291 @Override 2292 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 2293 super.onInitializeAccessibilityEvent(event); 2294 event.setClassName(WebView.class.getName()); 2295 mProvider.getViewDelegate().onInitializeAccessibilityEvent(event); 2296 } 2297 2298 @Override 2299 public boolean performAccessibilityAction(int action, Bundle arguments) { 2300 return mProvider.getViewDelegate().performAccessibilityAction(action, arguments); 2301 } 2302 2303 /** @hide */ 2304 @Override 2305 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 2306 int l, int t, int r, int b) { 2307 mProvider.getViewDelegate().onDrawVerticalScrollBar(canvas, scrollBar, l, t, r, b); 2308 } 2309 2310 @Override 2311 protected void onOverScrolled(int scrollX, int scrollY, boolean clampedX, boolean clampedY) { 2312 mProvider.getViewDelegate().onOverScrolled(scrollX, scrollY, clampedX, clampedY); 2313 } 2314 2315 @Override 2316 protected void onWindowVisibilityChanged(int visibility) { 2317 super.onWindowVisibilityChanged(visibility); 2318 mProvider.getViewDelegate().onWindowVisibilityChanged(visibility); 2319 } 2320 2321 @Override 2322 protected void onDraw(Canvas canvas) { 2323 mProvider.getViewDelegate().onDraw(canvas); 2324 } 2325 2326 @Override 2327 public boolean performLongClick() { 2328 return mProvider.getViewDelegate().performLongClick(); 2329 } 2330 2331 @Override 2332 protected void onConfigurationChanged(Configuration newConfig) { 2333 mProvider.getViewDelegate().onConfigurationChanged(newConfig); 2334 } 2335 2336 @Override 2337 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 2338 return mProvider.getViewDelegate().onCreateInputConnection(outAttrs); 2339 } 2340 2341 @Override 2342 protected void onVisibilityChanged(View changedView, int visibility) { 2343 super.onVisibilityChanged(changedView, visibility); 2344 // This method may be called in the constructor chain, before the WebView provider is 2345 // created. 2346 ensureProviderCreated(); 2347 mProvider.getViewDelegate().onVisibilityChanged(changedView, visibility); 2348 } 2349 2350 @Override 2351 public void onWindowFocusChanged(boolean hasWindowFocus) { 2352 mProvider.getViewDelegate().onWindowFocusChanged(hasWindowFocus); 2353 super.onWindowFocusChanged(hasWindowFocus); 2354 } 2355 2356 @Override 2357 protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) { 2358 mProvider.getViewDelegate().onFocusChanged(focused, direction, previouslyFocusedRect); 2359 super.onFocusChanged(focused, direction, previouslyFocusedRect); 2360 } 2361 2362 /** @hide */ 2363 @Override 2364 protected boolean setFrame(int left, int top, int right, int bottom) { 2365 return mProvider.getViewDelegate().setFrame(left, top, right, bottom); 2366 } 2367 2368 @Override 2369 protected void onSizeChanged(int w, int h, int ow, int oh) { 2370 super.onSizeChanged(w, h, ow, oh); 2371 mProvider.getViewDelegate().onSizeChanged(w, h, ow, oh); 2372 } 2373 2374 @Override 2375 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 2376 super.onScrollChanged(l, t, oldl, oldt); 2377 mProvider.getViewDelegate().onScrollChanged(l, t, oldl, oldt); 2378 } 2379 2380 @Override 2381 public boolean dispatchKeyEvent(KeyEvent event) { 2382 return mProvider.getViewDelegate().dispatchKeyEvent(event); 2383 } 2384 2385 @Override 2386 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 2387 return mProvider.getViewDelegate().requestFocus(direction, previouslyFocusedRect); 2388 } 2389 2390 @Override 2391 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 2392 super.onMeasure(widthMeasureSpec, heightMeasureSpec); 2393 mProvider.getViewDelegate().onMeasure(widthMeasureSpec, heightMeasureSpec); 2394 } 2395 2396 @Override 2397 public boolean requestChildRectangleOnScreen(View child, Rect rect, boolean immediate) { 2398 return mProvider.getViewDelegate().requestChildRectangleOnScreen(child, rect, immediate); 2399 } 2400 2401 @Override 2402 public void setBackgroundColor(int color) { 2403 mProvider.getViewDelegate().setBackgroundColor(color); 2404 } 2405 2406 @Override 2407 public void setLayerType(int layerType, Paint paint) { 2408 super.setLayerType(layerType, paint); 2409 mProvider.getViewDelegate().setLayerType(layerType, paint); 2410 } 2411 2412 @Override 2413 protected void dispatchDraw(Canvas canvas) { 2414 mProvider.getViewDelegate().preDispatchDraw(canvas); 2415 super.dispatchDraw(canvas); 2416 } 2417} 2418