Can't get regID from gcm server - android

Few days ago, I succeeded in messaging my phone with push plugin. But now, after pushNotification.register is executed, I don't receive a notification that has a registration ID (after pushNotification.register, ecb was not fired). But success handler was fired. One strange thing is success handler is also fired when I turn off every network (Wifi, mobile internet).
So I tried it on another phone (friend's). Then it works well.
What happened in my phone? I searched this issue last few days, but I couldn't find any helpful docs. Is there anybody who has same problem?
var pushNotification;
document.addEventListener("deviceready", function(){
pushNotification=window.plugins.pushNotification;
console.log('Device Ready!!');
register();
});
function register() {
console.log('registering...');
pushNotification.register(
successHandler,
errorHandler,
{
"senderID":"1234567890", // (temporary)
"ecb":"onNotification"
}
);
}
function onNotification(e) {
console.log('======onNotification======');
console.log('type of notification:'+e.event);
switch(e.event) {
case 'registered':
if(e.regid.length>0) {
$("#status").append('<li>regid:'+e.regid+'</li>');
console.log('regid:'+e.regid);
}
break;
case 'message':
if(e.foreground) {
console.log('inline message');
} else {
if(e.coldstart) {
console.log('coldstart message');
} else {
console.log('background message');
}
}
console.log('message:'+e.payload.message);
console.log('msgcnt:'+e.payload.msgcnt);
break;
case 'error':
$("#status").append('<li>error:'+e.msg);
break;
}
}
function successHandler(result) {
console.log('success; result:'+result);
}
function errorHandler(error) {
console.log('error; error:'+error);
}

Related

socket.io is not receiving or sending events

I have a socket.io project and my client is using android. Connection event is fired on the server-side but join match is not. any ideas why?
socket.connect();
on the client-side, fires the below code on server-side:
io.on('connection', (socket) => {
try {
console.log("connected!");
self.handleJoinMatch(io, socket);
})
} catch (ex) {
console.log(ex.toString());
}
});
connected is logged on the console. handleJoinMatch function is:
handleJoinMatch(io, socket) {
console.log("handle join match is called!");
socket.on('join match', (params) => {
console.log("join matched is recieved!");
.........
handle join match is called! is logged on the console as well, but the below code does nothing:
socket.emit("join match");
update1:
I should mention the even after 10 minutes if I close the android app, the below code is called:
socket.on('disconnect', (reason) => {
console.log("disconnected");
......
update2:
I just realized that in my client, after socket.connect(), socket.connected() returns false and socket.on("connect", connectHandler); is not being called at all.

React Native: Handle silent push notification

Im using react-native-firebase for handling push notification for our React Native app (for android and iOS).
I noticed that there is only have 1 callback for a push notification that is received when the app is running (foreground or background) and not when its closed or killed.
firebase
.notifications()
.onNotification(notification => {
console.log('Notification received');
);
But if the app is closed or killed, it will just put the notification in the tray and will not execute the console.log above.
Then enter silent push notification. So when I just send data part in the payload of the notification and even if app is in foreground, the callback above wont be triggered.
I don't see other callbacks that would help on receiving silent push notifications.
So how do we handle push notification in the javascript part?
You don't need additional packages like suggested in other answers.
Use RNFirebase.io, you can handle this easily.
If you receive Notification if App is in Background, you have to handle it by your own to display this Notification. As an example see my init-Method for Push-Notifications.
import firebase from 'react-native-firebase';
const notifications = firebase.notifications();
....
notifications.onNotification((notif) => {
notif.android.setChannelId('app-infos');
notifications.displayNotification(notif);
});
You do it with displayNotification. But make sure, that you set the Notification-Channel before calling it, because else it wouldn't work on >= Android 8.0
BTW: Make sure, that you fully setup Firebase and grant all needed Permissions to be able to listen for Notifications if App is closed or in Background. (https://rnfirebase.io/docs/v5.x.x/notifications/android)
Appendix
I add this as example to show how I implemented the firebase-notification-stuff as a tiny library (remove the redux-stuff if you don't need it):
import firebase from 'react-native-firebase';
import { saveNotificationToken } from 'app/actions/firebase';
import reduxStore from './reduxStore';
import NavigationService from './NavigationService';
const messaging = firebase.messaging();
const notifications = firebase.notifications();
const crashlytics = firebase.crashlytics();
function registerNotifChannels() {
try {
// Notification-Channels is a must-have for Android >= 8
const channel = new firebase.notifications.Android.Channel(
'app-infos',
'App Infos',
firebase.notifications.Android.Importance.Max,
).setDescription('General Information');
notifications.android.createChannel(channel);
} catch (error) {
crashlytics.log(`Error while creating notification-channel \n ${error}`);
}
}
// This is the Promise object that we use to initialise the push
// notifications. It will resolve when the token was successfully retrieved. The
// token is returned as the value of the Promise.
const initPushNotifs = new Promise(async (resolve, reject) => {
try {
const isPermitted = await messaging.hasPermission();
if (isPermitted) {
registerNotifChannels();
try {
const token = await messaging.getToken();
if (token) {
resolve(token);
}
} catch (error) {
crashlytics.log(`Error: failed to get notification-token \n ${error}`);
}
}
} catch (error) {
crashlytics.log(`Error while checking notification-permission\n ${error}`);
}
// If we get this far then there was no token available (or something went
// wrong trying to get it)
reject();
});
function init() {
// Initialise the push notifications, then save the token when/if it's available
initPushNotifs.then(token => reduxStore.dispatch(saveNotificationToken(token)));
// Save the (new) token whenever it changes
messaging.onTokenRefresh(token => reduxStore.dispatch(saveNotificationToken(token)));
notifications.onNotification((notif) => {
notif.android.setChannelId('app-infos');
notifications.displayNotification(notif);
});
notifications.onNotificationOpened((notif) => {
const { notification: { _data: { chatroom: chatRoomId } } = {} } = notif;
if (chatRoomId) {
NavigationService.navigate('ChatRoom', { chatRoomId });
}
});
}
export default {
init,
};
With this, only go to your index.js file (or your root-file for your app, how ever it will be named) and call the init-Metod:
...
import LPFirebase from 'lib/LPFirebase';
LPFirebase.init();

geolocation not working when location service toggled off and on

I have a function triggered by button click that checks geolocation..it works fine on phones when geolocation is on, and when off, a message saying so displays, as expected. The problem occurs when first the phone's location service is turned off, the button is clicked(message pops up, as expected), then if the user turns location services back on while app is still open, and again clicks the button, still the same 'no location service' message pops up.
Is there a way to check if the phone's location service is turned on or off on each button click? Getting the same results on Android and IOS.
code:
$(document).ready(function () {
$('#smallScreenGeolocate').on('click', function(){
getCurrentLocation();
});
});
function getCurrentLocation () {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(addGeolocationMarker, locationError);
return true;
}
else {
alert("Browser doesn't support Geolocation. Visit http://caniuse.com to discover browser support for the Geolocation API.");
return false;
}
}
Check this answer from another SO post https://stackoverflow.com/a/14862073/6539349
You have to check what was the error as suggested here http://www.w3schools.com/html/html5_geolocation.asp
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition,showError);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
The second parameter showError of the getCurrentPosition() method is used to handle errors. It specifies a function to run if it fails to get the user's location:
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
x.innerHTML = "User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML = "Location information is unavailable."
break;
case error.TIMEOUT:
x.innerHTML = "The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
x.innerHTML = "An unknown error occurred."
break;
}
}

onSMSArrive cordova sms plugins executed more than once

I was developing an app that have capability to read sms content when the user get sms.
So I use ionic and cordova sms plugin to read the sms content. But when user get a sms and triggered the onSMSArrive event provided by the plugin, it did work and can read the sms content.
The problem is it execute (read the sms) more then once, tree times to be exact.
I place this code as a service in ionic.
app.factory('$smsarrive', [function() {
return {
periksa:function() {
if (SMS) SMS.enableIntercept(true, function() {
console.log("some debug hint here");
}, function(){
console.log("some debug hint here");
});
if(SMS) SMS.startWatch(function() {
//update('watching', 'watching started');
console.log("some debug hint here");
}, function(){
//updateStatus('failed to start watching');
console.log("some debug hint here");
});
document.addEventListener('onSMSArrive', function(e) {
var sms = e.data;
var isiSms = sms.body;
if (isiSms.match(/FC0019229/g)!=null) {
if (isiSms.match(/Berhasil/g)!=null) {
console.log("Isi pulsa Berhasil");
} else if (isiSms.match(/Gagal/g)) {
console.log("Isi pulsa Gagal");
} else {
console.log(isiSms);
}
} else {
console.log("some hint here");
}
console.log("ASLI : "+isiSms);
});
}
}
}])
and execute that service whenever a controller of a view is
$scope.$on('$ionicView.enter', function() {
$smsarrive.periksa();
})
Any suggestion? And also sorry for bad english.
i use this plugin
From what I understand in your code examples, you are executing the function "periksa" every time a view is entered ( that's what fires the '$ionicView.enter' event). Then also, you are creating an EventListener for SMS messages every time you execute 'periksa' (every time a view is entered).
So, if you have entered three views, you would have three listeners firing for the arrival of an SMS onSMSArrive.
So, I think you should only Start Watching, and add the EventListener, once, when starting the app (in app.js, inside .run, when $ionicPlatform.ready()).
.run(function($ionicPlatform, $smsarrive) {
$ionicPlatform.ready(function() {
if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
if(( /(ipad|iphone|ipod|android)/i.test(navigator.userAgent) )) {
if (! SMS ) { alert( 'SMS plugin not ready' ); return; }
SMS.startWatch(function(){
console.log('Watching');
}, function(){
console.log('Not Watching');
});
document.addEventListener('onSMSArrive', function(e){
var data = e.data;
$smsarrive.periksa(data);
});
} else {
alert('need run on mobile device for full functionalities.');
}
});
Then, your 'periksa' function should only receive the data as a parameter, for processing and disposing of the results.
Let me know if this was helpful, i'm also studying this framework and I have this plugin working in my App.

navigator.online works in desktop but always returns true in my android phone

I need to check if user is connected to the internet. My code works very well on browser but fails in android phone.
In app.js, I have the following code:
$rootScope.online = navigator.onLine;
$window.addEventListener("offline", function () {
console.log("called offline")
$rootScope.$apply(function() {
$rootScope.online = false;
});
}, false);
$window.addEventListener("online", function () {
console.log("called online")
$rootScope.$apply(function() {
$rootScope.online = true;
});
}, false);
In app, The events are never really fired and navigator.onLine always returns true? How do I fix this?

Categories

Resources