前言
您app
需要 Internet 连接才能运行,因此您应该检查是否device
已连接internet
。为此,您可以创建一个utility
函数(比如hasConnection
),它boolean true
在 Internet 连接或boolean false
没有 Internet 连接时返回。
hasConnection
功能_
function hasConnection() {
var networkState = navigator.network.connection.type;
if(networkState === Connection.NONE) {
return false;
}
return true;
}
并且根据hasConnction
返回值,您可以做出正确的决定。
示例
document.addEventListener('deviceready',onDeviceReady, false);
function onDeviceReady(){
if(!hasConnection()){ //there is no internet connection
navigator.notification.alert(
'No Internet Connection!', // message
function(){
/*
If you are using jQuery mobile for UI you can create a seperate page #no-connection-page and display that page :
$.mobile.changePage('#no-connection-page',{'chageHash':false});
*/
}, // callback
'Connection Required', // title
'OK' // buttonName
);
return false;
} else {
//There is internet Connection, get the data from server and display it to the end user
//Again, If you are using jQuery mobile, display the page that should be displayed only when Internet Connection is available
//$.mobile.changePage('#has-connection-page');
}
/*
If the device is connected to the internet while your app is running,
you can add a listener for 'online' event and take some action. For example :
*/
document.addEventListener('online', function(){
//Now the device has internet connection
//You can display the '#has-connection-page' :
//$.mobile.changePage('#has-connection-page');
});
//You can use the listener for 'offline' event to track the app if the connection has gone while the app is running.
}
一注
确保您有:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
在 android 清单中。
最后
我也在创建android app
使用Phonepage
/Cordova
并且jQuery-mobile
需要互联网连接并使用这种方法,对我来说工作正常。我希望它对你有帮助。