2

嗨,我创建了应用程序,在该应用程序中,我从我想要的某个服务器获取数据,如果未连接互联网,则用户将无法使用该应用程序。我放

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(){}以便用户在用户连接到互联网之前无法移动到这里,我在消息功能中放入警报框,但这不是我想要的

4

1 回答 1

2

前言

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需要互联网连接并使用这种方法,对我来说工作正常。我希望它对你有帮助。

于 2013-09-06T17:28:19.787 回答