phonegap 基础原理

phonegap是web app 下调用移动OS原生API的库。在整个压缩包结构中主要分三块:

1、cordova.js,前端的js库;功能是提供js的API接口,最终调用的是promp方法,如下:

/**
 * Implements the API of ExposedJsApi.java, but uses prompt() to communicate.
 * This is used only on the 2.3 simulator, where addJavascriptInterface() is broken.
 */

module.exports = {
    exec: function(service, action, callbackId, argsJson) {
        return prompt(argsJson, 'gap:'+JSON.stringify([service, action, callbackId]));
    },
    setNativeToJsBridgeMode: function(value) {
        prompt(value, 'gap_bridge_mode:');
    },
    retrieveJsMessages: function() {
        return prompt('', 'gap_poll:');
    }
};

2、cordova jar包

以android下为例,基本原理是通过重写webview下的onJsConfirm接口,如下:

public class CordovaChromeClient extends WebChromeClient
  public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result)
  {
    boolean reqOk = false;
    if ((url.startsWith("file://")) || (Config.isUrlWhiteListed(url))) {
      reqOk = true;
    }

    if ((reqOk) && (defaultValue != null) && (defaultValue.length() > 3) && (defaultValue.substring(0, 4).equals("gap:")))
    {
      try {
        JSONArray array = new JSONArray(defaultValue.substring(4));
        String service = array.getString(0);
        String action = array.getString(1);
        String callbackId = array.getString(2);
        String r = this.appView.exposedJsApi.exec(service, action, callbackId, message);
        result.confirm(r == null ? "" : r);
      } catch (JSONException e) {
        e.printStackTrace();
        return false;
      }

    }
通过exposedJsApi对象,以类似MML的设计模式,将前端不同的JS脚本转换成action,通过对应plugin处理。
3、config.xml 配置文件
用以配置需要用的插件,比如摄像头、文件、事件等等。
原文地址:https://www.cnblogs.com/Fredric-2013/p/4223076.html