I made an application using twilio, webRTC and ionic, and the video call is working. However, is it possible to make the video call when the app runs in background? I couldn't come up with a solution with ionic.
I created a landing page upon login which has all the token grant and initialization of twilio so that once a user logs in. It is already on listening mode. Then, i handled the opening of push to actually just redirect to that particular landing page. In my case, the landing page is app.onlineUsers
var notificationOpenedCallback = function(jsonData) {
console.log('notificationOpenedCallback: ' + JSON.stringify(jsonData.action));
if (jsonData.action) {
if (jsonData.action.actionID == "IdAccept") {
$state.go('app.onlineUsers');
//custom code executes
} else if (jsonData.action.actionID == "IdReject") {
alert('rejected');
}
}
};
window.plugins.OneSignal.getIds(function(ids) {
// alert(ids);
did = ids.userId;
$sessionStorage.DID = did;
$localStorage.DID = did;
// alert(" player_id: "+$localStorage.DID);
});
// TODO: Update with your OneSignal AppId and googleProjectNumber before running.
window.plugins.OneSignal.startInit("appId", "googleProjectNumber")
.handleNotificationOpened(notificationOpenedCallback).handleNotificationReceived(function(jsonData) {
$state.go('app.onlineUsers');
// alert("Notification received:\n" + JSON.stringify(jsonData));
// console.log('Did I receive a notification: ' + JSON.stringify(jsonData));
}).inFocusDisplaying(window.plugins.OneSignal.OSInFocusDisplayOption.None).endInit();
Related
How to integrate Quickblox with AngularJs?
I already have done Login using it's sample's js and also getting response of incoming call looking at console.
But now I want to integrate Quickblox's listeners like
onCallListener,onAcceptCallListener,onRejectCallListener etc. are not working.
Please help me to solved it out, what i have missed? Thanks.
Just add below code in body of your main index page for quickblox integration.
<aside class="msg_board" id="msg_board"></aside>
Go through this link for integrating quickblox into angular js Here
after integration SDK initialize SDK using user credentials(email or password), then initialize all handler for event handling like.
function setupAllListeners() {
QB.chat.onDisconnectedListener = onDisconnectedListener;
QB.chat.onReconnectListener = onReconnectListener;
QB.chat.onMessageListener = onMessage;
QB.chat.onSystemMessageListener = onSystemMessageListener;
QB.chat.onDeliveredStatusListener = onDeliveredStatusListener;
QB.chat.onReadStatusListener = onReadStatusListener;
setupIsTypingHandler();
}
then implement function that handle all events like
// on message listener
//
function onMessage(userId, msg) {
// check if it's a mesasges for current dialog
//
if (isMessageForCurrentDialog(userId, msg.dialog_id)){
dialogsMessages.push(msg);
if (msg.markable === 1) {
sendReadStatus(userId, msg.id, msg.dialog_id);
}
// сheck if it's an attachment
//
var messageAttachmentFileId = null;
if (msg.extension.hasOwnProperty("attachments")) {
if(msg.extension.attachments.length > 0) {
messageAttachmentFileId = msg.extension.attachments[0].id;
}
}
showMessage(userId, msg, messageAttachmentFileId);
}
// Here we process the regular messages
//
updateDialogsList(msg.dialog_id, msg.body);
}
It will call whenever message is sended from otherend.
I am doing pushnotification for both Android/IOS.
I have used a cordova push-plugin https://github.com/phonegap-build/PushPlugin, it seems to work great.
Info : I'm on a AngularJS project.
In my NotificationHelper factory i have this init method:
helper.init = function() {
// Instanciate push plugin notification
var pushNotification = window.plugins.pushNotification;
var errorHandler = function(error) {
logger.debug('errorHandler = ' + error);
};
if ($rootScope.isAndroid()) {
var senderId = CONFIG.NOTIFICATION_ANDROID_SENDER_ID;
pushNotification.register(function(result) {
logger.debug('successHandler = ' + result);
}, errorHandler, {
'senderID' : senderId,
'ecb' : 'onNotificationGCM'
});
}
};
I also defined those methods on mains.js :
var onNotificationGCM = function(event) {
// call back to web service in Angular.
var elem = angular.element(document.querySelector('[ng-app]'));
var injector = elem.injector();
var service = injector.get('NotificationHelper');
service.onNotificationGCM(event);
};
It's a trick to call angularJS factory from main javascript.
'onNotificationGCM' call the 'NotificationHelper.onNotificationGCM' method :
helper.onNotificationGCM = function(e) {
switch (e.event) {
case 'message':
// Notification happened while app was in the foreground
if (e.foreground) {
logger.debug('[notification] [message] Foreground : ' + JSON.stringify(e));
} else { // Notification touched in the notification tray
logger.debug('[notification] [message] Background : ' + JSON.stringify(e));
if (e.coldstart) {
// App was not running and user clicked on notification
} else {
// App was running and user clicked on notification
}
}
decriptPayloadNotification(e.payload);
break;
case 'registered':
logger.debug('[notification] [registered] : ' + JSON.stringify(e));
if (e.regid.length > 0) {
registerUser(e.regid, 'gcm');
}
break;
case 'error':
logger.debug('[notification] [error] : ' + JSON.stringify(e));
break;
default:
logger.debug('[notification] [default] : Unknown, an event was received and we do not know what it is : ' + JSON.stringify(e));
break;
}
};
During the first use, everything work good :
'Registered' event is received
Notifications are received
When i'm on foreground I receive 'message' event :
NotificationHelper: [notification] [message] Foreground : {"event":"message","from":"847593779913","message":"Agenêts 23/03 10h\r\n","collapse_key":"do_not_collapse","foreground":true,"payload":{"lt":"school","lv":"E1154","notId":"35429","title":"Agenêts le 23/03/2015","message":"Agenêts 23/03 10h\r\n"}}
When i'm on background, if i receive notif and touche it on notification tray, I receive 'message' event :
NotificationHelper: [notification] [message] Background : {"event":"message","from":"847593779913","message":"la piscine sera fermée 1 journée pour raison technique","coldstart":false,"collapse_key":"do_not_collapse","foreground":false,"payload":{"lt":"swimming pool","lv":"E114","notId":"29869","title":"23/04/2015 fermeture de la piscine","message":"la piscine sera fermée 1 journée pour raison technique"}}
BUT, if i kill my app, everything stop to work.
If i restart app, i will not receive anymore 'message'event and 'onNotificationGCM' will not be called.
I founded some articles speaking about this problem, but without success :
Stackoverflow : Phonegap PushNotification to open a specific app page
Does anyone has an idea about this problem ?
If you are using node-gcm as push notification server side I hope this might help for your question:
things to check:
use adb logcat from console and check your device logs to see if your device receives any notification (you should see some logs from gcmservices if you receive). I believe you should see some logs because otherwise you probably wouldn't get any notification when the app is on foreground either.
check if you add "title" and "message" keys on your message data (this draw me crazy before)
check if delayWhileIdle parameter is false
sample message variable and method i am using is below:
var pushAndroidSender = new gcm.Sender('Your GoogleApi Server Key Here');
var message = new gcm.Message({
collapseKey: 'demo',
delayWhileIdle: false,
timeToLive: 3,
data: {
"message":"What's up honey?",
"title":"Come on"
}
});
pushAndroidSender.send(message, registrationIds, function(err, result) {
if (err) {
console.error("this is an error: " + err);
} else {
console.log("this is a successful result:" + result);
}
});
I was asking myself why it worked correctly the first time and not the following times...and i had this idea :
maybe callback function is subscribed to plugin first time but not the next times.
And this is exactly the source of my problem. I call "pushNotification.register" only one time to init plugin and get ids...
But the next time I launch app, i don't instanciate again the plugin, so pushplugin don't know which method to call in callback request.
So answer is : Call "pushNotification.register" in each application launch !
In my code, i have to call method below on each "deviceready" event :
helper.init = function() {
// Instanciate push plugin notification
var pushNotification = window.plugins.pushNotification;
var errorHandler = function(error) {
logger.debug('errorHandler = ' + error);
};
if ($rootScope.isAndroid()) {
var senderId = CONFIG.NOTIFICATION_ANDROID_SENDER_ID;
pushNotification.register(function(result) {
logger.debug('successHandler = ' + result);
}, errorHandler, {
'senderID' : senderId,
'ecb' : 'onNotificationGCM'
});
}
};
I'm having a tough time getting push notifications (using the ngCordova plugin) to work. I have followed their sample code exactly as is documented on the site: http://ngcordova.com/docs/plugins/pushNotifications/
(the only difference is that I don't have a deviceready listener, instead, my code is inside the ionicPlatform.ready listener.)
Here is my code:
angular.module('myApp', ['ionic', 'ngCordova'])
.run(function($ionicPlatform, $rootScope, $state, $cordovaPush) {
$ionicPlatform.ready(function() {
var config = {
"senderID": "myID100001000"
};
$cordovaPush.register(config).then(function(result) {
alert(result);
}, function(err) {
alert(err);
})
});
$rootScope.$on('$cordovaPush:notificationReceived', function(event, notification) {
switch(notification.event) {
case 'registered':
if (notification.regid.length > 0 ) {
alert('registration ID = ' + notification.regid);
}
break;
default:
alert('An unknown GCM event has occurred');
break;
}
});
})
When my app starts I do get the "OK" alert, so I know it successfully goes through the $cordovaPush.register call. However, I was expecting to get a "registered" notification event, right after, but I never get notified.
Any help would be appreciated.
The solution is in the comments but this needs a proper answer.
First of all, the register callback always returns OK as long as you pass a senderID, but if the $cordovaPush:notificationReceived event is never called (it may take a few seconds), this ID is probably wrong.
You must use the Project Number, not the Project ID.
To get the number, go to the API Console, select the project and you'll be on the Overview page. On top of this page, you'll see something like this:
Project ID: your-project-id Project Number: 0123456789
Just copy and use the project number and everything should work.
I have suffered with this a lot and I have found out, that there are in fact two versions of the cordova push plugin currently:
https://github.com/phonegap-build/PushPlugin (deprecated)
https://github.com/phonegap/phonegap-plugin-push (new one)
Both are supported by ngCordova, but only the deprecated version is documented.
The deprecated version is $cordovaPush
and the newer one is $cordovaPushV5, and they have completely different methods.
For me the problem was that I downloaded the cordova-plugin-push and tried to implement it with the old documentation on ngCordova site.
The code is:
/*
* Non deprecated version of Push notification events
*/
function registerV5() {
$ionicLoading.show({
template: '<ion-spinner></ion-spinner>'
});
if (ionic.Platform.is('browser')) {
alert("You are running on broswer, please switch to your device. Otherwise you won't get notifications");
$ionicLoading.hide();
return;
}
/**
* Configuration doc:
* https://github.com/phonegap/phonegap-plugin-push/blob/master/docs/API.md#pushnotificationinitoptions
*/
var GCM_PROJECT_ID = 'xxxxxx';
$cordovaPushV5.initialize({
"android": {
"clearNotifications": false,
"senderID" : GCM_PROJECT_ID
}
});
$cordovaPushV5.register().then(function (deviceToken) {
console.log("Successfully registered", deviceToken);
$scope.data.deviceToken = deviceToken;
// Below code required to configure $cordovaPushV5 notifications emitter.
// Don't pass function it's not handler.
$cordovaPushV5.onNotification();
$cordovaPushV5.onError();
$ionicLoading.hide();
}, function (error) {
console.log("Failed to registered");
console.log("error object : ", error);
$ionicLoading.hide();
});
}
$rootScope.$on('$cordovaPushV5:notificationReceived', function(event, data) {
console.log("notification received");
console.log("data object: ", data);
var foreground = data.additionalData.foreground || false;
var threadID = data.additionalData.payload.threadID || '';
var group = data.additionalData.payload.group || false;
if (foreground) {
// Do something if the app is in foreground while receiving to push - handle in app push handling
console.log('Receive notification in foreground');
} else {
// Handle push messages while app is in background or not started
console.log('Receive notification in background');
// Open FB messanger app when user clicks notification UI when app is in background.
if (typeof data.additionalData.coldstart != "undefined" && data.additionalData.coldstart == false)
if (!group)
// Open FB Messenger of specific user chat window
window.open('fb-messenger://user/' + threadID, '_system', 'location=no');
else
// Open FB Messenger of specific group chat window
window.open('fb-messenger://groupthreadfbid/' + threadID, '_system', 'location=no');
}
});
$rootScope.$on('$cordovaPushV5:errorOccurred', function(event, error) {
console.log("notification error occured");
console.log("event object: ", event);
console.log("error object: ", error);
});
More on this github article: https://github.com/driftyco/ng-cordova/issues/1125 (code from here) and in this article: https://github.com/yafraorg/yafra/wiki/Blog-Ionic-PushV5
I've been in contact with Phonegap Support, as well as people who are more experienced in Android than I, as well as a knowledgeable mobile web app developer to determine why an odd error is occurring in my application. According to the people I have talked to, the problem could stem from any of these places (Android, a PhoneGap plugin, or using jQuery mobile).
Here is the folder containing the index.html that holds my code for the Phonegap app:
https://github.com/galenthomasramos/EcigSurvey/tree/master/platforms/android/assets/www
The target device for this app is a Motorola Razr M. I use a local notification plugin to provide notifications throughout a day. Sometimes upon clicking on a notification, some code within my onResume event function is fired very late. I should receive and alert as soon as I resume the app, but instead I receive the alert almost a minute afterwards. An even bigger problem (same symptoms- very late function calls) occurs when I try to log in to my application (login screen is the first page to appear within my application) where I have entered the password correctly, but the phone will not navigate to the next page. There is no way that the page should just reset and not navigate to the next page-- Either I would be alerted to incorrect user input and asked to try again, or the app should successfully navigate to the next page.
I should mention that these errors seem to only occur when accessing the application via a notification, this does not occur if I resume the app from the stack of running apps.
At first I thought that maybe upon my application being suspended, or maybe Android killing some of my background processes, that variables were being terminated within my program which might lead to this kind of behavior, but after looking at the app running with an Android app that observes memory usage and any amount of garbage collection, it doesn't seem like Android is killing anything when this happens.
I have talked to someone else about jQuery Mobile maybe being the culprit (apparently jQuery Mobile acts differently depending on the device platform, and I don't seem to receive these errors on my Nexus 4) and that maybe my page events aren't working correctly?
My onResume event function (should trigger alert at resume):
function onResumeApp(){
//Check to see if there is a suspension time set, if so, check to see if that time has passed, if so, resume normal app behavior
if(resumeTime != null){
//in the case of delaying a notification, need to change currentState to active through a timeout function...
// otherwise causes error in how missing a delayed a notification counts more than once
if(moment().isAfter(resumeTime)){
currentState = states.ACTIVE;
displayAppStatus(states.ACTIVE);
resumeTime = null;
}
}
if (hasMissedNotification){
alert("You have missed " + missedNotifications + " random prompt survey(s). Please remember to take as many surveys as possible.");
hasMissedNotification = false;
missedNotifications = 0;
}
...
}
Is it okay to navigate to another page upon reading the pause event? In this situation, I could foresee an issue with the app being in the background by the time any code would be read within the pause event listener... then again, why would Phonegap include a pause event function if you can't write any Javascript code to use it?
My onPause event function:
function userHasGoneIdle(){
//If user goes idle and has started a random prompt survey but has not finished it before going idle,
//Need to record a survey as being abandoned
if(startedRandomPromptSurvey && !finishedRandomPromptSurvey){
//If a user delays a notification, don't want to add to missing notifications file yet.
if(currentState != states.DELAYED){
hasMissedNotification = true;
addToMissedNotifications(1, moment().toDate().toString());
startedRandomPromptSurvey = false;
finishedRandomPromptSurvey = false;
}
//If a user clicks a notification (indicates that they have started a random prompt interview), delays notification,
//then misses the delayed notificaiton, it will register both an abandoned as well as a missed, when really they have only missed
//the last delayed notification
}
writingToRandomPromptInt = false;
$("#login-password").val('');
if(!wakeUpFiring)
$.mobile.navigate('#login');
else
$.mobile.navigate('#wakeup');
resetSurveyWidgets();
console.log('userHasGoneIdle');
}
And then I have a bunch of code that is executed by event listener functions by a local notification plugin I use. These events can occur whenever, if the app is in the foreground or the background... they of course do not occur reliably when the app is in the background and I need to change the way this works, but I am wondering if any of the code within these event functions could cause the problem (I want to say yes, because the problems seem to only happen upon accessing the app via notification)
local notification event functions:
ontrigger:
window.plugin.notification.local.ontrigger = function (id, state, json) {
console.log('\nontrigger() #' + id + " State: " + state + " #" + moment().toString());// + ' #' + JSON.parse(json).date);
//if(id != serviceNotificationID){
if(Math.abs(id >= notificationCount - 1 || notificationCount == 0)){
console.log('id - notificationCount == 0:' + id + ' - ' + notificationCount + ' = ' + (id - notificationCount));
clearPriorNotifications(function(){
addNewNotifications(function(){
formNotificationString(writeToNotificationFile);
});
});
}
triggerTime = moment().toDate().toString();
if(id == 0)
didMissDelayedNotification = true;
if(id != -99){
playNotificationAudio();
}
//In the case that the user does not access app when an alarm goes off by clicking notification,
//Have app navigate to wakeup screen
else{
playAlarmAudio();
didMissWakeUp = true;
wakeUpFiring = true;
$.mobile.navigate("#wakeup");
}
setTimeout(function(){
if(id != -1 && id != -99){
//if Havent clicked on a notificaiton, and the notificaiton snt a delayed notificaiton,
if(didMissNotificationArr[parseInt(id)] && id != 0){
console.log("#onTrigger: didMissNotificationArr[" + id + "] = " + didMissNotificationArr[id]);
hasMissedNotification = true;
addToMissedNotifications(2, triggerTime);
window.plugin.notification.local.cancel(id);
}
//for missed delayed notifications, only log missed if not clicked and only cancel if not clicked (and therefore cnaceled)
else if(id == 0 && didMissDelayedNotification){
console.log("#onTrigger: didMissDelayedNotification = " + didMissDelayedNotification);
hasMissedNotification = true;
addToMissedNotifications(2, triggerTime);
window.plugin.notification.local.cancel(id);
}
}
//Need to set boolean to remain at #wakeup, regardless of whether or not the user leaves the app during
//wakeup alarm
else if(id == -99 && didMissWakeUp){
wakeUpFiring = false;
window.plugin.notification.local.cancel(id);
}
else if(id == -1)
window.plugin.notification.local.cancel(id);
}, (180 * 1000));
//}
};
onclick:
window.plugin.notification.local.onclick = function(id, state, json){
console.log('\n clicking notification #' + id);
//notificationTime = JSON.parse(json).date;
//if(id != serviceNotificationID){
//When clicking on a delayed notification
if(id == 0){
$.mobile.navigate('#delay');
didMissDelayedNotification = false;
startedRandomPromptSurvey = true;
finishedRandomPromptSurvey = false;
}
//When clicking on a test notification
else if(id == -1){
$.mobile.navigate("#login");
takingTestSurvey = true;
startedRandomPromptSurvey = false;
finishedRandomPromptSurvey = false;
}
//When clicking on a wakeup notification
else if(id == -99){
$.mobile.navigate("#wakeup");
startedRandomPromptSurvey = false;
finishedRandomPromptSurvey = false;
}
//When clicking on a standard, untouched notification
else{
$.mobile.navigate('#delay');
startedRandomPromptSurvey = true;
finishedRandomPromptSurvey = false;
didMissNotificationArr[parseInt(id)] = false;
}
oncancel:
window.plugin.notification.local.oncancel = function (id, state, json) {
console.log('\n CANCELLING notification #' + id + " State: " + state);
//console.log("caller is " + arguments.callee.caller.toString());
if(id != -99){
if(my_media){
my_media.stop();
//my_media.reset();
my_media.release();
}
}
//If wake up alarm notificaiton:
else{
wakeUpFiring = false;
//$.mobile.navigate("#login");
if(my_alarm_media){
my_alarm_media.stop();
//my_media.reset();
my_alarm_media.release();
}
}
};
Any ideas why my app could be unresponsive upon resuming from a notification?
i'm trying to login into the site with the following javascript. But, i'm loading only the complete page. I'm developing windows 8 app
(function () {
"use strict";
WinJS.UI.Pages.define("/pages/home/home.html", {
// This function is called whenever a user navigates to this page. It
// populates the page elements with the app's data.
ready: function (element, options) {
// TODO: Initialize the page here.
document.getElementById("bt_login").addEventListener("click", login, false);
}
});
})();
function login() {
var xhrDiv = document.getElementById("xhrReport");
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = dataLoaded;
xhr.open("POST", "http://www.160by2.com", true, <username>, <password>);
xhr.send();
function dataLoaded() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
// OK
xhrDiv.innerHTML = window.toStaticHTML("response:" + xhr.responseText);
} else {
// not OK
xhrDiv.innerText = "failure";
}
}
};}
I want to dsiplay in xhrdiv.innerHTML as "LOGIN SUCCESS" or "LOGIN ERROR"
EDIT:
I tried the following code:
iframe = document.getElementById("ifra_op");
iframe.setAttribute("src", "http://www.160by2.com/index");
document.getElementById("op").appendChild(iframe);
iframe.contentWindow.document.getElementById("MobileNoLogin") = "<mobno>";
iframe.contentWindow.document.getElementById("LoginPassword") = "<pass>;
iframe.contentWindow.document.getElementsByName("LoginForm").click();
But, there is an error. It says "Javascript run time error:math is undefined"
"math" comes from the website. I don't know how to handle this. Also, the permission is denied. Why is that so?
You need to make sure you have a service (something like a web service) in the remote server to process the request.
In here what you can do is.
Create an iframe and set the src to 160by2;
Access the webpage using iframe.contentwindow, inject your code to fill up the forms and trigger the submit button.
Parse the received html to verify your login.
Use jquery , makes life easier.
var iframe = $("#ifra_op");
$(iframe).attr("src", "http://www.160by2.com/index");
$(iframe).attr("onload","submitForm();");
function submitForm(){
$(iframe.contentWindow.document).find("#MobileNoLogin").val("9999");
$(iframe.contentWindow.document).find("#LoginPassword").val("pass");
$('#button').click();
}