引言
Cordova(PhoneGap)采用的是HTML5+JavaScript混合模式來開 發移動手機APP,因此當頁面需要獲取手機內部某些信息時(例如:聯系人信息,坐標定位,短信等),程序就需要調用手機內部的API跟頁面進行信息交換。 Cordova 特別為此定制了完善的解決方案,以方便用戶進行程序編輯。在這一章里將為大家逐一介紹Cordova與Actitity通訊的實現原理。
目錄
一、CordovaPlugin類簡介
二、頁面通過 cordova.exec 函數調用 CordovaPlugin 插件
三、CordovaInterface接口說明
四、頁面通過CordovaPlugin插件調用Activity開發實例
一、CordovaPlugin類簡介
CordovaPlugin是Cordova插件的父類,用戶自定義的插件必須繼承父類,它的主要常用屬性如下
| 屬性 | 詳細說明 |
| CordovaWebView | 視圖管理器,當中包括PluginManager、CordovaWebViewEngine、ICordovaCookieManager等多個對象,用于管理界面渲染,視圖加載過程中的生命周期 |
| CordovaInterface | 定義startActivityForResult、setActivityResultCallback等主要方法,獲取調用上下文中的Activity對象 |
| CordovaPreferences | 用于管理bundle中的屬性值 |
表格1.1
CordovaPlugin的常用方法如下
| 方法 | 詳細說明 |
| void privateInitialize(String serviceName, CordovaInterface cordova, CordovaWebView webView, CordovaPreferences preferences) | 插件初始化時執行,用于定義service名稱,cordovaInterface接口,CodovaWebView視圖,CordovaPreferences 屬性等值 |
| boolean execute(String action, String rawArgs, CallbackContext callbackContext) | 在開發插件時,用戶的自定義方法,當頁面調用插件時系統首先將會運行此方法 |
| boolean execute(String action, JSONArray args, CallbackContext callbackContext) | 同上 |
| boolean execute(String action, CordovaArgs args, CallbackContext callbackContext) | 同上 |
| void onActivityResult(int requestCode, int resultCode, Intent intent) | 在開發插件時,用戶的自定義方法,插件調用startActivityForResult后的回調函數。 |
| String getServiceName() | 獲取在config文件中該服務的名稱 |
| Boolean shouldAllowRequest(String url) | 判斷是否允許此請求 |
| Boolean shouldAllowNavigation(String url) | 判斷是否允許此導航 |
| Boolean shouldOpenExternalUrl(String url) | 判斷是否打開外部鏈接 |
| boolean onReceivedHttpAuthRequest(CordovaWebView view, ICordovaHttpAuthHandler handler, String host, String realm) | |
| boolean onReceivedClientCertRequest(CordovaWebView view, ICordovaClientCertRequest request) |
表格1.2
CordovaPlugin的詳細解析可參考官網
http://cordova.apache.org/docs/en/3.4.0/guide_hybrid_plugins_index.md.html#Plugin%20Development%20Guide
回到目錄
二、頁面調用 CordovaPlugin 插件實例
大概了解 CordovaPlugin 類的使用方法后,下面為大家介紹一下頁面調用插件的例子。首先打開文件res/xml/config.xml為插件進行配置。
<preference/>可用于運行環境中的常用參數,例如:全屏設置,滾動條設置,背景色設置等等
<preference name="Fullscreen" value="true" />
<preference name="DisallowOverscroll" value="true"/>
<preference name="BackgroundColor" value="0xff0000ff"/>
<feature></feature>節點用于設置插件描述,feature的name屬性是設置插件的唯一標示,在頁面調用插件時將通過name找到此插件
在開發插件時,先為此插件添加一個<feature>節點,在<param>中綁定插件的后臺執行文件ShowMessagePlugin.java
<param name="android-package" value="org.apache.cordova.showmessage.ShowMessagePlugin" />
<?xml version='1.0' encoding='utf-8'?> <widget id="com.sun.androidapp" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0"> <!--設置運行環境中的參數值 --> <preference name="loglevel" value="DEBUG" /> <!-- 插件描述 --> <feature name="Whitelist"> <param name="android-package" value="org.apache.cordova.whitelist.WhitelistPlugin" /> <param name="onload" value="true" /> </feature> <feature name="ShowMessage"> <param name="android-package" value="org.apache.cordova.showmessage.ShowMessagePlugin" /> </feature> <allow-intent href="market:*" /> <!-- 該APP名稱 --> <name>AndroidTest</name> <!-- APP描述 --> <description> A sample Apache Cordova application that responds to the deviceready event. </description> <!-- 作者信息描述 --> <author email="dev@cordova.apache.org" > Apache Cordova Team </author> <!-- 默認啟動頁面 --> <content src="index.html" /> <!-- 指定app可進行通信的域名,*為所有 --> <access origin="*" /> <!-- App默認只請允許通過手機端直接打開,若想通過網站,SMS等方式調用APP,則需要設置allow-intent配置 --> <allow-intent href="http://*/*" /> <allow-intent href="https://*/*" /> <allow-intent href="tel:*" /> <allow-intent href="sms:*" /> <allow-intent href="mailto:*" /> <allow-intent href="geo:*" /> </widget>
建立org.apache.cordova.showmessage.ShowMessagePlugin類,且繼承CordovaPlugin基類,并實現
bool execute(action,args,callbackcontext) 方法。當頁面調用此插件時,默認執行此方法。
action 是唯一標識符,系統可根據不同的action進行不同的操作。
args是頁面傳入的參數,支持String, JsonArray,CordovaArgs 等三種不同的類型。
callbackcontext是系統的上下文,當完成操作后調用callbackcontext.success(支持多類型參數)方法,表示插件操作已完成,并把參數返還到頁面。最終返回true代表插件執行成功,false代表執行失敗
package org.apache.cordova.showmessage;
public class ShowMessagePlugin extends CordovaPlugin {
@Override
public boolean execute(String action,JSONArray args,CallbackContext context)
throws JSONException{
if(action.equals("mydream")){
String msg=args.getString(0)+"'s dream is to become a "+args.getString(1);
context.success(msg);
return true;
}
return false;
}
}在 cordova.js 包中,最常用的是 cordova.exec(success,failed,service,action,args)函數,頁面正是通過此函數調用插件。
success 用于綁定插件執行成功后回調的回調函數
failed用于綁定執行失敗的回調函數
service與config.xml配置文件中feature字節的name屬性相對應
action與ShowMessagePlugin對象boolean excute方法中action參數對應,用于分辨插件執行的方法類型,插件可根據action類型的不同作出分類處理。
args為輸入參數
Name: <input type="text" id="txt1"/>
Dream:<input type="text" id="txt2"/>
<input type="button" onclick="btnclick()" name="btn" value="Click"/> <br/>
<label id="label"></label>
<script type="text/javascript">
function btnclick(){
var name=$("#txt1").val();
var dream=$("#txt2").val();
//通過 cordova.exec (success,failed,serviceName,action,args)函數調用插件
cordova.exec(success,failed,"ShowMessage","mydream",[name,dream])
}
//成功調用插件,獲取返回值后的頁面處理函數
function success(result){
if(result!=null)
$("#label").html(result);
else
alert("no message");
}
//調用失敗后的處理函數
function failed(msg){
......
}
</script>測試結果

