嗨,我创建了应用程序,其中我从某些服务器获取数据,如果互联网没有连接,那么用户将无法使用应用程序。我把
document.addEventListener("deviceready", function(){ onDeviseReady(); }, false);
function onDeviseReady()
{
document.addEventListener("offline", offLine, false);
}
function offLine()
{
navigator.notification.alert(
'No Internet Connected',message,'Message','Done');
}
现在我应该在function message(){}
做什么,以便用户无法移动到此处,直到用户连接到互联网
我在消息功能中放入警报框但这不是我想要的
答案 0 :(得分:2)
<强>前言强>
您的app
需要运行Internet连接,因此您应该检查device
是否已连接到internet
。为此,您可以创建utility
函数(例如hasConnection
),该函数在互联网连接上返回boolean true
或在没有互联网连接时返回boolean false
。
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 Manifest中。
最后
我还使用android app
/ Phonepage
和Cordova
创建jQuery-mobile
,需要互联网连接并使用此方法,对我来说工作正常。我希望它可以帮助你。