I have created an android app that basically loads the responsive website via phonegap inappbrowser.
Now i want to fancy it up and make it more like an app. So my main problems are
When i try to load the app and somehow internet goes off, it displays the url of the website and says website not available. So i want to remove that and display my own custom message. Is that possible? What do i need to do for that?
Whenever user clicks on any menu item of the website from the app it gives a blank screen during the page transition/load. Now is there anyway i can show a loading sign every time they click on a menu item?
This is what i am using
<script type="text/javascript" charset="utf-8">
// Wait for Cordova to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is ready
//
function onDeviceReady() {
var ref = window.open('http://www.google.com', '_blank', 'location=yes');
ref.addEventListener('loadstart', function() { alert('start: ' + event.url); });
ref.addEventListener('loadstop', function() { alert('stop: ' + event.url); });
ref.addEventListener('loaderror', function(event) { alert('error: Please Check your Internet Connection. '); });
ref.addEventListener('exit', function() { alert(event.type); });
}
</script>
I am using dreamweaver to deal with the html section and phonegap build to compile my app.
I am fairly new at this so please elaborate.
function onDeviceReady()
{
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.NONE] = 'No network connection';
if(states[networkState]==states[Connection.NONE])
{alert('No Internet Connection! Please Turn on Wifi or Mobile Data to use this application');}
else
{
var ref = window.open('http://www.google.com', '_blank', 'location=yes');
ref.addEventListener('loadstart', function() { alert('start: ' + event.url); });
ref.addEventListener('loadstop', function() { alert('stop: ' + event.url); });
ref.addEventListener('loaderror', function(event) { alert('error: Please Check your Internet Connection. '); });
ref.addEventListener('exit', function() { alert(event.type); });
}
}
So what if the internet gets turned off in the middle of using the app? Would it work then too? If not then is there any way to get that done too?
Also can you please tell me where to apply the following codes that you had put on your response
navigator.notification.activityStart("Please Wait", "Its loading your homepage.....");
Below code will stop the loading popup :
navigator.notification.activityStop();
Thank you very much. I really am in need for these 2 solutions :(
Hi Finally for me works
onerror function is called when the browser hasn't internet.
onload function is called when exist a internet connection.
<body>
<script>document.write('<img src="http://static.forosdelweb.com/fdwtheme/logo-navidad.png?'+Math.random()+'" style="display:none" onload="alert("hay internet")" onerror="alert("no hay internet")" />');</script>
</body>
You can Check internet connection onDeviceReady function with following code.
function onDeviceReady()
{
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.NONE] = 'No network connection';
if(states[networkState]==states[Connection.NONE])
{alert('No Internet Connection! Please Turn on Wifi or Mobile Data to use this application');}
else
{
//load your pages
}
}
Now if you are loading responsive site then you need to specify loader in that responsive website. But in cordova you can use following code for loader
navigator.notification.activityStart("Please Wait", "Its loading your homepage.....");
Below code will stop the loading popup :
navigator.notification.activityStop();
Related
Using:
xcode 10.3
firebase plugin ( https://www.npmjs.com/package/cordova-plugin-fcm )
cordova version 8.1.2
The xcode console shows:
app enters background
Set state background
Disconnected from FCM
What do I have:
Push notification enable on the app(on https://developer.apple.com/)
All the keys/Certificates
I get the token identifier on the iphone, so I suppose it's working but I'm not sure since when you get a notification with the app opened it does show the notification ( Also if someone knows how to fix it, I would appreciate it) but my question is how to stop from disconnecting the FCM plugin when the app goes to background.
Only code I have
function onDeviceReady() {
// Handle the Cordova pause and resume events
document.addEventListener( 'pause', onPause.bind( this ), false );
document.addEventListener('resume', onResume.bind(this), false);
function checkConnection() {
var networkState = navigator.connection.type;
var states = {};
states[Connection.UNKNOWN] = 'Ligação desconhecida';
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] = 'Sem ligação a internet';
if (states[networkState] === states[Connection.NONE]) {
alert("A aplicação necessida de internet para funcionar correctamente");
}
}
FCMPlugin.getToken(function (token) {
myToken = token;
alert(token);
}, function (error) {
console.error(error);
});
}
I am using cordova 3.5.0 to develop my phonegap application . In that i want to check internet connectivity before web service calls . So i added network status plugin by using the command cordova plugin add org.apache.cordova.network-information . Plugin installed successfully in my application .
After Adding the plugins i added 2 EventListener's one for online and another for offline.
var app = {
// Application Constructor
initialize: function() {
console.log('App initializing...');
this.bindEvents();
},
// Bind Event Listeners
//
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindEvents: function() {
//This is to allow testing in desktop browser where there is no device ready event
if (navigator.userAgent.match(/(iPhone|iPod|iPad|Android|BlackBerry)/)) {
document.addEventListener('deviceready', this.onDeviceReady, false);
document.addEventListener("offline", onOffline, false);
document.addEventListener("online", onOnline, false);
} else {
this.onDeviceReady();
}
},
// deviceready Event Handler
//
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicity call 'app.receivedEvent(...);'
onDeviceReady: function() {
StatusBar.overlaysWebView(false);
app.receivedEvent('deviceready');
},
onOnline:function(){
console.log("Online");
}.
onOffline: function(){
console.log("Offline");
},
// Update DOM on a Received Event
receivedEvent: function(id) {
require(['router'], function(Router){
Router.getInstance();
console.log('Backbone callback...');
});
}
};
So i used another method to check online status as mentioned in Phonegap documentation
function checkConnection() {
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]);
}
which is always returning the mode am connected to internet for e.g "WiFi connection" . Though i changed my disconnected my internet connection .
Help me resolving this issue .
I had the same problem: the online/offline event was not firing, and sometimes when it went offline, the app crashed...
THE SOLUTION:
- The appropriate permission tag must bem IMMEDIATELY after the tag , in the AndroidManifest.xml file... it may appear ridiculous, but otherwise the event was not firing.
In the end, your file will look like:
<manifest android:hardwareAccelerated="true" android:versionCode="10000" android:versionName="1.0.0" android:windowSoftInputMode="adjustPan" package="br.com.burkard.app" xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:resizeable="true" android:smallScreens="true" android:xlargeScreens="true" />
Scope.
document.addEventListener("offline", this.onOffline, false);
document.addEventListener("online", this.onOnline, false);
I avoid using the network types, as I found they do not work consistently on all platforms.
Instead I use:
isOnline = function() {
try {
if (!navigator.onLine){
return false;
} else {
return true;
}
}
catch(e) {
alert('An error has occurred: '+e.message);
}
};
I would do to things.
First add the online and offline eventlisteners only in the onDeviceReady function,
Second, add scope to the onOffline and onOnline method calls in the event listeners.
Something like this:
if (navigator.userAgent.match(/(iPhone|iPod|iPad|Android|BlackBerry)/)) {
document.addEventListener('deviceready', this.onDeviceReady, false);
} else {
this.onDeviceReady();
}
},
onDeviceReady: function() {
StatusBar.overlaysWebView(false);
app.receivedEvent('deviceready');
document.addEventListener("offline", app.onOffline, false);
document.addEventListener("online", app.onOnline, false);
},
onOnline:function(){
console.log("Online");
}.
onOffline: function(){
console.log("Offline");
},
I am seeing a few different options to check internet connection with phonegap. There is document.addEventListener("online", onOnline, false); and there is also navigator.network.connection.type... but I am not sure which one is best practice. I would also like to be able to prevent the bad case where the phone is connected to a wifi network but has no internet connection.
$(document).on('pagecreate','#explanation-short', function(){
if ( isPhoneGap() ) {
if (checkConnection() == "none" ) {
connectionStatus = 'offline';
} else {
connectionStatus = 'online';
}
function checkConnection() {
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';
//console.log('Connection : ' + Connection);
//console.log('Connection type: ' + states[networkState]);
return networkState;
}
} else {
connectionStatus = navigator.onLine ? 'online' : 'offline';
}
console.log("connectionStatus : "+connectionStatus);
});
For example, this code works if the phone is connected to the wifi, but we are not sure the internet is actually available.
What are the best practices with phonegap 3.3+ and Jquery mobile 1.4 ?
The event,
document.addEventListener("online", onOnline, false);
is only fired when your app is already is loaded and regains a connection. This is not fired on start of the application.
Therefore, you have to use the checkConnection() method on start of your application and then if you need to check later while the app is running, you use the event listener.
Inside device ready function , I use the following lines to check for internet connection
if(navigator.connection.type==0)
{
alert('This application requires internet. Please connect to the internet.');
}
else if(navigator.connection.type=='none')
{
alert('This application requires internet. Please connect to the internet.');
}
else
{
//Hurray I'm online
}
Currently this is serving me quite well. But I still don't have that way to detect connected wifi,but no internet.I would also like to know how to detect that.
In Phonegap there are two event listeners 'online' & 'offline'. use them for fast response.Please check Example :
var internet;
document.addEventListener('online',online,false);
document.addEventListener('offline',offline,false);
function online(){
internet=true;
}
function offline(){
internet=false;
}
if(internet){
// internet is connected
}else{
// internet is not connected
}
for more details please visit http://docs.phonegap.com/en/3.0.0/cordova_events_events.md.html
Here is my code at the minute:
Using phonegap 2.9
<head>
</head>
<body>
<script charset="utf-8" src="js/cordova.js"></script>
<script>
document.addEventListener("deviceready", onDeviceReady, false);
document.addEventListener("online", onOnline, false);
document.addEventListener("offline", onOffline, false);
// PhoneGap is loaded and it is now safe to make calls PhoneGap methods
//
function onDeviceReady() {
console.log("Device Ready");
}
// Handle the online event
//
function onOnline() {
document.location = 'http://app.dadad.com';
}
function onOffline() {
console.log("Offline");
}
</script>
</body>
However right now I just get a white screen whether i'm connected or not. Eventually what I would like is to display some html when the user is not connected.
So in conclusion:
Would like to fix the function as it is not working
Would like to show html when not connected.
The Online/Offline events do not fire onload. They are there for when you are in app (complete load) and then lose or gain connection. I have gotten around this by doing an initial connection check on load, like this:
function checkConnetcion() {
var networkState = navigator.connection.type;
var states = {};
states[Connection.UNKNOWN] = false;
states[Connection.ETHERNET] = true;
states[Connection.WIFI] = true;
states[Connection.CELL_2G] = true;
states[Connection.CELL_3G] = true;
states[Connection.CELL_4G] = true;
states[Connection.CELL] = true;
states[Connection.NONE] = false;
var connectionStatus = states[networkState];
if(connectionStatus) {
//Do something if connected
}
else{
//Do something if not connected
}
}
Then add this your onready function:
// PhoneGap is loaded and it is now safe to make calls PhoneGap methods
//
function onDeviceReady() {
console.log("Device Ready");
checkConnetcion();
}
You can make use of Jquery ajax and send a dummy request before sending actual request. If you get and Error Code as '0' it means there is no internet connectivity.
$.ajax({
url: 'TestUrl',
type: 'GET',
success: function (data) {
// Go ahead with you request
},
error: function (x, y, z) {
if (x.status == 0) {
alert("Please connect to the internet");
}
else{
alert("Other Error Occured")
}
}
});
Secondly you can also make you of HTML 5 navigator
var condition = navigator.onLine ? "ONLINE" : "OFFLINE";
But it will show ONLINE when WIFI doesn't provide Internet connection.
Cordova connection object will also show WIFI if there is no internet connection
The following code works fine on a desktop browser exactly how it is, but isn't working in my phone gap/cordova app. My output says connect and iOS received stream, but nothing is showing up in the body of my app. This is in my index.js file:
var app = {
initialize: function() {
this.bindEvents();
},
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
onDeviceReady: function() {
app.receivedEvent('deviceready');
////////////////////////////////
//////Start of my opentok code////////////
var apiKey = '21692492';
var sessionId = '2_MX4yMTY5MTQ5Mn5-RnJpIEZlYiAwNyAwODozMjozOSBQU1QgMjAxNH4wLjIwMzc2MDV-';
var token = 'T1==cGFydG5lcl9pZD0yMTY5MTQ5MiZzaWc9ZWUxMTNjNjZiYjlkNWI4NTkwZTE2MDZiMjM0MzFkOWYyMzhiYzgxNjpzZXNzaW9uX2lkPTJfTVg0eU1UWTVNVFE1TW41LVJuSnBJRVpsWWlBd055QXdPRG96TWpvek9TQlFVMVFnTWpBeE5INHdMakl3TXpjMk1EVi0mY3JlYXRlX3RpbWU9MTM5MTc5MDgwNSZyb2xlPXB1Ymxpc2hlciZub25jZT0xMzkxNzkwODA1LjIzMzk0MTE4MzcyJmV4cGlyZV90aW1lPTEzOTQzODI4MDU=';
function connectedHandler(event) {
for (var i = 0; i < event.streams.length; i++) {
var newDiv = $('<div />', {id:event.streams[i].streamId});
$('body').append(newDiv);
session.subscribe(event.streams[i], event.streams[i].streamId,{});
}
}
var session = TB.initSession(sessionId);
session.addEventListener('sessionConnected', connectedHandler);
session.connect(apiKey, token);
//////End of my opentok code////////////
////////////////////////////////////////////////
},
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);
}
};
This is the output I get:
2014-02-07 11:44:19.407 HelloCordova[2377:60b] iOS Connected to Session
2014-02-07 11:44:19.408 HelloCordova[2377:60b] object for session is {
connection = {
connectionId = "4B191468-46D5-4414-A46A-5C97376D6F2E";
creationTime = 1391791459;
};
connectionCount = 0;
environment = production;
sessionConnectionStatus = OTSessionConnectionStatusConnected;
sessionId = "2_MX4yMTY5MTQ5Mn5-RnJpIEZlYiAwNyAwODozMjozOSBQU1QgMjAxNH4wLjIwMzc2MDV-";
streams = (
);
}
2014-02-07 11:44:19.456 HelloCordova[2377:60b] iOS Received Stream
Does anyone know why this isn't working and what I need to change?
Cordova plugin is modeled after OpenTok JS 2.2. In this new version, there are several changes. First of all, 'addEventListener' has been renamed to 'on'. To add events, you can do this:
session.on({
'sessionConnected': function(event){
session.publish( publisher );
},
'streamCreated': function(event){
var newDiv = $('<div />', {id:event.stream.streamId});
$('body').append(newDiv);
session.subscribe(event.stream, event.stream.streamId, {});
}
})
Note the following changes:
* addEventListener no longer exists
* on sessionConnected events, you no longer get an array of existing streams in the session. Every stream in the session will trigger a streamCreated event.
* streamCreated event callback parameter only has 1 stream element. This event will be triggered once for every stream
Here's a list of coming v2.2 changes: http://labs.tokbox.com/javascript-2.2
I have added some working sample code for you to reference: https://github.com/songz/cordova-plugin-opentok/blob/master/README.md#sample-code