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

PhoneGap / Cordova 混合開發入門:動手做一個 Echo Plugin

編輯:關於 Android 程式設計

用 PhoneGap(Cordova)做 JS 與原生交織的混合型應用時,最關鍵的一塊就是 Plugin。Plugin 是 WebView 裡的 JavaScript 與原生程式碼之間的橋梁,本篇以一個把字串回傳的 Echo 範例走過完整流程。

一、環境準備

先安裝 Node.js(https://nodejs.org/),再用 npm 安裝 PhoneGap(https://phonegap.com/install/)。首次安裝會需要等候一段時間下載相依套件。

二、建立專案並觀察目錄結構

建立完成後,platforms/ 底下會依平台產生各自的專案結構,把 Android 目錄匯入 IDE 即可開始編輯。

三、撰寫原生 Plugin

Plugin 類別繼承 CordovaPlugin,重點是覆寫 execute():由 action 名稱決定要執行什麼,再用 CallbackContext 把結果回傳給 JS。

package com.bbcvision.multiscreen.plugin;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;

public class Echo extends CordovaPlugin {
    private static final String ACTION_ECHO = "echo";

    @Override
    public boolean execute(String action, JSONArray args,
                           CallbackContext callbackContext) throws JSONException {
        if (ACTION_ECHO.equals(action)) {
            String message = args.getString(0);
            this.echo(message, callbackContext);
            return true;
        }
        return false;
    }

    private void echo(String message, CallbackContext callbackContext) {
        if (message != null && message.length() > 0) {
            callbackContext.success(message);
        } else {
            callbackContext.error("Expected one non-empty string argument.");
        }
    }
}

四、在 config.xml 註冊 Plugin

於 res/xml/config.xml 中以 <feature> 標籤登記,並用 <param> 指向原生類別的完整路徑,JS 端才找得到它。

<widget id="com.phonegap.helloworld" version="1.0.0"
    xmlns="https://www.w3.org/ns/widgets"
    xmlns:gap="https://phonegap.com/ns/1.0">

    <name>Hello Cordova</name>
    <description>A sample Apache Cordova application.</description>
    <content src="index.html" />

    <feature name="App">
        <param name="android-package" value="org.apache.cordova.App" />
    </feature>
    <feature name="Echo">
        <param name="android-package" value="com.bbcvision.multiscreen.plugin.Echo" />
    </feature>

    <preference name="android-minSdkVersion" value="7" />
    <preference name="fullscreen" value="true" />
</widget>

五、撰寫 JS 橋梁

在 assets/www/js/ 建立 echo.js,用 cordova.exec() 把成功回呼、失敗回呼、Plugin 名稱、action 名稱與參數串接起來。

var echoPlugin = {
    echo: function(message, successCallback, errorCallback) {
        cordova.exec(
            successCallback,   // 成功回呼
            errorCallback,     // 失敗回呼
            'Echo',            // 對應 config.xml 中 feature 的名稱
            'echo',            // 對應 execute() 中的 action
            [message]          // 傳入原生的參數陣列
        );
    }
};

六、在頁面中呼叫

var success = function(message) { alert("Success: " + message); };
var error = function(message) { alert("Oopsie! " + message); };
echoPlugin.echo("Hello Plugin", success, error);

七、介面 HTML

<script type="text/javascript" src="phonegap.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript" src="js/echo.js"></script>
<script type="text/javascript">app.initialize();</script>

<input type="button" value="Say Hello" onclick="app.addToCal()" />

八、自訂 Activity 承載 CordovaWebView

若不使用預設的 DroidGap,可以自行把 CordovaWebView 放進配置檔,並讓 Activity 實作 CordovaInterface。

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <org.apache.cordova.CordovaWebView
        android:id="@+id/content"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

    <Button
        android:id="@+id/load"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Load" />
</LinearLayout>
@ContentView(R.layout.phonegap1)
public class HelloPhoneGap2 extends RoboActivity implements CordovaInterface {

    private final ExecutorService threadPool = Executors.newCachedThreadPool();
    private CordovaPlugin activityResultCallback;
    private boolean activityResultKeepRunning;
    private boolean keepRunning;

    @InjectView(R.id.content)
    private CordovaWebView mWebView;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mWebView.loadUrl("file:///android_asset/www/hello.html");
    }

    @Override
    public void setActivityResultCallback(CordovaPlugin plugin) {
        this.activityResultCallback = plugin;
    }

    @Override
    public Activity getActivity() { return this; }

    @Override
    public Object onMessage(String s, Object o) { return null; }

    @Override
    public ExecutorService getThreadPool() { return threadPool; }

    @Override
    public void startActivityForResult(CordovaPlugin command, Intent intent, int requestCode) {
        this.activityResultCallback = command;
        this.activityResultKeepRunning = this.keepRunning;
        if (command != null) {
            this.keepRunning = false;
        }
        super.startActivityForResult(intent, requestCode);
    }
}

上述 Activity 使用 RoboGuice 做依賴注入,因此可省去大量 findViewById。完成後執行專案,點擊按鈕即可看到 Plugin 回傳的訊息。

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