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