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