2015-06-05 8 views
1

Я делаю неродное приложение в Phonegap, и я хочу знать, когда у меня есть соединение или нет. Поиск в WEB, я нашел способ узнать, получаю ли я подключение в своем приложении, но я реализовал в своем коде и не работал.Проверьте подключение к приложению Phonegap

Путь я нашел это:

document.addEventListener("deviceready", onDeviceReady, false); 

     // PhoneGap is loaded and it is now safe to make calls PhoneGap methods 
     function onDeviceReady() { 
      check_my_Connection(); 
     } 

     function check_my_Connection() { 
      var networkState = navigator.network.connection.type; 

      var states = {}; 
      states[Connection.UNKNOWN] = 'Unknown connection'; 
      states[Connection.ETHERNET] = 'Ethernet connection'; 
      states[Connection.WIFI]  = 'WiFi connection'; 
      states[Connection.CELL_2G] = 'Cell 2G connection'; 
      states[Connection.CELL_3G] = 'Cell 3G connection'; 
      states[Connection.CELL_4G] = 'Cell 4G connection'; 
      states[Connection.NONE]  = 'No network connection'; 

      alert('Connection type: ' + states[networkState]); 
     } 

И я вызываю функцию onDeviceReady() в ready функции моего сценария, как это:

<script type="text/javascript"> 

    $(document).ready(function(){ 
      /*other code*/ 
      onDeviceReady(); 
     /*other chode*/ 
    }); 

    /*other code functions*/ 
    /*Before the rest of the code, I added the snippet code above of this*/ 

    document.addEventListener("deviceready", onDeviceReady, false); 
    ... 
</script> 

Я читал, что мне нужно cordova.js, но PhoneGap Desktop App (бета-версия) не создала его. Этот JS-файл должен выполнять эту работу? Существует другой способ обнаружить соединение в приложениях Phonegap, не используя jQueryUI или jQueryMobile? Мне нужно сделать некоторые изменения в некоторых файлах моего проекта?

Буду признателен за любую помощь или любой способ сделать это.

P. S .: извините, что за мой английский.

+0

Я ответил здесь http://stackoverflow.com/questions/30482845/navigator-online-not-working-cordova- подобный вопрос 5-0-0/30483272 # 30483272 – AshBringer

+0

@BipBip Где я могу найти эту строку: 'document.addEventListener (« offline », function() {alert (« No connection found »)}, false);' –

+0

Вы можете поставить это везде, где вы хотите на своей странице html – AshBringer

ответ

0

Проблема должна быть внутри вашего кода. Просто выполните следующие действия, чтобы получить состояние соединения:

  1. Откройте ваш терминальный/консоль
  2. cordova create networkInformation com.example.com networkInformation
  3. cd networkInformation
  4. cordova platform add android
  5. cordova plugin add cordova-plugin-network-information
  6. cordova build

Закончив этот процесс, вы откроете созданную папку на рабочем столе. Перемещение внутри папки www внутри platform ->android папка под assets. Откройте index.js, который должен выглядеть следующим образом:

