理解Android Web Apps的運行機制,實現簡單的包含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>元素

<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中請求網絡權限的:

<uses-permission android:name="android.permission.INTERNET"/>

    2.3 使用Web View:

WebView myWebView = (WebView) findViewById(R.id.webview);

    2.4 加載一個頁面,可以用loadUrl()方法,例如:

myWebView.loadUrl("http://www.xxx.com");

  3. 在Web View 中使用JavaScript

     3.1 如果你加載到 Web View 中的網頁使用了JavaScript,那麼,需要在Websetting 中開啓對JavaScript的支持,因爲Web View 中默認的是JavaScript未啓用。

// 獲取 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調用

public class JavaScriptInterface { 

  Context mContext;

    /** 初始化context,供makeText方法中的參數來使用 */
    JavaScriptInterface(Context c) {
        mContext = c;
    }

   
/** 創建一個方法,實現顯示對話框的功能,供JavaScript中的代碼來調用 */
   
public void showToast(String toast) {
        Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
    }

}

 

    2)通過調用addJavascriptInterface方法,把我們上面創建的接口類綁定與運行在Web View上的JavaScript進行綁定。

// 第二個參數是爲這個接口對象取的名字,以方便JavaScript調用

webView.addJavascriptInterface(new JavaScriptInterface(this), "Android");

 

       3)現在,我們可以在html中的JavaScript部分調用showToast()方法了。

<script type="text/javascript">
   
function showAndroidToast(toast) {
        Android.showToast(toast);
    }
</script>

<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />

 

    4. 處理頁面導航

     當用戶在Web View中點擊頁面上的超鏈接時, Android的默認行爲是啓動一個能處理URL的應用程序,通常情況下是啓動默認的瀏覽器。而如果我們想用當前的Web View打開頁面,則需要重載這個行爲。這樣我們就可以通過操作Web View的歷史記錄來向前和向後導航。

      4.1 爲Web View提供一個WebViewClient,從而在WebView中打開用戶的鏈接。 如果我們想對加載頁面有跟多的控制,可以繼承並實現一個複雜的WebViewClient

myWebView.setWebViewClient(new 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;
    }
}
 

     4.2 利用Web View的歷史記錄來實現頁面navigate backword.

     重載Activity中的onKeyDown方法,實現此功能:

@Override

public boolean onKeyDown(int keyCode, 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();
        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);
}

 


  5. 現在應用以上知識,實現一個簡單的基於Web View的Android 應用程序

    程序的功能主要是:當進入程序後,顯示一個網頁,此頁面上有一個新聞超鏈接,用戶點擊超鏈接,在Web View中加載新聞的內容頁面。

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

package com.WebApp;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebSettings;
import android.webkit.WebView;

public class Home extends Activity {
   
// declare a WebView
    private WebView myWebView;

    @Override
   
public void onCreate(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(new myJavaScriptInterface(), "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
    
*/
   
final class myJavaScriptInterface {

        myJavaScriptInterface() {
        }

       
/**
         * load the content page
        
*/
       
public void LoadContentPage() {
            myWebView.loadUrl(
"file:///android_asset/second.html");
        }
    }
   
    @Override
   
public boolean onKeyDown(int keyCode, 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();
           
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);
    }
}
 

    5.2 在Android項目文件下的assets目錄下創建一個名爲first.html的頁面作爲首頁

<html>
        <body>
            <!-- 調用Android代碼中的方法 -->
            <a onClick="window.myJS.LoadContentPage()" style="text-decoration: underline">
            Google+ is now under testing!
            </a>
        </body>
</html>
 

    5.3 在Android項目文件下的assets目錄下創建一個名爲second.html的頁面作爲內容頁

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-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>

 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章