Hi, I created app in which i get data from some server i want to that if internet is not connected then user will not able to use app. I put
document.addEventListener("deviceready", function(){ onDeviseReady(); }, false);
function onDeviseReady()
{
document.addEventListener("offline", offLine, false);
}
function offLine()
{
navigator.notification.alert(
'No Internet Connected',message,'Message','Done');
}
Now what i should do in function message(){} so that the user not be able to move here until user connected to the internet
i put in alert box in message function but this is not i want
PREFACE
Your app needs Internet Connection to run, so you should check either the device is connected to the internet or not. For that you can create a utility function (say hasConnection) which returns boolean true on internet connection or boolean false on no internet connection.
The hasConnection Function
function hasConnection() {
var networkState = navigator.network.connection.type;
if(networkState === Connection.NONE) {
return false;
}
return true;
}
And depending on the hasConnction return value you can take the right decision.
SAMPLE EXAMPLE
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.
}
ONE NOTE
Make sure that you have :
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
in android Manifest.
AT LAST
I am also creating android app using Phonepage / Cordova and jQuery-mobile that needs internet connection and using this approach, working fine for me. I hope it helps you.
Related
I am just confused Like how this window.addEventListener('online') or window.addEventListener('offline') works.
I have created An LGTV WebOS application where I have added that if any video is playing and on during play the video if internet connection is lost it should show an alert message.
So I used these window events but they only work when my wifi or network is disconnected not when I have connected to wifi but there is no internet on that.
So what I want is alert should be displayed when I have connected to wifi but there is no internet available on wifi is there any way to do this?
window.addEventListener('online', updateOnlineStatus);
window.addEventListener('offline', updateOnlineStatus);
function updateOnlineStatus(event) {
console.log("-----------------Control comes into updateOnlineStatus --------------");
console.log("event",event);
var errorModal = document.getElementById("errorModal");
var condition = navigator.onLine ? "online" : "offline";
if(condition == "online"){
console.log("-----------INternet Is conected ----------------");
errorModal.style.display="none";
video.play();
}else{
console.log("-----------INternet Is NOOOOOOTT conected ----------------");
video.pause();
errorModal.style.display="block";
SpatialNavigation.makeFocusable();
SpatialNavigation.focus("#ok_btn");
}
}
If you are developing a WebOS TV application, you should check first the native APIs of that platform...
Connection Manager
Event handler
WebOS services
You can get a connection status by using the webOsDev.js library of WebOS.
webOSDev.connection.getStatus({
onSuccess: function (res) {
if (res.isInternetConnectionAvailable === false) {
//when the internet connection is not available
} else {
//when internet is available
}
},
onFailure: function (res) {
//on failure to request the API
},
subscribe: true
});
Here is my code:
firebase.initializeApp(config);
if(!window.Notification){
alert('Not supported');
}else{
Notification.requestPermission().then(function(p){
if(p=='denied'){
alert('You denied to show notification');
}else if(p=='granted'){
alert('You allowed to show notification');
}
});
}
var database = firebase.database().ref("sensor/Motion");
database.on('child_added', function() {
$("#Mt").val("Motion detected");
$("#dateM").val( moment().format('LLL') );
if(Notification.permission!=='default'){
var notification = new Notification('Alert', {
icon: 'alert-icon-red.png',
body: "Motion detected!",
});
}else{
alert('Please allow the notification first');
}
Everything works fine in my desktop browser but on my Android device, when the screen is locked, it works for a few minute and after that it doesn't work. I get no notifications.
It sounds like your mobile browser is stopping tasks when the screen is locked, likely to improve battery life. That in general sounds like a good thing.
If you want to alert the user of an event that happens when they're not using their device, consider using Firebase Cloud Messaging for sending and handling those messages. This ensures it uses a communication channel that is more likely to be active when the user is not actively using the app.
I am using Cordova / Phonegap iBeacon plugin with ionicframework at my cordova project. I am tryin to send a local notification both on android and ios with cordova local notification plugin while entering monitored region , when the app is killed.
Here is my code :
document.addEventListener("deviceready", onDeviceReady, false);
function didDetermineStateForRegion(pluginResult) {
}
function didStartMonitoringForRegion (pluginResult) {
}
function didExitRegion(pluginResult) {
$cordovaLocalNotification.add({
id: 30244234234,
title: "Good By!",
text: "Hope to see you again."
}).then(function () {
});
}
function didEnterRegion (pluginResult) {
$cordovaLocalNotification.add({
title: "Welcome",
text: "Tap to launch app"
}).then(function () {
});
};
function didRangeBeaconsInRegion (pluginResult) {
}
function onDeviceReady() {
// Now safe to use device APIs
function createBeacon(uuid,nofiyState) {
var uuid = uuid; // mandatory
var identifier = 'estimote'; // mandatory
// throws an error if the parameters are not valid
var beaconRegion = new cordova.plugins.locationManager.BeaconRegion(identifier, uuid);
beaconRegion.notifyEntryStateOnDisplay = true;
return beaconRegion;
}
var delegate = new cordova.plugins.locationManager.Delegate();
delegate.didDetermineStateForRegion = didDetermineStateForRegion;
delegate.didStartMonitoringForRegion = didStartMonitoringForRegion;
delegate.didRangeBeaconsInRegion = didRangeBeaconsInRegion;
delegate.didEnterRegion = didEnterRegion;
delegate.didExitRegion = didExitRegion;
var beaconRegion = createBeacon('02681445-8D1B-4F58-99D4-B25F4B129A58',true);
// var beaconRegionBlue = createBeacon('02681445-8D1B-4F58-99D4-B25F4B129A58',1,,true);
cordova.plugins.locationManager.setDelegate(delegate);
// required in iOS 8+
//cordova.plugins.locationManager.requestWhenInUseAuthorization();
cordova.plugins.locationManager.requestAlwaysAuthorization();
cordova.plugins.locationManager.startMonitoringForRegion(beaconRegion)
.fail(console.error)
.done();
}
cordova plugins :
com.unarin.cordova.beacon 3.3.0 "Proximity Beacon Plugin"
de.appplant.cordova.plugin.local-notification 0.8.1 "LocalNotification"
nl.x-services.plugins.socialsharing 4.3.16 "SocialSharing"
org.apache.cordova.console 0.2.13 "Console"
org.apache.cordova.device 0.3.0 "Device"
cordova version : 4.3.0
this works fine for ios even if the app is killed but on android notifications cames only if app in the background. When i kill the app from task manager on android i never seen any local notification.
Is it possible to receive notification on android even if app is killed ?
thanks for help.
lets clear some stuff , there are states that yo are confusing :
App as a service
App running in background (i.e minimized).
App killed (not running at all)
in all cases the 3rd state when you kill app ( via long press back button in custom roms , or force stop from app menu in your OS ) , the app is simply removed from memory , no code is being excuted !
what usually is done in this case is automatically relaunching the service after it has been stopped check this answer , and as you can read :
it is really very bad pattern to run service forcefully against the
user's willingness.
there are so many cordova plugins to create BroadcasteReceiver , however the simple answer to your question , if app is killed it is not possible to receive notification .
But you should consider this: if user kills your app , it means it was done intentionally , so you shouldnt really worry if your app will work or not , as this is the user's issue , and not yours as a developer.
I'm developing an Android app with Phonegap. I need check if an internet connection is "true". If is false, show an alert, "else" redirect to website.
But not working, it seems that the app simply ignores this "script".
code:
<head>
<script>
var state = navigator.connection.type;
if (state == window.Connection.NONE)
{
alert("nao");
}
else
{
<meta http-equiv="refresh" content="0; url=http://website.com.br/abc" />
}
</script>
I use this function in my Android/Phonegap Application:
function CheckConnection() {
if(!navigator.network) {
navigator.network = window.top.navigator.network;
}
// return the type of connection found
return ( (navigator.network.connection.type === "none" || navigator.network.connection.type === null || navigator.network.connection.type === "unknown" ) ? false : true );
}
I want to point out that this may not be the most reliable. Also you don't want to confuse a slow connection with no connection so the timeout attribute must be set for a long period of time for slow connections. I also use jquery for the ajax request because the javascript would be a lot of code so make sure you have the jquery library on hand. First create a php file to make a request to (I'll call it test.php):
<?php
//test.php
echo 'request success';
?>
The initiator for the request (checks your internet connection):
Javascript/Jquery:
<script type="text/javascript">
$.ajax({
url: "test.php",
error: function(){
// will fire when timeout is reached
alert('no internet');
},
success: function(){
//do something
//success function do this if the request is a success
},
timeout: 30000 // sets timeout to 30 seconds remember you want it to be long to ensure that it isn't just a slow connection
});
</script>
Hope this helps and again it may not be the best way. I'd think that java might have a method/class to see about internet. I'd also think that you are using java since this appears to be an Android app--Correct? Tell me if this didn't work for you.
If you are working in cordova ver >= 3.0.0 then first you need to install Network Connection plugin using CLI(Command-Line Interface), which events added by org.apache.cordova.network-information
online
offline
cordova plugin add org.apache.cordova.network-information
$(document).ready(function() {
document.addEventListener("offline", onOffline, false);
document.addEventListener("online", onOnline, false);
});
function onOffline() {
// YOUR CODE FOR OFFLINE
}
function onOnline() {
// YOUR CODE FOR ONLINE
}
I see you are using an experimental API and that's why its not working.
As you are developing on PhoneGap then you have to add the corresponding plugin to retrieve network info.
cordova plugin add org.apache.cordova.network-information
check details and examples of this plugin here.
once you added the plugin, now to test network connection.
var state = navigator.network.connection.type;
if (state == navigator.network.connection.type)
{
alert("nao");
}
else
{
<meta http-equiv="refresh" content="0; url=http://website.com.br/abc" />
}
The Facebook OAuth popup is throwing an error in Chrome on iOS only. Both developers.facebook.com and google have turned up nothing about this. Ideas?
You can use the redirection method as follow for this case (by detecting the user agent being chrome ios):
https://www.facebook.com/dialog/oauth?client_id={app-id}&redirect_uri={redirect-uri}
See more info here https://developers.facebook.com/docs/facebook-login/login-flow-for-web-no-jssdk/
Remark: I personnaly use the server OAuth in that case but this should do the trick and is quite simple
This is how I did it (fixing iOS chrome specifically)
// fix iOS Chrome
if( navigator.userAgent.match('CriOS') )
window.open('https://www.facebook.com/dialog/oauth?client_id='+appID+'&redirect_uri='+ document.location.href +'&scope=email,public_profile', '', null);
else
FB.login(null, {scope: 'email,public_profile'});
Here is a complete workaround for your FB JS Auth on Chrome iOS issue http://seanshadmand.com/2015/03/06/facebook-js-login-on-chrome-ios-workaround/
JS functions to check auth, open FB auth page manually and refresh auth tokens on original page once complete:
function openFBLoginDialogManually(){
// Open your auth window containing FB auth page
// with forward URL to your Opened Window handler page (below)
var redirect_uri = "&redirect_uri=" + ABSOLUTE_URI + "fbjscomplete";
var scope = "&scope=public_profile,email,user_friends";
var url = "https://www.facebook.com/dialog/oauth?client_id=" + FB_ID + redirect_uri + scope;
// notice the lack of other param in window.open
// for some reason the opener is set to null
// and the opened window can NOT reference it
// if params are passed. #Chrome iOS Bug
window.open(url);
}
function fbCompleteLogin(){
FB.getLoginStatus(function(response) {
// Calling this with the extra setting "true" forces
// a non-cached request and updates the FB cache.
// Since the auth login elsewhere validated the user
// this update will now asyncronously mark the user as authed
}, true);
}
function requireLogin(callback){
FB.getLoginStatus(function(response) {
if (response.status != "connected"){
showLogin();
}else{
checkAuth(response.authResponse.accessToken, response.authResponse.userID, function(success){
// Check FB tokens against your API to make sure user is valid
});
}
});
}
And the Opener Handler that FB auth forwards to and calls a refresh to the main page. Note the window.open in Chrome iOS has bugs too so call it correctly as noted above:
<html>
<head>
<script type="text/javascript">
function handleAuth(){
// once the window is open
window.opener.fbCompleteLogin();
window.close();
}
</script>
<body onload="handleAuth();">
<p>. . . </p>
</body>
</head>
</html>
My 2 cents on this as noone of the answers were clear to me. Im firing the login js dialog on a button click, so now when it's chrome ios I check first if the user it's logged into facebook and if not I send them to the login window. The problem with this is that chome ios users needs to click connect button twice if they are not logged into facebook. If they are logged into facebook one click is enough.
$( 'body' ).on( 'click', '.js-fbl', function( e ) {
e.preventDefault();
if( navigator.userAgent.match('CriOS') ) {
// alert users they will need to click again, don't use alert or popup will be blocked
$('<p class="fbl_error">MESSAGE HERE</p>').insertAfter( $(this));
FB.getLoginStatus( handleResponse );
} else {
// regular users simple login
try {
FB.login( handleResponse , {
scope: fbl.scopes,
return_scopes: true,
auth_type: 'rerequest'
});
} catch (err) {
$this.removeClass('fbl-loading');
}
}
});
That bit of code make it works for chrome ios users. On handle response I simple take care of fb response and send it to my website backend for login/register users.
var handleResponse = function( response ) {
var $form_obj = window.fbl_button.parents('.flp_wrapper').find('form') || false,
$redirect_to = $form_obj.find('input[name="redirect_to"]').val() || window.fbl_button.data('redirect');
/**
* If we get a successful authorization response we handle it
*/
if (response.status == 'connected') {
var fb_response = response;
/**
* Make an Ajax request to the "facebook_login" function
* passing the params: username, fb_id and email.
*
* #note Not all users have user names, but all have email
* #note Must set global to false to prevent gloabl ajax methods
*/
$.ajax({...});
} else {
//if in first click user is not logged into their facebook we then show the login window
window.fbl_button.removeClass('fbl-loading');
if( navigator.userAgent.match('CriOS') )
window.open('https://www.facebook.com/dialog/oauth?client_id=' + fbl.appId + '&redirect_uri=' + document.location.href + '&scope=email,public_profile', '', null);
}
};
Hope it helps!
Not a real answer but based on this thread worth noting that is started working for our app, on Chrome when on the iPhone we did General>Reset>Reset Location & Privacy
I got a solution for ios facebook website login in google chrome . Actually the issue was with google chrome in ios when we click on facebook login button it give internally null to the window.open in ios chrome .
There are two solution either to check it is chrome in ios(chrios) and then generate custom login screen ( still not chance that it will we correct ).
Second what i have used. Is to use facebook login from backhand create a api hit will populate facebook screen and then when login is done it will redirect to your server from where you will redirect to your website page with facebook data.
one other benefit of it is that you create 2 website for same website owner you can not set two website url in facebook developer account .In this way you can create many website facebook login with same facebook appid .
This is a very common issue which all developers have faced while implementing the FB login feature. I have tried most of the Internet solutions but none of them worked. Either window.opener do not work in Chrome iOS or sometime FB object is not loaded while using /dialog/oauth.
Finally I solved this by myself after trying all the hacks!
function loginWithFacebook()
{
if( navigator.userAgent.match('CriOS') )
{
var redirect_uri = document.location.href;
if(redirect_uri.indexOf('?') !== -1)
{
redirect_uri += '&back_from_fb=1';
}
else
{
redirect_uri += '?back_from_fb=1';
}
var url = 'https://www.facebook.com/dialog/oauth?client_id=[app-id]&redirect_uri='+redirect_uri+'&scope=email,public_profile';
var win = window.open(url, '_self');
}
else
{
FB.login(function(response)
{
checkLoginState();
},
{
scope:'public_profile,email,user_friends,user_photos'
});
}
}
Notice that above I'm passing an extra param to the redirect url so that once the new window opens with above redirect uri I could read the values and can say yes this call is from Chrome iOS window. Also make sure this code runs on page load.
if (document.URL.indexOf('back_from_fb=1') != -1 && document.URL.indexOf('code=') != -1)
{
pollingInterval = setInterval(function()
{
if(typeof FB != "undefined")
{
FB.getLoginStatus(function(response) {}, true);
checkLoginState();
}
else
{
alert("FB is not responding, Please try again!", function()
{
return true;
});
}
}, 1000);
}