Check internet connectivity in mobile application using phonegap - javascript

On creating the mobile app in phonegap, I would like to show an alert message regarding internet connectivity as online / offline. But I do not get the alert message. I used
cordova-plugin-network-information
plugin with the code below on my js file
<script type="text/javascript">
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]); </script>
Can any one help me with the solution?

First Add the below Cordova Plugins:
cordova plugin add cordova-plugin-network-information
cordova plugin add cordova-plugin-dialogs
Add Below cript files:
jquery.mobile-1.4.0.css jquery-1.10.2.min.js cordova.js
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" name="viewport"
content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no, width=device-width">
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="format-detection" content="telephone=no">
<link rel="stylesheet" href="css/jquery.mobile-1.4.0.css" />
<script src="cordova.js"></script>
<script type="text/javascript" src="js/jquery-1.10.2.min.js">
</script>
<script>
$(document).ready(function () {
document.addEventListener("deviceready", onDeviceReady, false);
document.addEventListener("online", onOnline, false);
document.addEventListener("offline", onOffline, false);
function onDeviceReady() {
console.log(" ready");
}
function onOnline() {
console.log("connected");
}
function onOffline() {
debugger;
console.log("lost connection");
navigator.notification.alert(
'Please Check your internet connection.', // message
null, // callback
'Sample', // title
'OK' // buttonName
);
}
});
</script>
</head>
<body>
<p style="top:100px;"> Sample</p>
</body>
</html>
Output:
For More Details Click Here..!

You have to make sure that document has loaded before adding the above code. Do something like this in your HTML:
<body onload="onLoad">
and in your script/JS file do something like this:
function onLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
}
function onDeviceReady() {
//call your internet connectivity code here...
}

Related

Cordova File Opener Failing to Find File

I'm trying to use cordova-plugin-file-opener2 to load a pdf in Cordova. I can't seem to get it to work in the browser or on Android.
Here is my app.js file:
(function () {
document.querySelector('#file-button').addEventListener('click', openFile);
function openFile(){
console.log('opening file');
console.log(cordova.file.applicationDirectory);
var fileName = 'www/assets/pdf/foo.pdf';
var pathToFile = cordova.file.applicationDirectory + fileName;
window.resolveLocalFileSystemURL(pathToFile, function (entry) {
cordova.plugins.fileOpener2.open(
entry.toInternalURL(),
'application/pdf', {
error: function (e) {
alert.log('Error status: ' + e.status + ' - Error message: ' + e.message);
},
success: function () {
alert.log('file opened successfully');
}
}
);
}, function (e) {
alert('File Not Found');
});
}
}());
And here's the html:
<!DOCTYPE html>
<html>
<head>
<script src="cordova.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
</head>
<body>
<p><button id="file-button" class="help-btn">Help</button></p>
<div class='header'><h1>Directory</h1></div>
<div class='search-view'>
<input class='search-key' type="search" placeholder="Enter name"/>
<ul class='list employee-list'></ul>
</div>
<script src="lib/jquery.js"></script>
<script src="js/services/memory/EmployeeService.js"></script>
<script src="js/app.js"></script>
</body>
</html>
When the 'file-button' is clicked, it triggers the openFile function.
This shows me the following in the console:
adding proxy for Device cordova.js:1010:9
adding proxy for File cordova.js:1010:9
opening file app.js:6:9
"http://localhost:8000/" app.js:7:9
And the alert message says 'File not found'.
App.js is located in www --> js
foo.pdf is located in www --> assets --> pdf

Cordova OneSignal Plugin won't getIds properly

I got a small problem with the onesignal plugin for cordova.
When I'm running the app for the first time on wifi it won't get user's ids if I switch on mobile data it works just fine, after this works on wifi too.
This is the error i get on onesignal debugger:
Index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport"
content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<title>My App</title>
</head>
<body>
Test
</body>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
</html>
Index.js
var app = {
initialize: function()
{
this.bindEvents();
},
dump: function (obj) {
var out = '';
for (var i in obj) {
out += i + ": " + obj[i] + "\n";
}
alert(out);
},
bindEvents: function()
{
document.addEventListener('deviceready', this.onDeviceReady, false);
},
onDeviceReady: function()
{
app.receivedEvent('deviceready');
},
receivedEvent: function(id)
{
alert('init');
window.plugins.OneSignal
.startInit('onesignalid', 'googleproject')
.inFocusDisplaying(window.plugins.OneSignal.OSInFocusDisplayOption.Notification)
.handleNotificationOpened(app.notificationOpenedCallback)
.endInit();
app.getIds();
},
getIds: function()
{
window.plugins.OneSignal.getIds(function(ids){
app.dump(ids);
$.post('http://example.com/app_register_notif', {uid:'4764',onesignalid: ids.userId,onesignaltoken: ids.pushToken});
});
}
};
app.initialize();
The SERVICE_NOT_AVAILABLE is returned from Google Play services when it can't connect to get a registration id needed for push notifications. Your wifi network might be blocking a connection to Google if your cell connection works fine.
See the following stack overflow answer for more details.
https://stackoverflow.com/a/18325226/1244574

