Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android WebView 加載本地 HTML 並與 Java 互相呼叫

編輯:關於 Android 程式設計

透過 WebView,我們可以在應用中展示 HTML 內容,並透過 addJavascriptInterface() 建立 Java 與 JavaScript 之間的雙向溝通橋樑。以下示範如何加載本地 HTML,並實現兩者互相呼叫。

版面配置

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/tv"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <WebView
        android:layout_below="@+id/tv"
        android:id="@+id/webview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />
</RelativeLayout>

Java 端程式碼

package com.example.webview_workflowy;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.webkit.WebView;
import android.widget.Toast;

public class MainActivity extends Activity {
    private WebView webView;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 找到 WebView
        webView = (WebView) findViewById(R.id.webview);
        // 允許 JavaScript 執行
        webView.getSettings().setJavaScriptEnabled(true);
        // 加載頁面,找到 Html 檔案,也可以用網路上的檔案
        webView.loadUrl("file:///android_asset/index.html");
        // 添加一個物件,讓 JS 可以訪問該物件的方法,該物件中也可以呼叫 JS 中的方法
        webView.addJavascriptInterface(new Contact(), "contact");
    }

    private final class Contact {
        // JavaScript 調用此方法撥打電話
        public void call(String phone) {
            // startActivity(new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phone)));
            Toast.makeText(MainActivity.this, phone, Toast.LENGTH_LONG).show();
        }

        // Html 調用此方法傳遞數據
        public void showcontacts() {
            String json = "[{\"name\":\"zxx\", \"amount\":\"9999999\", \"phone\":\"18600012345\"}]";
            // 調用 JS 中的方法
            webView.loadUrl("javascript:show('" + json + "')");
        }

        public void toast(String str) {
            Toast.makeText(MainActivity.this, "aaaaaaaaaaaa --- " + str, Toast.LENGTH_LONG).show();
        }
    }
}

HTML 端程式碼

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
function show(jsondata){
    var jsonobjs = eval(jsondata);
    var table = document.getElementById("personTable");
    for(var y=0; y<jsonobjs.length; y++){
        var tr = table.insertRow(table.rows.length);
        var td1 = tr.insertCell(0);
        var td2 = tr.insertCell(1);
        td2.align = "center";
        var td3 = tr.insertCell(2);
        td3.align = "center";
        td1.innerHTML = jsonobjs[y].name;
        td2.innerHTML = jsonobjs[y].amount;
        td3.innerHTML = "<a href='javascript:contact.call(\""+ jsonobjs[y].phone+ "\")'">"+ jsonobjs[y].phone+ "</a>";
    }
}
</script>
</head>
<body onload="javascript:contact.showcontacts()">
<button id="button" onclick="javascript:contact.toast('123')">haha</button>
<table border="0" width="100%" id="personTable" cellspacing="0">
    <tr>
        <td width="30%">姓名</td>
        <td width="30%" align="center">存款</td>
        <td align="center">電話</td>
    </tr>
</table>
</body>
</html>

溝通流程說明

  • Java 呼叫 JS:Java 端透過 webView.loadUrl("javascript:show(...)") 主動呼叫 HTML 中的 JavaScript 函式,並可傳入 JSON 字串。
  • JS 呼叫 Java:HTML 端透過 contact.xxx() 呼叫已透過 addJavascriptInterface() 注入的 Java 物件方法,例如 contact.call() 或 contact.toast()。
  • 載入本地檔案時,需將 HTML 放在 assets 目錄,並以 file:///android_asset/ 為前綴載入。

安全提醒:在 Android 4.2 以下版本,addJavascriptInterface() 存在已知的安全漏洞,可能讓惡意網頁執行任意程式碼。建議僅對可信的本地內容使用,並在 minSdkVersion 設定為 17 以上以啟用安全防護。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved