具体请参考官方提供文档 Api Guide->Web Apps->Building Web Apps in WebView
If you want to deliver a web application (or just a web page) as a part of a client application,you can do it using WebView
. The WebView
class is anextension of Android's View
class that allows you to display web pages as apart of your activity layout. It does not include any features of a fully developed webbrowser, such as navigation controls or an address bar. All that WebView
does, by default, is show a web page.
如果你想开发一款web的应用程序(或者仅仅是web页)作为你客户端app的一部分,你可以使用webView. webview类可以在activity中的一部分布局显示网页.但是他不具备一些属于浏览器的功能.比如地址导航栏.总而言之.webview就是用来显示网页的..
A common scenario in which using WebView
is helpful is when you want toprovide information in your application that you might need to update, such as an end-user agreementor a user guide. Within your Android application, you can create an Activity
that contains a WebView
, then use that to display your document that'shosted online.
一个常见的场景就是,当你想要提供一些app可能的更新的时候,比如最终用户协议和用户指导,webview是有效的.在你的app中,你可以创建一个包裹着webview布局的activity,用来在线演示一些文档.
Another scenario in which WebView
can help is if your application provides data to the user that always requires an Internet connection to retrieve data, such as email. In this case, you might find that it's easier to build a WebView
in your Android application that shows a web page with all the user data, rather than performing a network request, then parsing the data and rendering it in an Android layout. Instead, you can design a web page that's tailored for Android device sand then implement a WebView
in your Android application that loads the webpage.
另一个常见的场景就是你的应用程序需要经常从网络上获取下载数据的时候,比如邮件,web是有效的,你可能会发现,创建一个webview在你的app中去展示这个用户的所有数据在网页中 比 不断的去请求,然后分析或解析他在你的app中要简单的多.与此相反的,你也可以通过实现webview接口设计一个为android设备去加载网页的程序...
This document shows you how to get started with WebView
and how to do some additional things, such as handle page navigation and bind JavaScript from your web page toclient-side code in your Android application.
这篇文档展示的就是如何开始使用webview,和怎么样去做一些事件,比如实现js与android交互..
This document shows you how to get started with WebView
and how to do some additional things, such as handle page navigation and bind JavaScript from your web page toclient-side code in your Android application.
Add a WebView to your application
添加webview到你的应用程序
To add a WebView
to your Application, simply include the <WebView>
element in your activity layout. For example, here's a layout file in which theWebView
fills the screen:
添加webview到你的app中,使用<webview>布局到activity布局中就可以了,举个例子,下面就是添加了一个充满屏幕的webview.
<?xml version="1.0" encoding="utf-8"?>
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
WebView
, use
loadUrl()
. For example:
使用loadUrl()加载网页,如下:
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.loadUrl("http://www.example.com");
Before this will work, however, your application must have access to the Internet. To getInternet access, request the
INTERNET
permission in yourmanifest file. For example:
在你运行程序之前,你必须让你的app可以连接到网络,为了可以获取网络权限,需要在配置文件中添加INTERNET权限,如下:
<manifest ... >
<uses-permission android:name="android.permission.INTERNET" />
...
</manifest>
That's all you need for a basic WebView
that displays a web page.
以上就是webview如何去显示一个web页面
Using JavaScript in WebView
在webview中使用js
If the web page you plan to load in your WebView
use JavaScript, you must enable JavaScript for your WebView
. Once JavaScript is enabled, you canalso create interfaces between your application code and your JavaScript code.
如果你想在你的webview加载web页面之后使用js的话,你必须允许js在webview可用,一旦js可用,你就可以创建一些接口在你的app代码和你的js代码中..
Enabling JavaScript
JS可用
JavaScript is disabled in a WebView
by default. You can enable it through the WebSettings
attached to your WebView
. You can retrieve WebSettings
with getSettings()
, then enableJavaScript with setJavaScriptEnabled()
.
默认js在webview中不使用的,你可以通过webview获取到WebSettings.你可以通过getSettings()获取WebSettings,然后通过setJavaScriptEnabled()设置js可用.如下:
WebView myWebView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
WebSettings
provides access to a variety of other settings that you might find useful. For example, if you're developing a web application that's designed specifically for the
WebView
in your Android application,then you can define a custom user agent string with
setUserAgentString()
, then query the custom user agent in your web page to verify that the client requesting your web page is actually your Android application.
WebSettings
提供一些你可能会用到的设置.举个例子,如果你正在设计一个webview,是专为你的app的webview,你可以通过setUserAgentString()自定义一个用户,然后在您的网页中查询自定义用户代理,以查看请求网页信息是不是您所需要的android程序
Binding JavaScript code to Android code
Android与JS交互
When developing a web application that's designed specifically for the WebView
in your Android application, you can create interfaces between your JavaScript code and client-side Android code.For example, your JavaScript code can call a method in your Android code to display a Dialog
, instead of using JavaScript's alert()
function.
你可以通过创建js代码和android客户端之间的接口来为你的app设计一个与众不同的web视图.举个例子,你可以通过你的js方法去演示一个窗口,用来代替js的alert功能
public class WebAppInterface {
Context mContext;
/** Instantiate the interface and set the context */
WebAppInterface(Context c) {
mContext = c;
}
/** Show a toast from the web page */
@JavascriptInterface
public void showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
}
Caution: If you've set your
targetSdkVersion
to 17 or higher,
you must add the @JavascriptInterface
annotation to any method that you want available to your JavaScript (the method must also be public). If you do not provide the annotation, the method is not accessible by your web page when running on Android 4.2 or higher.
特别注意:如果你想在你的targetSdkVersion在版本17以上,你必须添加注解@JavascriptInterface在你想要和js交互的方法上(这个方法必须是public的)如果你没有添加注解,那么这个方法将无法在android4.2及以上版本使用..
In this example, the WebAppInterface
class allows the web page to create a Toast
message, using the showToast()
method.
在这个例子中,这个WebAppInterface类通过showToast()方法去创建一个Toast消息
You can bind this class to the JavaScript that runs in your WebView
with addJavascriptInterface()
and name the interface Android
. For example:
你可以将接口名字叫做Android,通过调用webview的addJavascriptInterface()方法绑定到js上,如下:
WebView webView = (WebView) findViewById(R.id.webview);
webView.addJavascriptInterface(new WebAppInterface(this), "Android");
this creates an interface called
Android
for JavaScript running in the
WebView
. At this point, your web application has access to the
WebAppInterface
class. For example, here's some HTML and JavaScript that creates a toastmessage using the new interface when the user clicks a button:
这个创建了一个可以在js运行的叫做Android的接口在webview上,在这里,你的web app可以接受WebAppInterface
类,举个例子,这里是一些通过点击按钮来弹出消息的html和js,
<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />
<script type="text/javascript">
function showAndroidToast(toast) {
Android.showToast(toast);
}
</script>
There's no need to initialize the
Android
interface from JavaScript. The
WebView
automatically makes it available to your web page. So, at the click of the button, the
showAndroidToast()
function uses the
Android
interface to call the
WebAppInterface.showToast()
method.
js里面的Android接口不需要初始化,webview可以让其在网页中可用.点击按钮,这个showAndroidToast()方法就可以使用Android接口里面的 WebAppInterface.showToast()方法了
Note: The object that is bound to your JavaScript runs in another thread and not in the thread in which it was constructed.
注:这个object是已经在另一个线程与js绑定好了,而不是在一个线程里面初始化
Caution: Using addJavascriptInterface()
allows JavaScript to control your Android application. This can be a very useful feature or a dangerous security issue. When the HTML in the WebView
is untrustworthy (for example,part or all of the HTMLis provided by an unknown person or process), then an attacker can include HTML that executes your client-side code and possibly any code of the attacker's choosing. As such, you should not use addJavascriptInterface()
unless you wrote all of the HTML and JavaScript that appears in your WebView
. You should also not allow the user to navigate to other web pages that are not your own, within your WebView
(instead, allow the user's default browser application to open foreign links—by default, the user's web browser opens all URL links, so be careful only if you handle page navigation as described in thefollowing section).
注:使用addJavascriptInterface()可以让你的app使用js,这可能是一个非常有用的功能,或者是一个非常危险的安全问题,当webview视图的html是不可靠的(html完全有一个未知的人或者过程提供)那么攻击者就可以通过html和运行你的客户端代码.所以,你不应该在除了你自己写的html和js中使用addJavascriptInterface().你也不应该让用户导航到一个你也不知道的页面在你的webview中(相反的你可以语序用户使用默认的浏览器去打开外部链接,用户的web浏览器可以打开所有链接,如果你导航到以下情况请小心)
Handing Page Navigation
控制页面导航
When the user clicks a link from a web page in your WebView
, the default behavior is for Android to launch an application that handles URLs. Usually, the default web browser opens and loads the destination URL. However, you can override this behavior for your WebView
,so links open within your WebView
. You can then allow the user to navigate backward and forward through their web page history that's maintained by your WebView
.
当用户点击了webview加载的web页面的一个连接时,android系统的默认行为是启动一个应用去处理,通常,这个默认的web浏览器能够打开和加载目标url,但是你可以重写webview的行为,然后链接可以在你的webview中打开,你也可以允许用户去导航或者跳转通过webview记录的页面历史
To open links clicked by the user, simply provide a WebViewClient
for your WebView
, using setWebViewClient()
. For example:
你可以通过调用webview的setWebViewClient()方法获取到 WebViewClient方法去打开连接,如下:
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.setWebViewClient(new WebViewClient());
That's it. Now all links the user clicks load in your WebView
.
现在所有的用户连接都可以在你的webview中打开
If you want more control over where a clicked link load, create your own WebViewClient
that overrides the shouldOverrideUrlLoading()
method. For example:
shouldOverrideUrlLoading()
方法来创建属于你的WebViewClient,如下:
private class MyWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Uri.parse(url).getHost().equals("www.example.com")) {
// This is my web site, so do not override; let my WebView load the page
return false;
}
// Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
}
Then create an instance of this new
WebViewClient
for the
WebView
:
然后为你的webview初始化一个新的WebViewClient对象.
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.setWebViewClient(new MyWebViewClient());
Now when the user clicks a link, the system calls
shouldOverrideUrlLoading()
, which checks whether the URL host matches a specific domain (as definedabove). If it does match, then the method returns false in order to
not override the URL loading (it allows the
WebView
to load the URL as usual). If the URL hostdoes not match, then an
Intent
is created to launch the default Activity for handling URLs (which resolves to the user's default webbrowser).
现在用户点击了链接之后,这个系统会调用shouldOverrideUrlLoading()这个方法,来检验url是否匹配,如果匹配的话就返回false,如果不匹配的话,就会启动一下默认的activity来处理url....
Navigating web page history
web页面历史导航
When your
WebView
overrides URL loading, it automatically accumulates ahistory of visited webpages. You can navigate backward and forward through the history with goBack()
and goForward()
.
当你的Web视图重写URL加载,它会自动累计访问网页的历史。你可以通过与goback()和goforward()向前或向后导航。
For example, here's how your
Activity
can use the device Back button to navigate backward:
例如,这里是您的activity可以使用物理按钮返回来执行回退操作:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Check if the key event was the Back button and if there's history
if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
myWebView.goBack();
return true;
}
// If it wasn't the Back key or there's no web page history, bubble up to the default
// system behavior (probably exit the activity)
return super.onKeyDown(keyCode, event);
}
The
canGoBack()
method returnstrue if there is actually web page history for the user to visit. Likewise, you can use
canGoForward()
to check whether there is a forward history. If you don't perform this check, then once the user reaches the end of the history,
goBack()
or
goForward()
does nothing.
canGoBack()方法返回true可以说明你有可供后退的历史,你也可以使用canGoForward()来检查是否有前进历史,如果你没有进行调用,当你到达历史的第一页或者最后一页时, goBack()
或goForward()
将没有任何作用