Websocket not working in android app using phonegap

I am trying to establish a websocket connection between my signalR server and an android app, built using the phonegap CLI.
The javascript code runs on browsers on my PC but when I package it for android it fails to connect and gives the following error: Error during negotiation request
Here is the javascript code -
<!DOCTYPE html>
<html>
<head>
<title>My New Application</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no;" />
<script type="text/javascript" src="js/jquery-1.7.1.js" ></script>
<script type="text/javascript" src="js/jquery.mobile-1.0.1.js"></script>
<script type="text/javascript" src="js/jquery.signalR-2.0.3.js"></script>
<script type="text/javascript" src="phonegap.js"></script>
<script type="text/javascript" src=http://WEB_ADDRESS.net/signalrPush/signalr/hubs"></script>
<script type="text/javascript">
$(function() {
alert('Phonegap device ready event...');
/*
var connection = $.hubConnection("http://WEB_ADDRESS.net/signalrPush/signalr", { useDefaultPath: false });
connection.error(function (error){
alert("SignalR error: " + error);
});
var pushhubProxy = connection.createHubProxy('pushhub');
pushhubProxy.on('sendmsg',function(message){ $('#ulServerMessages').append('<li>' + message + '</li>'); alert(message);});
connection.start({ transport: ['webSockets', 'longPolling'] }).done(function(){ alert('Now connected, connection ID=' + connection.id);})
.fail(function(){ alert('Could not connect'); });
*/
$.connection.hub.url = "http://WEB_ADDRESS.net/signalrPush/signalr";
var mypushHub = $.connection.pushhub;
if(typeof(mypushHub)=="object")
{
alert(typeof(mypushHub));
mypushHub.client.sendmsg = function (message) {
$('#ulServerMessages').append('<li>' + message + '</li>');
alert(message);
}
$.connection.hub.start({jsonp: true}).done(function () {
mypushHub.server.broadcastmsg();
}).fail(function (error) { alert(error); });
}
else
{
alert(typeof(mypushHub));
alert("Connection Prob");
}
});
</script>
</head>
<body>
<div data-role="header">
<h1>Get Server Data</h1>
</div>
<div id="pusheddata" style="width:300px; height:400px; overflow: auto;">
<ul id="ulServerMessages"></ul>
</div>
</body>
</html>
The asp.net code is hosted on azure.
I also tried to connect without the generated proxy(commented code) which again worked on chrome but not on the android emulator(4.4).
Could someone tell me what I am doing wrong?
Thanks
I am having the same problem as you.
Websocket is a feature within html5 and is not supported by all browsers
Chrome browser supports websockets but android 4.4 (jelly beans) In-browser doesn't.
This is why Android developed kitkat (which supports the websocket).
If you want to use websocket within android 4.2,4.4 (jelly beans), you have to use websocket cordova plugin like the one here
there are alot of others and I am just like you trying to find an answer

Simple way of displaying images from parse.com database using javascript

