如何在WebView中建立Android Apps

来源:互联网 发布:一个小游戏的java语言 编辑:程序博客网 时间:2024/05/29 04:02

今日学习任务:理解Android Web Apps的运行机制,实现简单的包含Web View的应用程序

涉及的主要内容:1) Android Web Apps的两种形式 2)Web View的创建和使用方法    

1. Web Apps的两种形式

在Android中,Web Apps有两种形式供用户访问。一种就是用手机上的浏览器直接访问的网络应用程序,这种情况用户不需要额外安装其他应用,只要有浏览器就行;而另一种,则 是在用户的手机上安装客户端应用程序(.apk),并在此客户端程序中嵌入Web View来显示从服务器端下载下来的网页数据,比如新浪微博和人人网的客户端。对于前者来说,主要的工作是根据手机客户端的屏幕来调整网页的显示尺寸、比 例等;而后者需要单独开发基于Web View的Web app. 本篇主要是学习后者的开发。

      

     (图片来源于:developer.android.com) 

2. 怎样在Android应用程序中加入Web View?

2.1 先在layout文件中加入<WebView>元素

1
2
3
4
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/webview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"/>
2.2 由于应用程序需要访问网络,所以需要在AndroidManifest.xml中请求网络权限的:
1
<uses-permissionandroid:name="android.permission.INTERNET"/>
2.3 使用Web View:
1
WebView myWebView = (WebView) findViewById(R.id.webview);
2.4 加载一个页面,可以用loadUrl()方法,例如:
1
myWebView.loadUrl("http://www.xxx.com");
3. 在Web View 中使用JavaScript 

3.1 如果你加载到 Web View 中的网页使用了JavaScript,那么,需要在Websetting 中开启对JavaScript的支持,因为Web View 中默认的是JavaScript未启用。

1
2
3
4
// 获取 WebSetting
WebSettings webSettings = myWebView.getSettings();
// 开启Web View对JavaScript的支持
webSettings.setJavaScriptEnabled(true);
3.2 将JavaScript与Android客户端代码进行绑定。

为什么要绑定呢? 可以看这个例子:如果JavaScript 代码想利用Android的代码来显示一个Dialog,而不用JavaScript的alert()方法,这时就需要在Android代码和 JavaScript代码间创建接口,这样在Android代码中实现显示对话框的方法,然后JavaScript调用此方法。

1)创建 Android代码和JavaScript代码的接口,即创建一个类,类中所写的方法将被JavaScript调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
publicclassJavaScriptInterface { 
 
  Context mContext;
 
    /** 初始化context,供makeText方法中的参数来使用 */
    JavaScriptInterface(Context c) {
        mContext = c;
    }
 
    /** 创建一个方法,实现显示对话框的功能,供JavaScript中的代码来调用 */
    publicvoidshowToast(String toast) {
        Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
    }
 
}
2)通过调用addJavascriptInterface方法,把我们上面创建的接口类绑定与运行在Web View上的JavaScript进行绑定。
1
2
// 第二个参数是为这个接口对象取的名字,以方便JavaScript调用
webView.addJavascriptInterface(newJavaScriptInterface(this),"Android");
3)现在,我们可以在html中的JavaScript部分调用showToast()方法了。
1
2
3
4
5
6
7
<scripttype="text/javascript">
    function showAndroidToast(toast) {
        Android.showToast(toast);
    }
</script>
 
<inputtype="button"value="Say hello" onClick="showAndroidToast('Hello Android!')" />
4. 处理页面导航

当用户在Web View中点击页面上的超链接时, Android的默认行为是启动一个能处理URL的应用程序,通常情况下是启动默认的浏览器。而如果我们想用当前的Web View打开页面,则需要重载这个行为。这样我们就可以通过操作Web View的历史记录来向前和向后导航。

4.1 为Web View提供一个WebViewClient,从而在WebView中打开用户的链接。 如果我们想对加载页面有跟多的控制,可以继承并实现一个复杂的WebViewClient

1
myWebView.setWebViewClient(newWebViewClient());
1
2
3
4
5
6
7
8
9
10
11
12
13
privateclassMyWebViewClient extends WebViewClient {
    @Override
    publicboolean 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
            returnfalse;
        }
        // Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
        Intent intent = newIntent(Intent.ACTION_VIEW, Uri.parse(url));
        startActivity(intent);
        returntrue;
    }
}
4.2 利用Web View的历史记录来实现页面navigate backword.

重载Activity中的onKeyDown方法,实现此功能:

1
2
3
4
5
6
7
8
9
10
11
12
@Override
 
 publicboolean onKeyDown(intkeyCode, KeyEvent event) {
    // Check if the key event was the BACK key and if there's history
    if((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack() {
        myWebView.goBack();
        returntrue;
    }
    // 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)
    returnsuper.onKeyDown(keyCode,event);
}
5. 现在应用以上知识,实现一个简单的基于Web View的Android 应用程序

程序的功能主要是:当进入程序后,显示一个网页,此页面上有一个新闻超链接,用户点击超链接,在Web View中加载新闻的内容页面。

5.1 创建含有Web View的Activity:Home.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package com.WebApp;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebSettings;
import android.webkit.WebView;
 
publicclassHome extends Activity {
    // declare a WebView
    privateWebView myWebView;
 
    @Override
    publicvoidonCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);
         
        // initialize the WebView
        myWebView = (WebView) findViewById(R.id.webview);
         
        /* Enable the JavaScript in Web View */
        WebSettings webSettings = myWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
 
        // bind the Android code to JavaScript code
        myWebView.addJavascriptInterface(newmyJavaScriptInterface(),"myJS");
         
        // load a web page
        myWebView.loadUrl("file:///android_asset/first.html");
    }
 
    /**
     * This class is an interface between Android and JavaScript
     * whose methods can be accessed by JavaScript code
     */
    finalclassmyJavaScriptInterface {
 
        myJavaScriptInterface() {
        }
 
        /**
         * load the content page
         */
        publicvoidLoadContentPage() {
            myWebView.loadUrl("file:///android_asset/second.html");
        }
    }
     
    @Override
    publicboolean onKeyDown(intkeyCode, KeyEvent event) {
        // Check if the key event was the BACK key and if there's history
        if((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()){
            myWebView.goBack();
            returntrue;
        }
        // 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)
        returnsuper.onKeyDown(keyCode,event);
    }
}
5.2 在Android项目文件下的assets目录下创建一个名为first.html的页面作为首页
1
2
3
4
5
6
7
8
<html>
        <body>
            <!-- 调用Android代码中的方法 -->
            <aonClick="window.myJS.LoadContentPage()"style="text-decoration: underline">
            Google+ is now under testing!
            </a>
        </body>
</html>
5.3 在Android项目文件下的assets目录下创建一个名为second.html的页面作为内容页
1
2
3
4
5
6
7
8
9
10
11
12
13
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html; charset=ISO-8859-1">
<title>Google+ is under testing</title>
</head>
<body>
Google+ is in limited Field Trial Right now, we're testing with a small number of people,
but it won't be long before the Google+ project is ready for everyone.
Leave us your email address and we'll make sure you're the first to know when we're ready to invite more people.
</body>
 
</html>
5.4 运行程序,测试

本文转自:http://www.itivy.com/android/archive/2011/7/1/how-to-build-android-application-in-webview.html