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