WebView.java revision a83f1e3d230300fc49aea0fb49f9f1f6bf628764
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 table 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 client certificate 1493 * preferences are global for all Webviews. 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 * Clears the highlighting surrounding text matches created by 1628 * {@link #findAllAsync}. 1629 */ 1630 public void clearMatches() { 1631 checkThread(); 1632 if (DebugFlags.TRACE_API) Log.d(LOGTAG, "clearMatches"); 1633 mProvider.clearMatches(); 1634 } 1635 1636 /** 1637 * Queries the document to see if it contains any image references. The 1638 * message object will be dispatched with arg1 being set to 1 if images 1639 * were found and 0 if the document does not reference any images. 1640 * 1641 * @param response the message that will be dispatched with the result 1642 */ 1643 public void documentHasImages(Message response) { 1644 checkThread(); 1645 mProvider.documentHasImages(response); 1646 } 1647 1648 /** 1649 * Sets the WebViewClient that will receive various notifications and 1650 * requests. This will replace the current handler. 1651 * 1652 * @param client an implementation of WebViewClient 1653 */ 1654 public void setWebViewClient(WebViewClient client) { 1655 checkThread(); 1656 mProvider.setWebViewClient(client); 1657 } 1658 1659 /** 1660 * Registers the interface to be used when content can not be handled by 1661 * the rendering engine, and should be downloaded instead. This will replace 1662 * the current handler. 1663 * 1664 * @param listener an implementation of DownloadListener 1665 */ 1666 public void setDownloadListener(DownloadListener listener) { 1667 checkThread(); 1668 mProvider.setDownloadListener(listener); 1669 } 1670 1671 /** 1672 * Sets the chrome handler. This is an implementation of WebChromeClient for 1673 * use in handling JavaScript dialogs, favicons, titles, and the progress. 1674 * This will replace the current handler. 1675 * 1676 * @param client an implementation of WebChromeClient 1677 */ 1678 public void setWebChromeClient(WebChromeClient client) { 1679 checkThread(); 1680 mProvider.setWebChromeClient(client); 1681 } 1682 1683 /** 1684 * Preauthorize the given origin to access resources. 1685 * This authorization only valid for this WebView instance life cycle and 1686 * will not retained. 1687 * 1688 * @param origin the origin authorized to access resources 1689 * @param resources the resource authorized to be accessed by origin. 1690 * 1691 * @hide 1692 */ 1693 public void preauthorizePermission(Uri origin, long resources) { 1694 checkThread(); 1695 mProvider.preauthorizePermission(origin, resources); 1696 } 1697 1698 /** 1699 * Sets the Picture listener. This is an interface used to receive 1700 * notifications of a new Picture. 1701 * 1702 * @param listener an implementation of WebView.PictureListener 1703 * @deprecated This method is now obsolete. 1704 */ 1705 @Deprecated 1706 public void setPictureListener(PictureListener listener) { 1707 checkThread(); 1708 if (DebugFlags.TRACE_API) Log.d(LOGTAG, "setPictureListener=" + listener); 1709 mProvider.setPictureListener(listener); 1710 } 1711 1712 /** 1713 * Injects the supplied Java object into this WebView. The object is 1714 * injected into the JavaScript context of the main frame, using the 1715 * supplied name. This allows the Java object's methods to be 1716 * accessed from JavaScript. For applications targeted to API 1717 * level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1} 1718 * and above, only public methods that are annotated with 1719 * {@link android.webkit.JavascriptInterface} can be accessed from JavaScript. 1720 * For applications targeted to API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN} or below, 1721 * all public methods (including the inherited ones) can be accessed, see the 1722 * important security note below for implications. 1723 * <p> Note that injected objects will not 1724 * appear in JavaScript until the page is next (re)loaded. For example: 1725 * <pre> 1726 * class JsObject { 1727 * {@literal @}JavascriptInterface 1728 * public String toString() { return "injectedObject"; } 1729 * } 1730 * webView.addJavascriptInterface(new JsObject(), "injectedObject"); 1731 * webView.loadData("<!DOCTYPE html><title></title>", "text/html", null); 1732 * webView.loadUrl("javascript:alert(injectedObject.toString())");</pre> 1733 * <p> 1734 * <strong>IMPORTANT:</strong> 1735 * <ul> 1736 * <li> This method can be used to allow JavaScript to control the host 1737 * application. This is a powerful feature, but also presents a security 1738 * risk for applications targeted to API level 1739 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} or below, because 1740 * JavaScript could use reflection to access an 1741 * injected object's public fields. Use of this method in a WebView 1742 * containing untrusted content could allow an attacker to manipulate the 1743 * host application in unintended ways, executing Java code with the 1744 * permissions of the host application. Use extreme care when using this 1745 * method in a WebView which could contain untrusted content.</li> 1746 * <li> JavaScript interacts with Java object on a private, background 1747 * thread of this WebView. Care is therefore required to maintain thread 1748 * safety.</li> 1749 * <li> The Java object's fields are not accessible.</li> 1750 * <li> For applications targeted to API level {@link android.os.Build.VERSION_CODES#L} 1751 * and above, methods of injected Java objects are enumerable from 1752 * JavaScript.</li> 1753 * </ul> 1754 * 1755 * @param object the Java object to inject into this WebView's JavaScript 1756 * context. Null values are ignored. 1757 * @param name the name used to expose the object in JavaScript 1758 */ 1759 public void addJavascriptInterface(Object object, String name) { 1760 checkThread(); 1761 if (DebugFlags.TRACE_API) Log.d(LOGTAG, "addJavascriptInterface=" + name); 1762 mProvider.addJavascriptInterface(object, name); 1763 } 1764 1765 /** 1766 * Removes a previously injected Java object from this WebView. Note that 1767 * the removal will not be reflected in JavaScript until the page is next 1768 * (re)loaded. See {@link #addJavascriptInterface}. 1769 * 1770 * @param name the name used to expose the object in JavaScript 1771 */ 1772 public void removeJavascriptInterface(String name) { 1773 checkThread(); 1774 if (DebugFlags.TRACE_API) Log.d(LOGTAG, "removeJavascriptInterface=" + name); 1775 mProvider.removeJavascriptInterface(name); 1776 } 1777 1778 /** 1779 * Gets the WebSettings object used to control the settings for this 1780 * WebView. 1781 * 1782 * @return a WebSettings object that can be used to control this WebView's 1783 * settings 1784 */ 1785 public WebSettings getSettings() { 1786 checkThread(); 1787 return mProvider.getSettings(); 1788 } 1789 1790 /** 1791 * Enables debugging of web contents (HTML / CSS / JavaScript) 1792 * loaded into any WebViews of this application. This flag can be enabled 1793 * in order to facilitate debugging of web layouts and JavaScript 1794 * code running inside WebViews. Please refer to WebView documentation 1795 * for the debugging guide. 1796 * 1797 * The default is false. 1798 * 1799 * @param enabled whether to enable web contents debugging 1800 */ 1801 public static void setWebContentsDebuggingEnabled(boolean enabled) { 1802 getFactory().getStatics().setWebContentsDebuggingEnabled(enabled); 1803 } 1804 1805 /** 1806 * Gets the list of currently loaded plugins. 1807 * 1808 * @return the list of currently loaded plugins 1809 * @deprecated This was used for Gears, which has been deprecated. 1810 * @hide 1811 */ 1812 @Deprecated 1813 public static synchronized PluginList getPluginList() { 1814 return new PluginList(); 1815 } 1816 1817 /** 1818 * @deprecated This was used for Gears, which has been deprecated. 1819 * @hide 1820 */ 1821 @Deprecated 1822 public void refreshPlugins(boolean reloadOpenPages) { 1823 checkThread(); 1824 } 1825 1826 /** 1827 * Puts this WebView into text selection mode. Do not rely on this 1828 * functionality; it will be deprecated in the future. 1829 * 1830 * @deprecated This method is now obsolete. 1831 * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1} 1832 */ 1833 @Deprecated 1834 public void emulateShiftHeld() { 1835 checkThread(); 1836 } 1837 1838 /** 1839 * @deprecated WebView no longer needs to implement 1840 * ViewGroup.OnHierarchyChangeListener. This method does nothing now. 1841 */ 1842 @Override 1843 // Cannot add @hide as this can always be accessed via the interface. 1844 @Deprecated 1845 public void onChildViewAdded(View parent, View child) {} 1846 1847 /** 1848 * @deprecated WebView no longer needs to implement 1849 * ViewGroup.OnHierarchyChangeListener. This method does nothing now. 1850 */ 1851 @Override 1852 // Cannot add @hide as this can always be accessed via the interface. 1853 @Deprecated 1854 public void onChildViewRemoved(View p, View child) {} 1855 1856 /** 1857 * @deprecated WebView should not have implemented 1858 * ViewTreeObserver.OnGlobalFocusChangeListener. This method does nothing now. 1859 */ 1860 @Override 1861 // Cannot add @hide as this can always be accessed via the interface. 1862 @Deprecated 1863 public void onGlobalFocusChanged(View oldFocus, View newFocus) { 1864 } 1865 1866 /** 1867 * @deprecated Only the default case, true, will be supported in a future version. 1868 */ 1869 @Deprecated 1870 public void setMapTrackballToArrowKeys(boolean setMap) { 1871 checkThread(); 1872 mProvider.setMapTrackballToArrowKeys(setMap); 1873 } 1874 1875 1876 public void flingScroll(int vx, int vy) { 1877 checkThread(); 1878 if (DebugFlags.TRACE_API) Log.d(LOGTAG, "flingScroll"); 1879 mProvider.flingScroll(vx, vy); 1880 } 1881 1882 /** 1883 * Gets the zoom controls for this WebView, as a separate View. The caller 1884 * is responsible for inserting this View into the layout hierarchy. 1885 * <p/> 1886 * API level {@link android.os.Build.VERSION_CODES#CUPCAKE} introduced 1887 * built-in zoom mechanisms for the WebView, as opposed to these separate 1888 * zoom controls. The built-in mechanisms are preferred and can be enabled 1889 * using {@link WebSettings#setBuiltInZoomControls}. 1890 * 1891 * @deprecated the built-in zoom mechanisms are preferred 1892 * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN} 1893 */ 1894 @Deprecated 1895 public View getZoomControls() { 1896 checkThread(); 1897 return mProvider.getZoomControls(); 1898 } 1899 1900 /** 1901 * Gets whether this WebView can be zoomed in. 1902 * 1903 * @return true if this WebView can be zoomed in 1904 * 1905 * @deprecated This method is prone to inaccuracy due to race conditions 1906 * between the web rendering and UI threads; prefer 1907 * {@link WebViewClient#onScaleChanged}. 1908 */ 1909 @Deprecated 1910 public boolean canZoomIn() { 1911 checkThread(); 1912 return mProvider.canZoomIn(); 1913 } 1914 1915 /** 1916 * Gets whether this WebView can be zoomed out. 1917 * 1918 * @return true if this WebView can be zoomed out 1919 * 1920 * @deprecated This method is prone to inaccuracy due to race conditions 1921 * between the web rendering and UI threads; prefer 1922 * {@link WebViewClient#onScaleChanged}. 1923 */ 1924 @Deprecated 1925 public boolean canZoomOut() { 1926 checkThread(); 1927 return mProvider.canZoomOut(); 1928 } 1929 1930 /** 1931 * Performs zoom in in this WebView. 1932 * 1933 * @return true if zoom in succeeds, false if no zoom changes 1934 */ 1935 public boolean zoomIn() { 1936 checkThread(); 1937 return mProvider.zoomIn(); 1938 } 1939 1940 /** 1941 * Performs zoom out in this WebView. 1942 * 1943 * @return true if zoom out succeeds, false if no zoom changes 1944 */ 1945 public boolean zoomOut() { 1946 checkThread(); 1947 return mProvider.zoomOut(); 1948 } 1949 1950 /** 1951 * @deprecated This method is now obsolete. 1952 * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1} 1953 */ 1954 @Deprecated 1955 public void debugDump() { 1956 checkThread(); 1957 } 1958 1959 /** 1960 * See {@link ViewDebug.HierarchyHandler#dumpViewHierarchyWithProperties(BufferedWriter, int)} 1961 * @hide 1962 */ 1963 @Override 1964 public void dumpViewHierarchyWithProperties(BufferedWriter out, int level) { 1965 mProvider.dumpViewHierarchyWithProperties(out, level); 1966 } 1967 1968 /** 1969 * See {@link ViewDebug.HierarchyHandler#findHierarchyView(String, int)} 1970 * @hide 1971 */ 1972 @Override 1973 public View findHierarchyView(String className, int hashCode) { 1974 return mProvider.findHierarchyView(className, hashCode); 1975 } 1976 1977 //------------------------------------------------------------------------- 1978 // Interface for WebView providers 1979 //------------------------------------------------------------------------- 1980 1981 /** 1982 * Gets the WebViewProvider. Used by providers to obtain the underlying 1983 * implementation, e.g. when the appliction responds to 1984 * WebViewClient.onCreateWindow() request. 1985 * 1986 * @hide WebViewProvider is not public API. 1987 */ 1988 public WebViewProvider getWebViewProvider() { 1989 return mProvider; 1990 } 1991 1992 /** 1993 * Callback interface, allows the provider implementation to access non-public methods 1994 * and fields, and make super-class calls in this WebView instance. 1995 * @hide Only for use by WebViewProvider implementations 1996 */ 1997 public class PrivateAccess { 1998 // ---- Access to super-class methods ---- 1999 public int super_getScrollBarStyle() { 2000 return WebView.super.getScrollBarStyle(); 2001 } 2002 2003 public void super_scrollTo(int scrollX, int scrollY) { 2004 WebView.super.scrollTo(scrollX, scrollY); 2005 } 2006 2007 public void super_computeScroll() { 2008 WebView.super.computeScroll(); 2009 } 2010 2011 public boolean super_onHoverEvent(MotionEvent event) { 2012 return WebView.super.onHoverEvent(event); 2013 } 2014 2015 public boolean super_performAccessibilityAction(int action, Bundle arguments) { 2016 return WebView.super.performAccessibilityAction(action, arguments); 2017 } 2018 2019 public boolean super_performLongClick() { 2020 return WebView.super.performLongClick(); 2021 } 2022 2023 public boolean super_setFrame(int left, int top, int right, int bottom) { 2024 return WebView.super.setFrame(left, top, right, bottom); 2025 } 2026 2027 public boolean super_dispatchKeyEvent(KeyEvent event) { 2028 return WebView.super.dispatchKeyEvent(event); 2029 } 2030 2031 public boolean super_onGenericMotionEvent(MotionEvent event) { 2032 return WebView.super.onGenericMotionEvent(event); 2033 } 2034 2035 public boolean super_requestFocus(int direction, Rect previouslyFocusedRect) { 2036 return WebView.super.requestFocus(direction, previouslyFocusedRect); 2037 } 2038 2039 public void super_setLayoutParams(ViewGroup.LayoutParams params) { 2040 WebView.super.setLayoutParams(params); 2041 } 2042 2043 // ---- Access to non-public methods ---- 2044 public void overScrollBy(int deltaX, int deltaY, 2045 int scrollX, int scrollY, 2046 int scrollRangeX, int scrollRangeY, 2047 int maxOverScrollX, int maxOverScrollY, 2048 boolean isTouchEvent) { 2049 WebView.this.overScrollBy(deltaX, deltaY, scrollX, scrollY, scrollRangeX, scrollRangeY, 2050 maxOverScrollX, maxOverScrollY, isTouchEvent); 2051 } 2052 2053 public void awakenScrollBars(int duration) { 2054 WebView.this.awakenScrollBars(duration); 2055 } 2056 2057 public void awakenScrollBars(int duration, boolean invalidate) { 2058 WebView.this.awakenScrollBars(duration, invalidate); 2059 } 2060 2061 public float getVerticalScrollFactor() { 2062 return WebView.this.getVerticalScrollFactor(); 2063 } 2064 2065 public float getHorizontalScrollFactor() { 2066 return WebView.this.getHorizontalScrollFactor(); 2067 } 2068 2069 public void setMeasuredDimension(int measuredWidth, int measuredHeight) { 2070 WebView.this.setMeasuredDimension(measuredWidth, measuredHeight); 2071 } 2072 2073 public void onScrollChanged(int l, int t, int oldl, int oldt) { 2074 WebView.this.onScrollChanged(l, t, oldl, oldt); 2075 } 2076 2077 public int getHorizontalScrollbarHeight() { 2078 return WebView.this.getHorizontalScrollbarHeight(); 2079 } 2080 2081 public void super_onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 2082 int l, int t, int r, int b) { 2083 WebView.super.onDrawVerticalScrollBar(canvas, scrollBar, l, t, r, b); 2084 } 2085 2086 // ---- Access to (non-public) fields ---- 2087 /** Raw setter for the scroll X value, without invoking onScrollChanged handlers etc. */ 2088 public void setScrollXRaw(int scrollX) { 2089 WebView.this.mScrollX = scrollX; 2090 } 2091 2092 /** Raw setter for the scroll Y value, without invoking onScrollChanged handlers etc. */ 2093 public void setScrollYRaw(int scrollY) { 2094 WebView.this.mScrollY = scrollY; 2095 } 2096 2097 } 2098 2099 //------------------------------------------------------------------------- 2100 // Package-private internal stuff 2101 //------------------------------------------------------------------------- 2102 2103 // Only used by android.webkit.FindActionModeCallback. 2104 void setFindDialogFindListener(FindListener listener) { 2105 checkThread(); 2106 setupFindListenerIfNeeded(); 2107 mFindListener.mFindDialogFindListener = listener; 2108 } 2109 2110 // Only used by android.webkit.FindActionModeCallback. 2111 void notifyFindDialogDismissed() { 2112 checkThread(); 2113 mProvider.notifyFindDialogDismissed(); 2114 } 2115 2116 //------------------------------------------------------------------------- 2117 // Private internal stuff 2118 //------------------------------------------------------------------------- 2119 2120 private WebViewProvider mProvider; 2121 2122 /** 2123 * In addition to the FindListener that the user may set via the WebView.setFindListener 2124 * API, FindActionModeCallback will register it's own FindListener. We keep them separate 2125 * via this class so that that the two FindListeners can potentially exist at once. 2126 */ 2127 private class FindListenerDistributor implements FindListener { 2128 private FindListener mFindDialogFindListener; 2129 private FindListener mUserFindListener; 2130 2131 @Override 2132 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, 2133 boolean isDoneCounting) { 2134 if (mFindDialogFindListener != null) { 2135 mFindDialogFindListener.onFindResultReceived(activeMatchOrdinal, numberOfMatches, 2136 isDoneCounting); 2137 } 2138 2139 if (mUserFindListener != null) { 2140 mUserFindListener.onFindResultReceived(activeMatchOrdinal, numberOfMatches, 2141 isDoneCounting); 2142 } 2143 } 2144 } 2145 private FindListenerDistributor mFindListener; 2146 2147 private void setupFindListenerIfNeeded() { 2148 if (mFindListener == null) { 2149 mFindListener = new FindListenerDistributor(); 2150 mProvider.setFindListener(mFindListener); 2151 } 2152 } 2153 2154 private void ensureProviderCreated() { 2155 checkThread(); 2156 if (mProvider == null) { 2157 // As this can get called during the base class constructor chain, pass the minimum 2158 // number of dependencies here; the rest are deferred to init(). 2159 mProvider = getFactory().createWebView(this, new PrivateAccess()); 2160 } 2161 } 2162 2163 private static synchronized WebViewFactoryProvider getFactory() { 2164 return WebViewFactory.getProvider(); 2165 } 2166 2167 private final Looper mWebViewThread = Looper.myLooper(); 2168 2169 private void checkThread() { 2170 // Ignore mWebViewThread == null because this can be called during in the super class 2171 // constructor, before this class's own constructor has even started. 2172 if (mWebViewThread != null && Looper.myLooper() != mWebViewThread) { 2173 Throwable throwable = new Throwable( 2174 "A WebView method was called on thread '" + 2175 Thread.currentThread().getName() + "'. " + 2176 "All WebView methods must be called on the same thread. " + 2177 "(Expected Looper " + mWebViewThread + " called on " + Looper.myLooper() + 2178 ", FYI main Looper is " + Looper.getMainLooper() + ")"); 2179 Log.w(LOGTAG, Log.getStackTraceString(throwable)); 2180 StrictMode.onWebViewMethodCalledOnWrongThread(throwable); 2181 2182 if (sEnforceThreadChecking) { 2183 throw new RuntimeException(throwable); 2184 } 2185 } 2186 } 2187 2188 //------------------------------------------------------------------------- 2189 // Override View methods 2190 //------------------------------------------------------------------------- 2191 2192 // TODO: Add a test that enumerates all methods in ViewDelegte & ScrollDelegate, and ensures 2193 // there's a corresponding override (or better, caller) for each of them in here. 2194 2195 @Override 2196 protected void onAttachedToWindow() { 2197 super.onAttachedToWindow(); 2198 mProvider.getViewDelegate().onAttachedToWindow(); 2199 } 2200 2201 /** @hide */ 2202 @Override 2203 protected void onDetachedFromWindowInternal() { 2204 mProvider.getViewDelegate().onDetachedFromWindow(); 2205 super.onDetachedFromWindowInternal(); 2206 } 2207 2208 @Override 2209 public void setLayoutParams(ViewGroup.LayoutParams params) { 2210 mProvider.getViewDelegate().setLayoutParams(params); 2211 } 2212 2213 @Override 2214 public void setOverScrollMode(int mode) { 2215 super.setOverScrollMode(mode); 2216 // This method may be called in the constructor chain, before the WebView provider is 2217 // created. 2218 ensureProviderCreated(); 2219 mProvider.getViewDelegate().setOverScrollMode(mode); 2220 } 2221 2222 @Override 2223 public void setScrollBarStyle(int style) { 2224 mProvider.getViewDelegate().setScrollBarStyle(style); 2225 super.setScrollBarStyle(style); 2226 } 2227 2228 @Override 2229 protected int computeHorizontalScrollRange() { 2230 return mProvider.getScrollDelegate().computeHorizontalScrollRange(); 2231 } 2232 2233 @Override 2234 protected int computeHorizontalScrollOffset() { 2235 return mProvider.getScrollDelegate().computeHorizontalScrollOffset(); 2236 } 2237 2238 @Override 2239 protected int computeVerticalScrollRange() { 2240 return mProvider.getScrollDelegate().computeVerticalScrollRange(); 2241 } 2242 2243 @Override 2244 protected int computeVerticalScrollOffset() { 2245 return mProvider.getScrollDelegate().computeVerticalScrollOffset(); 2246 } 2247 2248 @Override 2249 protected int computeVerticalScrollExtent() { 2250 return mProvider.getScrollDelegate().computeVerticalScrollExtent(); 2251 } 2252 2253 @Override 2254 public void computeScroll() { 2255 mProvider.getScrollDelegate().computeScroll(); 2256 } 2257 2258 @Override 2259 public boolean onHoverEvent(MotionEvent event) { 2260 return mProvider.getViewDelegate().onHoverEvent(event); 2261 } 2262 2263 @Override 2264 public boolean onTouchEvent(MotionEvent event) { 2265 return mProvider.getViewDelegate().onTouchEvent(event); 2266 } 2267 2268 @Override 2269 public boolean onGenericMotionEvent(MotionEvent event) { 2270 return mProvider.getViewDelegate().onGenericMotionEvent(event); 2271 } 2272 2273 @Override 2274 public boolean onTrackballEvent(MotionEvent event) { 2275 return mProvider.getViewDelegate().onTrackballEvent(event); 2276 } 2277 2278 @Override 2279 public boolean onKeyDown(int keyCode, KeyEvent event) { 2280 return mProvider.getViewDelegate().onKeyDown(keyCode, event); 2281 } 2282 2283 @Override 2284 public boolean onKeyUp(int keyCode, KeyEvent event) { 2285 return mProvider.getViewDelegate().onKeyUp(keyCode, event); 2286 } 2287 2288 @Override 2289 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 2290 return mProvider.getViewDelegate().onKeyMultiple(keyCode, repeatCount, event); 2291 } 2292 2293 /* 2294 TODO: These are not currently implemented in WebViewClassic, but it seems inconsistent not 2295 to be delegating them too. 2296 2297 @Override 2298 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 2299 return mProvider.getViewDelegate().onKeyPreIme(keyCode, event); 2300 } 2301 @Override 2302 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 2303 return mProvider.getViewDelegate().onKeyLongPress(keyCode, event); 2304 } 2305 @Override 2306 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 2307 return mProvider.getViewDelegate().onKeyShortcut(keyCode, event); 2308 } 2309 */ 2310 2311 @Override 2312 public AccessibilityNodeProvider getAccessibilityNodeProvider() { 2313 AccessibilityNodeProvider provider = 2314 mProvider.getViewDelegate().getAccessibilityNodeProvider(); 2315 return provider == null ? super.getAccessibilityNodeProvider() : provider; 2316 } 2317 2318 @Deprecated 2319 @Override 2320 public boolean shouldDelayChildPressedState() { 2321 return mProvider.getViewDelegate().shouldDelayChildPressedState(); 2322 } 2323 2324 @Override 2325 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 2326 super.onInitializeAccessibilityNodeInfo(info); 2327 info.setClassName(WebView.class.getName()); 2328 mProvider.getViewDelegate().onInitializeAccessibilityNodeInfo(info); 2329 } 2330 2331 @Override 2332 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 2333 super.onInitializeAccessibilityEvent(event); 2334 event.setClassName(WebView.class.getName()); 2335 mProvider.getViewDelegate().onInitializeAccessibilityEvent(event); 2336 } 2337 2338 @Override 2339 public boolean performAccessibilityAction(int action, Bundle arguments) { 2340 return mProvider.getViewDelegate().performAccessibilityAction(action, arguments); 2341 } 2342 2343 /** @hide */ 2344 @Override 2345 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 2346 int l, int t, int r, int b) { 2347 mProvider.getViewDelegate().onDrawVerticalScrollBar(canvas, scrollBar, l, t, r, b); 2348 } 2349 2350 @Override 2351 protected void onOverScrolled(int scrollX, int scrollY, boolean clampedX, boolean clampedY) { 2352 mProvider.getViewDelegate().onOverScrolled(scrollX, scrollY, clampedX, clampedY); 2353 } 2354 2355 @Override 2356 protected void onWindowVisibilityChanged(int visibility) { 2357 super.onWindowVisibilityChanged(visibility); 2358 mProvider.getViewDelegate().onWindowVisibilityChanged(visibility); 2359 } 2360 2361 @Override 2362 protected void onDraw(Canvas canvas) { 2363 mProvider.getViewDelegate().onDraw(canvas); 2364 } 2365 2366 @Override 2367 public boolean performLongClick() { 2368 return mProvider.getViewDelegate().performLongClick(); 2369 } 2370 2371 @Override 2372 protected void onConfigurationChanged(Configuration newConfig) { 2373 mProvider.getViewDelegate().onConfigurationChanged(newConfig); 2374 } 2375 2376 @Override 2377 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 2378 return mProvider.getViewDelegate().onCreateInputConnection(outAttrs); 2379 } 2380 2381 @Override 2382 protected void onVisibilityChanged(View changedView, int visibility) { 2383 super.onVisibilityChanged(changedView, visibility); 2384 // This method may be called in the constructor chain, before the WebView provider is 2385 // created. 2386 ensureProviderCreated(); 2387 mProvider.getViewDelegate().onVisibilityChanged(changedView, visibility); 2388 } 2389 2390 @Override 2391 public void onWindowFocusChanged(boolean hasWindowFocus) { 2392 mProvider.getViewDelegate().onWindowFocusChanged(hasWindowFocus); 2393 super.onWindowFocusChanged(hasWindowFocus); 2394 } 2395 2396 @Override 2397 protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) { 2398 mProvider.getViewDelegate().onFocusChanged(focused, direction, previouslyFocusedRect); 2399 super.onFocusChanged(focused, direction, previouslyFocusedRect); 2400 } 2401 2402 /** @hide */ 2403 @Override 2404 protected boolean setFrame(int left, int top, int right, int bottom) { 2405 return mProvider.getViewDelegate().setFrame(left, top, right, bottom); 2406 } 2407 2408 @Override 2409 protected void onSizeChanged(int w, int h, int ow, int oh) { 2410 super.onSizeChanged(w, h, ow, oh); 2411 mProvider.getViewDelegate().onSizeChanged(w, h, ow, oh); 2412 } 2413 2414 @Override 2415 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 2416 super.onScrollChanged(l, t, oldl, oldt); 2417 mProvider.getViewDelegate().onScrollChanged(l, t, oldl, oldt); 2418 } 2419 2420 @Override 2421 public boolean dispatchKeyEvent(KeyEvent event) { 2422 return mProvider.getViewDelegate().dispatchKeyEvent(event); 2423 } 2424 2425 @Override 2426 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 2427 return mProvider.getViewDelegate().requestFocus(direction, previouslyFocusedRect); 2428 } 2429 2430 @Override 2431 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 2432 super.onMeasure(widthMeasureSpec, heightMeasureSpec); 2433 mProvider.getViewDelegate().onMeasure(widthMeasureSpec, heightMeasureSpec); 2434 } 2435 2436 @Override 2437 public boolean requestChildRectangleOnScreen(View child, Rect rect, boolean immediate) { 2438 return mProvider.getViewDelegate().requestChildRectangleOnScreen(child, rect, immediate); 2439 } 2440 2441 @Override 2442 public void setBackgroundColor(int color) { 2443 mProvider.getViewDelegate().setBackgroundColor(color); 2444 } 2445 2446 @Override 2447 public void setLayerType(int layerType, Paint paint) { 2448 super.setLayerType(layerType, paint); 2449 mProvider.getViewDelegate().setLayerType(layerType, paint); 2450 } 2451 2452 @Override 2453 protected void dispatchDraw(Canvas canvas) { 2454 mProvider.getViewDelegate().preDispatchDraw(canvas); 2455 super.dispatchDraw(canvas); 2456 } 2457} 2458