回到目錄
三、CordovaInterface接口說明
CordovaInterface 接口默認是由 CordovaInterfaceImpl 類實現的,當中包括了一個Activity對象。當打開APP時 Cordova 會默認啟動此 Activity 以承載 Cordova 核心引擎對程序進行管理。ExecutorService 則負責對象對線程池進行管理,PluginManager則負責對插件進行管理,CordovaPlugin則是Cordova插件的父類,所有插件都必須繼承CordovaPlugin。
| 屬性 | 詳細說明 |
| Activity | 打開APP時 Cordova 會默認啟動此 Activity 以承載 Cordova 核心引擎對程序進行管理 |
| ExecutorService | 對線程池進行管理 |
| PluginManager | 插件管理器,用于管理插件的生成,運行,結束等生命周期 |
| CordovaPlugin | 通過startActivityForResult方法綁定CordovaPlugin插件 |
| ActivityResultHolder | 內部類,封裝了requestCode, resultCode, intent等對象 |
表格2.1
CordovaInterfaceImpl定義了三個最常用方法
| 方法 | 詳細說明 |
| void startActivityForResult(CordovaPlugin command, Intent intent, int requestCode) | 綁定CordovaPlugin參數,并調用Activity對象的startActivityForResult(intent, requestCode)方法,根據 intent 綁定值跳轉到對應的activity |
| void setActivityResultCallback(CordovaPlugin plugin) | 激發CordovaPlugin對象的onActivityResult事件 |
| boolean onActivityResult(int requestCode, int resultCode, Intent intent) | 封裝Acticity對象的onActivityResult回調函數, 激發CordovaPlugin對象的onActivityResult事件 |
表格2.2
回到目錄
四、頁面通過CordovaPlugin插件調用Activity開發實例
類似于第一節實例,在頁面通過cordova.exec(success,failed,service,action,args)方法調用插件,返回時調用success函數進行處理顯示結果
出游省份:
<select id="select1">
<option value='1' selected='selected'>黑龍江</option>
<option value='2'>吉林</option>
<option value='3'>遼寧</option>
</select>
<input type="button" onclick="btnclick()" name="btn" value="查找"/> <br/>
路線景點:
<label id="label"></label><br/>
<script type="text/javascript">
function btnclick(){
var province=$("#select1").val();
//通過 cordova.exec (success,failed,serviceName,actionName,args)函數調用插件
cordova.exec(success,null,"ShowMessage","showMessage",[province]);
}
//成功調用插件,獲取返回值后的頁面處理函數
function success(result){
if(result!=null)
$("#label").html(result);
else
alert("no message");
}
</script>
插 件通過判斷action參數判斷進行不同的處理,然后通過Intent對象綁定將要啟動的Activity,最后通過CordovaInterface中 的startActivityForResult(cordovaPlugin,intent,int)方法啟動該Activity。當 Activity 結束后,系統將調用回調函數 onActivityResult(int requestCode, int resultCode, Intent intent)
在此說明一下Intent類的用途,此類主要用于綁定當前的活動與子活動之間關系,當中包含6種構造函數。
1、Intent() 空構造函數
2、Intent(Intent o) 拷貝構造函數
3、Intent(String action) 指定action類型的構造函數
4、Intent(String action, Uri uri) 指定Action類型和Uri的構造函數,URI主要是結合程序之間的數據共享ContentProvider
5、Intent(Context packageContext, Class<?> cls) 傳入組件的構造函數,也就是此例子中使用到的
6、Intent(String action, Uri uri, Context packageContext, Class<?> cls) 前兩種結合體
Intent 類中封裝了一個Bundle 對象 mExtras,可用于主活動與子活動之間傳值,系統可通過 putExtra 方法把參數傳入mExtras, 也可通過 getShortExtra、getIntExtra、getBooleanExtra、getByteExtra 等多個方法從mExtras 獲取參數值。
public class ShowMessagePlugin extends CordovaPlugin {
private CallbackContext context;
@Override
public boolean execute(String action,JSONArray args,CallbackContext context)
throws JSONException{
this.context=context;
//根據action判斷調用方法
if(action.equals("showMessage")){
//通過Intent綁定將要調用的Activity
Intent intent=new Intent(this.cordova.getActivity(),SpotActivity.class);
//加入將要傳輸到activity中的參數
intent.putExtra("province", args.getString(0));
//啟動activity
this.cordova.startActivityForResult(this, intent, 0);
}
return true;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
// 根據resultCode判斷處理結果
if(resultCode==Activity.RESULT_OK){
String spot=intent.getStringExtra("spot");
context.success(spot);
}
}
}Activity 被觸發后先通過 setContentView 方法綁定視圖,再從intent 對象中獲取輸入參數進行處理。
完成操作后,通過 Activity 類 setResult(int resultCode, Intent data) 方法綁定返回值,其中resultCode可被 cordovaPlugin 插件用作判斷返回值的處理結果。
最后調用 Activity 對象的 finish 方法關閉 SpotActivity,把返回值回傳到 CordovaPlugin。
public class SpotActivity extends Activity{
private CheckBox chk1,chk2,chk3;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
//綁定視圖
setContentView(R.layout.goods_list);
//從intent中獲取輸入參數
Integer province=Integer.parseInt(this.getIntent().getStringExtra("province"));
setSpots(province);
}
private void setSpots(Integer n){
this.chk1=(CheckBox)this.findViewById(R.id.checkBox1);
this.chk2=(CheckBox)this.findViewById(R.id.checkBox2);
this.chk3=(CheckBox)this.findViewById(R.id.checkBox3);
switch(n){
case 1:
chk1.setText("漠河");
chk2.setText("北極村");
chk3.setText("九曲十八灣");
break;
case 2:
chk1.setText("長白山");
chk2.setText("霧凇島");
chk3.setText("朝鮮自治州");
break;
case 3:
chk1.setText("鴨綠江");
chk2.setText("筆架山");
chk3.setText("鳳凰山");
break;
default:
break;
}
}
public void btn_onClick(View view){
String spot="";
if(chk1.isChecked())
spot+=chk1.getText();
if(chk2.isChecked())
spot+=" "+chk2.getText();
if(chk3.isChecked())
spot+=" "+chk3.getText();
//通過setResult綁定返回值
Intent intent=new Intent();
intent.putExtra("spot",spot);
setResult(RESULT_OK,intent);
//關閉該activity,把返回值傳回到cordovaPlugin插件
this.finish();
}
}Activity 視圖
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_alignParentBottom="true" android:orientation="vertical" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="選擇景點" android:layout_marginTop="80dp"/> <CheckBox android:id="@+id/checkBox1" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <CheckBox android:id="@+id/checkBox2" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <CheckBox android:id="@+id/checkBox3" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="40dp" android:text="確認" android:layout_marginTop="20dp" android:onClick="btn_onClick"/> </LinearLayout>

activity 關閉后,cordovaPlugin 插件將 調用回調函數 onActivityResult(int requestCode, int resultCode, Intent intent),回調函數中可根據 resultCode 參數判斷處理情況,根據不同的結果對intent 中的返回值 bundler 對象進行不同處理。 最后使用 callbackContext 對象中的 success(string) 方法把處理結果回傳到頁面;
處理結果:

回到目錄
本章小結
Cordova(PhoneGap) 技術使用了CordovaPlugin 插件化(模塊化)技術,使用不同插件對不同HTML5頁面進行分別處理。與此同時,系統也可以利用插件調用系統已有的地圖、通信錄、瀏覽器等多個API, 與 HTML5 頁面進行信息交換,真正實現HTML5與Android、iOS系統的無縫對接。
參考文章
Cordova(PhoneGap)通過CordovaPlugin插件調用 Activity 實例
最新版Cordova 5.1.1(PhoneGap)搭建開發環境
Apache2.2+Tomcat7.0整合配置詳解
Windows Server 2008 R2 負載平衡入門篇
作者:風塵浪子
http://www.cnblogs.com/leslies2/p/cordovaPlugin.html
原創作品,轉載時請注明作者及出處
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。