編輯:關於 Android 程式設計
用 PhoneGap(Cordova)做 JS 與原生交織的混合型應用時,最關鍵的一塊就是 Plugin。Plugin 是 WebView 裡的 JavaScript 與原生程式碼之間的橋梁,本篇以一個把字串回傳的 Echo 範例走過完整流程。
先安裝 Node.js(https://nodejs.org/),再用 npm 安裝 PhoneGap(https://phonegap.com/install/)。首次安裝會需要等候一段時間下載相依套件。
建立完成後,platforms/ 底下會依平台產生各自的專案結構,把 Android 目錄匯入 IDE 即可開始編輯。
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.");
}
}
}
於 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>
在 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);
<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()" />
若不使用預設的 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 回傳的訊息。
Android 屏幕適配完全指南
從 2012 年到 2014 年,支持 Android 的設備種類從 3997 種暴漲到了 18796 種,各大廠商定制的屏幕尺寸更是五花八門。這給我們的屏幕適配工作帶來
深入解析 Android 6.0 的 LowMemoryKiller 機制
近來處理了一些與 LowMemoryKiller 相關的問題,於是對這個機制作了一輪梳理,在此整理成筆記。 背景知識 眾所周知,Android 的本質是一個 Linux
TextView 實現圖文混排:Html.fromHtml 與 ImageGetter 用法
TextView 通常只展示文字,但通過簡單的 HTML 標簽,就能實現不同顏色、不同字號的文字混排,甚至插入圖片。 支援的基礎標簽 <font>:設置顏
Android Fragment 界面向下跳轉與逐層返回的實作方法詳解
本文示範如何在 Android 中使用 Fragment 實現介面向下一層層跳轉、並能一級級返回的效果,供大家參考。核心思路是透過自訂的返回處理介面與抽象 Fragmen