创建第一个Helloworld项目,现在来分析运行机制
MainActivity.java
我们已经将MainActivity导入到了eclipse中。打开scr下com.example.hello下的MainActivity.java
public class MainActivity extends CordovaActivity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// enable Cordova apps to be started in the background
Bundle extras = getIntent().getExtras();
if (extras != null && extras.getBoolean("cdvStartInBackground", false)) {
moveTaskToBack(true);
}
// Set by <content src="index.html" /> in config.xml
loadUrl(launchUrl);
}
}
loadUrl(launchUrl);会在当前的WebView中去加载首页,当然这个首页是我们自己配置的,在res/xml/config.xml中。<content src="index.html" />。这个路径都是指的assets/www下的路径。
这样这个app启动的时候会首先调用这个MainActivity(当然这是在AndroidManifest.xml中配置的),然后Activity启动的时候会将index.html加载在其WebView中,然后我们就看到了Cordova的页面。
index.html
...
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
...
在显示这个index页面的时候,会加载两个js文件。cordova.js就是cordova的api,调用原生内容用的,相当于jar包。
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(背景是绿色)
网友评论