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