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