上一章我们介绍了如何创建一个cordova android项目,这章我们介绍一下创建的那个helloworld项目的代码,分析其运行。
MainActivity.java
我们已经将MainActivity导入到了eclipse中。打开scr下com.example.hello下的MainActivity.java。
//MainActivity继承了CordovaActivity
public class MainActivity extends CordovaActivity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Set by
loadUrl(launchUrl);
}
}
学过安卓的都知道,Activity在启动的时候会首先调用onCreate方法。
loadUrl(launchUrl);会在当前的WebView中去加载首页,当然这个首页是我们自己配置的,在res/xml/config.xml中。
这样这个app启动的时候会首先调用这个MainActivity(当然这是在AndroidManifest.xml中配置的),然后Activity启动的时候会将index.html加载在其WebView中,然后我们就看到了Cordova的页面。
index.html
我们再来看看index.html中都有什么内容。
Apache Cordova
Connecting to Device
Device is Ready
在显示这个index页面的时候,会加载两个js文件。cordova.js就是cordova的api,调用原生内容用的,相当于jar包。
index.js
再看这个index.js。
var app = {
// 初始化方法,会调用绑定事件的方法
initialize: function() {
this.bindEvents();
},
// 绑定事件的方法,事件可以是这些:
// 'load', 'deviceready', 'offline', and 'online'.
//该事件是在 cordova 载入完成后发生的事件,它表示cordova 加载完成并准备访问,yourCallbackFunction,相当于程序的入口功能
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
// deviceready 后事件处理
onDeviceReady: function() {
app.receivedEvent('deviceready');
},
// 事件处理,更新DOM,改变两个元素的css
receivedEvent: function(id) {
var parentElement = document.getElementById(id);
var listeningElement = parentElement.querySelector('.listening');
var receivedElement = parentElement.querySelector('.received');
listeningElement.setAttribute('style', 'display:none;');
receivedElement.setAttribute('style', 'display:block;');
console.log('Received Event: ' + id);
}
};
//调用初始化方法
app.initialize();
加载index.js之后,程序会首先调用初始化方法,初始化的时候会去绑定事件监听:document.addEventListener('deviceready', this.onDeviceReady, false);
deviceready事件,该事件是在 cordova 载入完成后发生的事件,它表示cordova 加载完成并准备访问,你传进去的回调函数,相当于程序的入口函数。
当cordova准备好的时候,会去首先执行你传进去的回调函数,这里是onDeviceReady()。这个方法会改变DOM元素的css样式。
最终效果就是,当cordova没有加载完的时候,页面上Apache Cordova下面那里显示的是:Connecting to Device(背景是灰色)。加载完之后,cordova准备好之后,原来显示的消失,现在显示的是:Device is Ready(背景是绿色)
相关阅读
发表评论