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