/* 
* Licensed to the Apache Software Foundation (ASF) under one 
* or more contributor license agreements. See the NOTICE file 
* distributed with this work for additional information 
* regarding copyright ownership. The ASF licenses this file 
* to you under the Apache License, Version 2.0 (the 
* "License"); you may not use this file except in compliance 
* with the License. You may obtain a copy of the License at 
* 
* http://www.apache.org/licenses/LICENSE-2.0 
* 
* Unless required by applicable law or agreed to in writing, 
* software distributed under the License is distributed on an 
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 
* KIND, either express or implied. See the License for the 
* specific language governing permissions and limitations 
* under the License. 
*/ 
var app = { 
    // Application Constructor 
    initialize: function() { 
     this.bindEvents(); 
    }, 
    // Bind Event Listeners 
    // 
    // Bind any events that are required on startup. Common events are: 
    // 'load', 'deviceready', 'offline', and 'online'. 
    bindEvents: function() { 
     document.addEventListener('deviceready', this.onDeviceReady, false); 
    }, 
    // deviceready Event Handler 
    // 
    // The scope of 'this' is the event. In order to call the 'receivedEvent' 
    // function, we must explicitly call 'app.receivedEvent(...);' 
    onDeviceReady: function() { 
     app.receivedEvent('deviceready'); 
    }, 
    // Update DOM on a Received Event 
    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(); 

Так что теперь ищет

onDeviceReady: function() { 
    app.receivedEvent('deviceready'); 
}, 

И изменить его к этому:

onDeviceReady: function() { 
    app.receivedEvent('deviceready'); 
    checkConnection(); 
}, 

Также добавьте

function checkConnection() { 
    var networkState = navigator.connection.type; 

    var states = {}; 
    states[Connection.UNKNOWN] = 'Unknown connection'; 
    states[Connection.ETHERNET] = 'Ethernet connection'; 
    states[Connection.WIFI]  = 'WiFi connection'; 
    states[Connection.CELL_2G] = 'Cell 2G connection'; 
    states[Connection.CELL_3G] = 'Cell 3G connection'; 
    states[Connection.CELL_4G] = 'Cell 4G connection'; 
    states[Connection.CELL]  = 'Cell generic connection'; 
    states[Connection.NONE]  = 'No network connection'; 

    alert('Connection type: ' + states[networkState]); 
} 

непосредственно выше app.initialize();

Это должен быть ваш полный index.js. Просто запустите приложение и оно будет оповещать вас ваше состояние сети:

/* 
* Licensed to the Apache Software Foundation (ASF) under one 
* or more contributor license agreements. See the NOTICE file 
* distributed with this work for additional information 
* regarding copyright ownership. The ASF licenses this file 
* to you under the Apache License, Version 2.0 (the 
* "License"); you may not use this file except in compliance 
* with the License. You may obtain a copy of the License at 
* 
* http://www.apache.org/licenses/LICENSE-2.0 
* 
* Unless required by applicable law or agreed to in writing, 
* software distributed under the License is distributed on an 
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 
* KIND, either express or implied. See the License for the 
* specific language governing permissions and limitations 
* under the License. 
*/ 
var app = { 
    // Application Constructor 
    initialize: function() { 
     this.bindEvents(); 
    }, 
    // Bind Event Listeners 
    // 
    // Bind any events that are required on startup. Common events are: 
    // 'load', 'deviceready', 'offline', and 'online'. 
    bindEvents: function() { 
     document.addEventListener('deviceready', this.onDeviceReady, false); 
    }, 
    // deviceready Event Handler 
    // 
    // The scope of 'this' is the event. In order to call the 'receivedEvent' 
    // function, we must explicitly call 'app.receivedEvent(...);' 
    onDeviceReady: function() { 
     app.receivedEvent('deviceready'); 
     checkConnection(); 
    }, 
    // Update DOM on a Received Event 
    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); 
    } 

}; 

function checkConnection() { 
    var networkState = navigator.connection.type; 

    var states = {}; 
    states[Connection.UNKNOWN] = 'Unknown connection'; 
    states[Connection.ETHERNET] = 'Ethernet connection'; 
    states[Connection.WIFI]  = 'WiFi connection'; 
    states[Connection.CELL_2G] = 'Cell 2G connection'; 
    states[Connection.CELL_3G] = 'Cell 3G connection'; 
    states[Connection.CELL_4G] = 'Cell 4G connection'; 
    states[Connection.CELL]  = 'Cell generic connection'; 
    states[Connection.NONE]  = 'No network connection'; 

    alert('Connection type: ' + states[networkState]); 
} 


app.initialize(); 
+0

Я не использую консоль для создания проекта, я использую приложение Desktop Phonegate, но я понимаю, что при создании приложения это создается, когда все файлы работают хорошо (я полагаю). Я проверяю файл 'index, js', тот же, что и вы показываете, но последняя строка отсутствует (' app.initialize() 'находится в моем' index.html'. Я проверил свой 'config.xml 'и у меня есть строка' '. С этим достаточно проверить подключение в моем приложении? –