如何在android studio中cordova的混合開發

基於Android Studio 中Cordova的開發
cordova簡介
Cordova的前身是PhoneGap 官網: (http://cordova.io)
Cordova應是運行在客戶端本地應用容器的web應用。所以,運行在Cordova容器中的Html5應用的結構和傳統的基於web服務器的有所不一樣。傳統的web應用中服務器端作了大部分工做,好比按照用戶請求傳回生成的內容。而Cordova這種容器中的應用自己包括了所須要的靜態頁面,用戶請求通常由js代碼響應並與服務器交互,這樣與服務器交互的內容會比較少。而且因爲html5自己的特性(如本地存儲)或容器的API,容器的應用能夠脫離服務器運行。
cordova安裝
先安裝JDK 
下載地址:(http://www.oracle.com/technetwork/java/javase/downloads/index.html)

安裝SDK 
下載地址:(http://developer.android.com/sdk/index.html)

CLI(command-line interface,命令行界面)的安裝 
CLI是用JavaScript寫的,而且是用Node.js做爲運行時執行引擎。因此須要先安裝Node.js(http://nodejs.org/download/),在安裝過程當中,CLI要獲取一些GitHub的代碼,因此要安裝Git(https://git-scm.com/downloads);

當Node.js和Git都安裝好後,在Git中命令行中輸入:

npm install -g cordova
1
完成cordova的安裝。

完成了cordova安裝的基本配置,能夠去了解一下CLI的經常使用命令,網上有不少(https://blog.csdn.net/guoscy/article/details/79202794)。經過命令建立一個android工程,添加android平臺,添加WhitelistPlugin白名單插件,至今生成的android工程中就有了咱們可移植到android studio中的一些核心文件。注意用Cordova CLI工具新建一個項目(不要使用 cordova build 命令進行編譯,否則導入android studio中失敗)

能夠根據本身的須要添加cordova提供的豐富系統插件(用命令行添加很容易),也能夠本身去寫自定義插件。

cordova集成到android studio
將這個 工程集成到android studio中最關鍵的是CordovaLib 、www、(platform_www、cordova )、res下的中的配置文件config.xml;

CordovaLib以Moudle的形式導入工程,並依賴於主工程;

www放在工程目錄assets文件夾下;

platform_www、cordova是主要用於CordovaCLI命令行類的,主要用於build後的做用;(導不到導入AS均可以)

咱們自定義插件主要在www、和工程src下進行編寫;

大體的結構圖

 





如今咱們就能夠在工程下建一個文件夾,專門管理咱們自定義的插件,進行開發。
cordova下自定義插件
以定義一個Toast的插件爲例
在src下建立ToastPlugin.java的文件執行android原生的調用

    /** 
     * 顯示土司插件 
     * @author yuhailong 
     * 
     */  
public class ToastPlugin extends CordovaPlugin {
     @Override
    public boolean execute(String action, JSONArray args,
                           CallbackContext callbackContext) throws JSONException {
        //前端回調的方法名
        if ("showToast".equals(action)) {
             return executeShowToast(args, callbackContext);
        } else {
            callbackContext.error("發生異常,請檢查API使用是否正確");
            return false;
        }
     }

    /**
     * 顯示toast的原生方法
     */
    private void executeShowToast() {
        try {
             CordovaArgs cordovaArgs = new CordovaArgs(args);
             String text = cordovaArgs.getJSONObject(0).getString("text");
             android.widget.Toast.makeText(cordova.getActivity(), text,Toast.LENGTH_LONG).show();
             callbackContext.success();
             return true;
        } catch (Exception e) {
            e.printStackTrace();
            callbackContext.error("顯示toast異常");
            return false;
        }
    }
}




在config.xml中配置插件路徑

 <feature name="ToastPlugin">
        <param
            name="android-package"
            value="com.example.test.plugins.ToastPlugin" />
    </feature>

在asserts/www/plugins/目錄下插件本身的插件js文件 
如:asserts/www/platform/android/plugins/cordova-plugin-toast/toast.js
cordova.define( "com.example.test.plugins.ToastPlugin" , function(require, exports, module) {

        var exec = require('cordova/exec');

        /**
         * Provides access to notifications on the device.
         */
        module.exports = {
                /**
                 * Causes the device to beep.
                 * On Android, the default notification ringtone is played "count" times.
                 *
                 * @param {Integer} type       The Toast type.
                */
        showToast:function(successCallback,errorCallback,content){
           exec(successCallback, errorCallback, "ToastPlugin", "showToast", [content]);
        },
        };
    });

添加土司插件js配置信息,配置調用的方法名 
在assets/www/platform/android/cordova_plugins.js文件中添加以下信息:
,{        
        "file" : "plugins/cordova-plugin-toast/toast.js", 
        "id" : "com.example.test.plugins.ToastPlugin",        
        "clobbers" : ["navigator.webtoast"]//定義調用的方法
    }

前端插件中方法代碼調用(本地的調試)
在index.html文件中

<html>
<head>
    <!--
    Customize this policy to fit your own app's needs. For more guidance, see:
        https://github.com/apache/cordova-plugin-whitelist/blob/master/README.md#content-security-policy
    Some notes:
        * gap: is required only on iOS (when using UIWebView) and is needed for JS->native communication
        * https://ssl.gstatic.com is required only on Android and is needed for TalkBack to function properly
        * Disables use of inline scripts in order to mitigate risk of XSS vulnerabilities. To change this:
            * Enable inline JS: add 'unsafe-inline' to default-src
    -->
    <meta http-equiv="Content-Security-Policy"
          content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-  *">
    <meta http-equiv="Content-type" content="text/html; charset=utf-8">
    <meta name="format-detection" content="telephone=no">
    <meta name="msapplication-tap-highlight" content="no">
    <meta name="viewport"
          content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
    <link rel="stylesheet" type="text/css" href="css/index.css">
    <title>Hello World</title>
</head>
<body>
<div class="app">
    <h1>Apache Cordova</h1>

    <div id="deviceready" class="blink">
        <p class="event listening">Connecting to Device</p>
        <p class="event received">Device is Ready</p>
        <button id="myBtnOne" >Toast</button>
    </div>
</div>
<script type= "text/javascript" src="cordova.js"></script>
<script type= "text/javascript" src="js/index.js"></script>
<script type= "text/javascript" src="js/custom.js"></script>
</body>
</html>

相似在index.js文件夾下建立一個custom.js的文件,將js代碼寫在裏面,Toast這裏要注意的是彈框只能 經過id的查找了進行編輯; 
custom.js的文件以下:
function showToast(){
    navigator.webtoast.showToast(function(result){
              alert("success:"+result);

          },function(err){
              alert("error:"+err);
          },{
              text:'你好,我是 Toast~',
          });
}
document.getElementById("myBtnOne" ).addEventListener("click", showToast);

結束
整個cordova在android studio中的導入和自定義插件的開發流程,大體如上。具體的詳情能夠參照cordova的官方給的文檔和網上的一下資料。

我的理解cordova相比於RN仍是要容易上手些,cordova的核心仍是一個H5,相似原生是個瀏覽器的殼;RN是經過js映射原生的組件。因此感受交互上RN是要比cordova要好的,對於初學者要學的更多。固然二者都有其優點,要想深刻其核心都是要下一點功夫的。
--------------------- 
版權聲明:本文爲CSDN博主「那一年的梧桐雨」的原創文章,遵循CC 4.0 by-sa版權協議,轉載請附上原文出處連接及本聲明。
原文連接:https://blog.csdn.net/liugang921118/article/details/82345435
相關文章
相關標籤/搜索