I was working on a very simple page which just pulls and displays images from a table in parse.com. I do not have much experience with javascript which might be evident from the code below.
I need the images to show up in a chronological order. With the current code, it works fine most of the times but is a little buggy.
There are 2 main problems:
1) Sometimes, randomly, one particular new image might not come on the top and instead show up somewhere in between.
2) This page works on Firefox and Chrome but NOT on IE.
Is there a better way to implement this or is there something that I should change? Any help would be appreciated.
Page source-
<!doctype html>
<head>
<meta charset="utf-8">
<title>My parse images</title>
<meta name="description" content="My Parse App">
<meta name="viewport" content="width=device-width">
<!-- <link rel="stylesheet" href="css/reset.css"> -->
<link rel="stylesheet" href="css/styles.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://www.parsecdn.com/js/parse-1.2.0.min.js"></script>
</head>
<body>
<div id="main">
<script type="text/javascript">
Parse.initialize("xxxxxxxxxxxxxxxxxx", "xxxxxxxxxxxxxxxx");
var config = {
parseAppId: 'xxxxxxxxxxxxxxxxxxx',
parseRestKey: 'xxxxxxxxxxxxxxxxxx',
streamName: 'parse-demo'
};
var getPhotos = function() {
var userImages = Parse.Object.extend("userImages");
var query = new Parse.Query(userImages);
query.find({
success: function(results) {
$('#photo-container').children().remove();
for(var i=results.length - 1; i>=0; i--){
var img = new Image();
img.src = results[i].get("image").url;
img.className = "photo";
document.body.appendChild( img );
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
};
function refresh (timeoutPeriod){
refresh = setTimeout(function(){window.location.reload(true);},timeoutPeriod);
}
$(document).ready(function() {
getPhotos();
// refresh(10000);
});
</script>
</body>
</html>
Internet Explorer blocks mixed content. Since Parse's JavaScript SDK requires SSL, you need to host your app using HTTPS as well in order to access it from IE.
Hey you made one mistake. it was not working for me. Then i found that it is url() not url.
The amendment is img.src = results[i].get("image").url();
<!doctype html>
<head>
<meta charset="utf-8">
<title>My parse images</title>
<meta name="description" content="My Parse App">
<meta name="viewport" content="width=device-width">
<!-- <link rel="stylesheet" href="css/reset.css"> -->
<link rel="stylesheet" href="css/styles.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://www.parsecdn.com/js/parse-1.2.0.min.js">
</script>
</head>
<body>
<div id="main">
<script type="text/javascript">
Parse.initialize("xxxxxxxxxxxxxxxxxx", "xxxxxxxxxxxxxxxx");
var config = {
parseAppId: 'xxxxxxxxxxxxxxxxxxx',
parseRestKey: 'xxxxxxxxxxxxxxxxxx',
streamName: 'parse-demo'
};
var getPhotos = function() {
var userImages = Parse.Object.extend("userImages");
var query = new Parse.Query(userImages);
query.find({
success: function(results) {
$('#photo-container').children().remove();
for(var i=results.length - 1; i>=0; i--){
var img = new Image();
img.src = results[i].get("image").url();
img.className = "photo";
document.body.appendChild( img );
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
};
function refresh (timeoutPeriod){
refresh = setTimeout(function(){window.location.reload(true);},timeoutPeriod);
}
$(document).ready(function() {
getPhotos();
// refresh(10000);
});

PhoneGap Device ready not firing in ios but working fine in android emulator and ripple

Hey Guys I have a problem firing the deviceready on ios, but the code work just find on adnroid emulator and also ripple i dont know what could be the problem. i didnt try it on a readl android device but the emulator works fine, but i have tried it on iphone 5 which never call the device ready.i have another question also is it true that there is different js files for cordova for different platforms ?
var deviceReadyDeferred = $.Deferred();
var jqmReadyDeferred = $.Deferred();
document.addEventListener("deviceReady", deviceReady, false);
document.addEventListener("resume", deviceResume, false);
function deviceResume() {
doWhenBothFrameworksLoaded();
}
function deviceReady() {
deviceReadyDeferred.resolve();
}
$(document).one("mobileinit", function() {
jqmReadyDeferred.resolve();
});
$.when(deviceReadyDeferred, jqmReadyDeferred).then(
doWhenBothFrameworksLoaded);
function doWhenBothFrameworksLoaded() {
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';
if (networkState == Connection.NONE)
alert('You have to be connected to the internet in order to use this app.');
else {
setTimeout(function(){
$.mobile.changePage("deals.html", {
transition : "pop",
reverse : false,
changeHash : false
});
},1000);
}
}
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>PhoneGap</title>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script type="text/javascript" charset="utf-8" src="cordova-2.6.0.js"></script>
<script type="text/javascript" charset="utf-8" src="PushNotification.js"></script>
<script type="text/javascript" charset="utf-8" src="js/jquery.min.js"></script>
<script type="text/javascript" charset="utf-8" src="controller/index.js"></script>
<script type="text/javascript" charset="utf-8" src="js/jqueryMobile.js"></script>
<script type="text/javascript" charset="utf-8" src="js/handlebars.js"></script>
<script type="text/javascript" charset="utf-8" src="js/handleHelpers.js"></script>
<script type="text/javascript" charset="utf-8" src="js/jquery.timeago.js"></script>
<link rel="stylesheet" href="css/jqm.css" charset="utf-8" />
<link rel="stylesheet" href="css/style.css" charset="utf-8" />
</head>
<body>
<div class="container splash" data-role="page" id="index">
<img src="img/logo.png" />
</div>
</body>
</html>
In order to use phonegap along with jquery mobile, you need to use it like this,
$(document).one("mobileinit", function() {
$.support.cors = true;
$.mobile.allowCrossDomainPages = true;
jqmReadyDeferred.resolve();
});
It turned out the i had to delete the cordova js file from the directory and specify that on the config.xml for phonegap build . Thanks all

Categories

Resources