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