Android基於cordova3.3的外掛程式開發

來源:互聯網
上載者:User

標籤:android cordova

  最近工作的項目,需要用到cordova進行外掛程式開發,具體Cordova的作用,就不再贅述,大家可以自行的去百度就OK了,直接開始。具體的流程,我將已一個小的Demo進行推進講解。也是剛剛接觸,太理論的基礎東西我也說不好,還是先跑起來一個Demo,才有繼續學下去的動力~大家多多指教~

  Step1.準備工作:

    首先將我提供的Demo執行個體包中的HelloWorld-CordovaLib引入到工作空間中,我是使用的Eclipse,接著建立工程MultiImageChooser,同時將HelloWorld-CordovaLib作為Library引入到MultiImageChooser中:

         

    接著,按照Demo執行個體包中的目錄結構,引入Cordova所需要的檔案,完成後的目錄結構如下所示:

                

    其中,res檔案夾下還有一個xml檔案夾,記得一併拷過去哦~

    截至到現在,基本的準備工作就算是完成了。


Step2.外掛程式的開發

    外掛程式的編寫,是為了讓JS可以調用我的Activity,其實編寫起來還是比較簡單的。

    a.在src目錄下建立包plugins,編寫外掛程式類Plugin_intent 

    

package plugins;import org.apache.cordova.CallbackContext;import org.apache.cordova.CordovaPlugin;import android.content.Intent;import android.util.Log;import android.widget.Toast;import com.wenjoy.dojo.ResponseJSON;import com.wenjoy.multiimagechooser.MainActivity;/** * js調用java方法 *  * 必須繼承CordovaPlugin CordovaPlugin裡面有實現cordovaActivity的方法 * 提供startActivityForResult(); *  * 我使用的 cordova 3.3.0版本 *  * @author XueQi *  */public class Plugin_intent extends CordovaPlugin {private String infos;/** * 注意 構造方法不能為 *  * Plugin_intent(){} *  * 可以不寫或者 定義為如下 *  */public Plugin_intent() {}CallbackContext callbackContext;@Overridepublic boolean execute(String action, org.json.JSONArray args,CallbackContext callbackContext) throws org.json.JSONException {this.callbackContext = callbackContext;Log.i("123", action);if (action.equals("intent")) {// 擷取JS傳遞的args的第一個參數infos = args.getString(0);this.function();return true;}return false;}// 方法執行體private void function() {// cordova.getActivity() 擷取當前activity的thisLog.i("123", cordova.getActivity().toString());Intent intent = new Intent(cordova.getActivity(), MainActivity.class);intent.putExtra("infos", infos);cordova.startActivityForResult((CordovaPlugin) this, intent, 200);}@Overridepublic void onActivityResult(int requestCode, int resultCode, Intent intent) {super.onActivityResult(requestCode, resultCode, intent);// 傳遞傳回值 給js方法callbackContext.success(com.alibaba.fastjson.JSONArray.toJSONString(ResponseJSON.getInstance().getJsonObjects()));if (ResponseJSON.getInstance().getJsonObjects() != null&& ResponseJSON.getInstance().getJsonObjects().size() > 0) {Toast.makeText(cordova.getActivity(), "恭喜,上傳完成", 1000).show();}}}

    b.方法編寫完成後,要在res/xml/config.xml下註冊,寫在widget標籤中添加

 <feature name="Demo">        <param name="android-package" value="plugins.Plugin_intent" /><!-- value:包名.類名 --> </feature>
    feature的name很重要,一會在JS中要用到。

    

    c.編寫外掛程式JS檔案,在assert/www/plugins下,建立intent.js檔案

cordova.define("org.apache.cordova.intent", function(require, exports, module) { /* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements.  See the NOTICE file * distributed with this work for additional information * regarding copyright ownership.  The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License.  You may obtain a copy of the License at * *   http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied.  See the License for the * specific language governing permissions and limitations * under the License. **/var exec = require('cordova/exec');/** * Provides access to the vibration mechanism on the device. */module.exports = {    /**     * 一共5個參數       第一個 :成功會掉       第二個 :失敗回調       第三個 :將要調用的類的配置名字(在config.xml中配置 稍後在下面會講解)       第四個 :調用的方法名(一個類裡可能有多個方法 靠這個參數區分)       第五個 :傳遞的參數  以json的格式     */    demo: function(mills) {        exec(function(winParam){        alert(winParam);<span style="font-family: Arial, Helvetica, sans-serif;">//執行成功,winParam是類中callbackContext.success傳遞的參數</span>        }, null, "Demo", "intent", [mills]);    },};});
    demo:定義被JS調用的方法名

    Demo:就是我們剛才在config.xml中配置的外掛程式類的名字

    mills:這裡我始終只能傳遞一個參數,所以,我現在的解決方式是拼接一個字串,例如:‘aaa,nnn,ccc‘,用逗號分割三個參數

Step3.使用外掛程式

    截止到現在,整個外掛程式就OK啦,可以建立一個html和Activiry了,這裡我只列出LUNCH Activity的編寫和html頁面

    在assert/www下建立index.html檔案,很簡單

<!DOCTYPE html><html>  <head>     <title>Notification Example</title>   <script type="text/javascript" charset="utf-8" src="cordova.js"></script>      <script type="text/javascript" charset="utf-8">       // Wait for device API libraries to load       //       document.addEventListener("deviceready", onDeviceReady, false);       // device APIs are available       //    //     跳轉    function intent() {          navigator.intent.demo('NDljY2E1ZGM4NzUzM2U3Yg==,order,5740');    }    //token,eneityname,entityid    </script>      </head>      <body>        <p><a href="#" onclick="intent(); return false;">Upload Image</a></p>      </body>    </html>

    ViewActivity:

package com.wenjoy.multiimagechooser;import org.apache.cordova.CordovaActivity;import android.content.Intent;import android.os.Bundle;/** * 裝載HTML頁面的Activity *  * @author XueQi *  */public class ViewActivity extends CordovaActivity {@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);super.init();// Set by <content src="index.html" /> in config.xmlsuper.loadUrl("file:///android_asset/www/index.html");// super.loadUrl("file:///android_asset/www/index.html")}@Overrideprotected void onActivityResult(int requestCode, int resultCode,Intent intent) {super.onActivityResult(requestCode, resultCode, intent);}}


  最後,至於許可權什麼的,大家就自己添加好了。


  大工告成!附上DEMO的,要1個積分,大家不要吐槽~ http://download.csdn.net/detail/xq328220454/7620119


        

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.