首先还是来张phoneGap的架构图
这副图讲了几个点:
1.UI是通过html,js,css来绘图的
2.底层Module是用object-C,java,C++等。phoneGap把web技术和编程语言相结合,phoneGap只用js封装了一部分的native API,例如camera,location等,具体业务逻辑还是要native去实现。
3.HTML rendering Engine是保证web和native module通信的桥梁,它会截取web发出请求,并执行native module,然后通过stringByEvaluatingJavaScriptFromString方法执行js方法,把native执行的结果返回到web。
/********************* 分割线 *******************/
具体上下调用过程我以调用native module中MyPlugin类为例,phoneGap具体实现流程如下:
1.native module端的创建。首先新建一个MyPlugin类,继承自CDVPlugin,实现xxx方法。并在config.xml的plugins标签中填写myplugin信息。
2.js端的创建。新建一个myPlugin.js,填写方法,执行cordava.exec(),参数是调用的native类名(字符串),方法名(字符串),执行成功时的回调,执行失败时的回调。原文如下:The JavaScript class invokes the native code using the Cordova.exec() function. When it invokes Cordova.exec , it can pass in a result handler function, an error handler function, and an array of parameters to be passed into native code, as well as a reference to the native class's name and native function name.
3.当web端开始调用cordava.exec()时,实际上会调用cordava-2.3.0.js中的iOSExec方法,主要是调用js中内置的xlmHttprequest对象(Xmlhttp是一种浏览器对象, 可用于模拟http的GET和POST请求。配合JavaScript可以实现页面数据在无刷新下的定时数据更新,如果应用在聊天室、文字直播上可以取得较好的视觉效果。),模拟发出一个请求,请求格式如下:xxxxxx。具体如下:
js iOSExec(),调用xmlhttp的setRequestHeader,发送http请求,被native捕获,canInitWithRequest,fetchCommandsFromJs(执行 JS nativeFetchMessages,从Js command queue中得到CommandJSON),把command放入队列中,开始执行command,比如camera,执行完毕后sendPluginResult,使用stringByEvaluatingJavaScriptFromString执行javascript,js执行nativeCallback,callbackFromNative。
4.html rendering engine(web view)会通过方法canInitxxxx截获这个请求,并通过参数,找到需要调用的类名和方法名并执行(通过ASIHttpReqeust获得HTTP response,JSON格式)。
5.当执行完毕后,通过webview的stringByEvaluatingJavaScriptFromString执行js的回调,web得到JSON后,可以通过JS内置的方法eval,把JSON解析成Object,然后在UI上展现出来
Note:需要注意
1.上述第4点不对,正确的使用phoneGap的方式是,RCP不用native的,应该是用js的网络模块,例如ajax,只有用本地服务例如camera,location等,才会用native。
2.phoneGap只是一个简单的跨平台框架,具体的内容还需要其他来填充,例如UI效果,要用到jQuery mobile,JQM封装了许多web app控件。
使用jQuery mobile需要引用3个文件
jquery-1.8.2.min.js
jquery.mobile-1.2.0.min.js
jquery.mobile-1.2.0.min.css
参考文献:
phoneGap的实现原理
参考PhoneGap源码分析 http://blog.csdn.net/cutesource/article/details/7784843
cordava-2.3.0.js文件的具体分析,可以参考
http://www.cnblogs.com/linjisong/archive/2012/08/08/2627938.html