I've set up Pushbots to work with my PhoneGap app, but since the setup and initiation of Pushbots is happening in the index.js file, i am not able to call any methods inside my main angularjs controller.
Whenever the user clicks on a notification i would want to run a function from my main controller and navigate to a page.
How can I achieve this?
Here's my index.js file with the onDeviceReady event set up:
function onDeviceReady() {
// Handle the Cordova pause and resume events
document.addEventListener( 'pause', onPause.bind( this ), false );
document.addEventListener( 'resume', onResume.bind( this ), false );
// TODO: Cordova has been loaded. Perform any initialization that requires Cordova here.
document.addEventListener("backbutton", onBackKeyDown, false);
window.plugins.PushbotsPlugin.initialize(.....);
window.plugins.PushbotsPlugin.on("registered", function(token){
console.log("Registration Id:" + token);
});
window.plugins.PushbotsPlugin.getRegistrationId(function(token){
console.log("Registration Id:" + token);
});
window.plugins.PushbotsPlugin.on("notification:received", function(data){
console.log("received:" + JSON.stringify(data));
});
// Should be called once the notification is clicked
window.plugins.PushbotsPlugin.on("notification:clicked", function(data){
$scope.LoadMyPage(); //this is not getting fired...
alert("clicked:" + JSON.stringify(data));
console.log("clicked:" + JSON.stringify(data));
});
};
You can use $emit on scope when notification is clicked.
window.plugins.PushbotsPlugin.on("notification:clicked", function(data){
console.log("clicked:" + JSON.stringify(data));
$rootScope.$emit('onNotificationClick');
});
Handle this event in main using
$rootScope.$on('onNotificationClick', function () {
// write your logic here
})
Hope this helps
Related
I have a database of persons on my server and it contains a group number attribute. I want to send separate notifications for each of the group. Using the following code, it will send a notification to all apps. How do I set or subscribe the app so that it will know that a certain mobile belongs to a certain group? Each of the members needs to login first before accessing the app.
var app = {
// Application Constructor
initialize: function() {
this.bindEvents();
},
// Bind Event Listeners
//
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
// deviceready Event Handler
//
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicitly call 'app.receivedEvent(...);'
onDeviceReady: function() {
console.log('Received Device Ready Event');
console.log('calling setup push');
// Set your iOS Settings
var iosSettings = {};
iosSettings["kOSSettingsKeyAutoPrompt"] = false;
iosSettings["kOSSettingsKeyInAppLaunchURL"] = true;
window.plugins.OneSignal
.startInit("3074529d MY APP ID HERE d5eb61b000")
.handleNotificationReceived(function(jsonData) {
alert("Notification received: \n" + JSON.stringify(jsonData));
console.log('Did I receive a notification: ' + JSON.stringify(jsonData));
})
.handleNotificationOpened(function(jsonData) {
alert("Notification opened: \n" + JSON.stringify(jsonData));
console.log('didOpenRemoteNotificationCallBack: ' + JSON.stringify(jsonData));
})
.inFocusDisplaying(window.plugins.OneSignal.OSInFocusDisplayOption.InAppAlert)
.iOSSettings(iosSettings)
.endInit();
},
};
When a user subscribes to your app, you can get the OneSignal Player ID of the device and save it to your database.
Anytime after the init call use getPermissionSubscriptionState method to get the Player ID.
Then you can follow OneSignal's Database Integration Guide to associate the player ID with your user's and group number.
Another option is to use OneSignal Tagging Guide documentation to associate devices with groups.
I try to build an android App with push notification and I want to open a specific component when sur touch a received notification.
https://github.com/phonegap/phonegap-plugin-push/blob/master/docs/API.md
http://docs.ionic.io/services/push/
In my app.component.ts constructor I try this :
platform.ready().then(() => {
//StatusBar.styleDefault();
Splashscreen.hide();
this.push.rx.notification()
.subscribe((msg) => {
alert(msg.title + ': ' + msg.text);
console.log(msg.app, "app");
console.log(msg.count, "count");
console.log(msg.image, "image");
console.log(msg.raw, "raw");
console.log(msg.sound, "sound");
console.log(msg.text, "text");
console.log(msg.title, "title");
});
});
It work well when my app isn't close or on pause. I can see my logs.
But when my app is closed or onpause, if I touch notification, my app open but I can't have my logs.
I tried this too :
this.push.on('notification', function(data) {
// do something with the push data
// then call finish to let the OS know we are done
this.push.finish(function() {
console.log("processing of push data is finished");
}, function() {
console.log("something went wrong with push.finish for ID = " + data.additionalData.notId)
}, data.additionalData.notId);
});
But I had this error :
Object [object Object] has no method 'on'
What I have to do ?
To have your notification event called when your application isn't in foreground, you have to add content-available: 1 into your push message.
Read this link
I have a PhoneGap app, that I've set up Pushbots with (in the onDeviceReady event).
The notification:clicked event is working correctly if the application was not running in the background, but if the app is running and it's in use, and the user brings down the notification tab and clicks on a notification, nothing happens.
How can I fire the notification:clicked event when the app is in the foreground?
I want to navigate to a page whenever the user clicks the notification, whether or not the application is running or not.
My index.js file
myApp.run(['$rootScope', function($rootScope) {
document.addEventListener('deviceready', function() {
// Handle the Cordova pause and resume events
document.addEventListener( 'pause', onPause.bind( this ), false );
document.addEventListener( 'resume', onResume.bind( this ), false );
window.plugins.PushbotsPlugin.initialize(...);
window.plugins.PushbotsPlugin.on("registered", function(token){
console.log("Registration Id:" + token);
});
window.plugins.PushbotsPlugin.getRegistrationId(function(token){
console.log("Registration Id:" + token);
});
// Should be called once app receive the notification
window.plugins.PushbotsPlugin.on("notification:received", function(data){
alert("received:" + JSON.stringify(data));
console.log("received:" + JSON.stringify(data));
});
// Should be called once the notification is clicked
window.plugins.PushbotsPlugin.on("notification:clicked", function(data){
alert("Notification clicked"); only fires when the app is not running
$rootScope.$emit('onNotificationClick', data);
console.log("clicked:" + JSON.stringify(data));
});
}, false);
}]);
I have a $rootScope.onNotificationClick event in my MainAppController. Should I instantiate / pass the Pushbotsplugin to that controller somehow?
you are emitting the event on notification click. So you can handle $on in controller using below code
$rootScoope.$on('onNotificationClick', function (data) {
// handle here.
//need not pass pushBotPlugin
});
I have a problem with Ionic framework. I follow the guide to receive and send push notification, but something doesn't work.
When I launch the app, I press button Identify, and show my an alert that say the user ID. After, I press on register button, the phone show me an alert that contains the Device token(ANDROID). But when I go to ionic.io, in the dashboard of my app, the device token there isn't.
If I don't have the token saved on my dashboard, I can't send push notification.
Anyone can help me?
This is my controller.js:
angular.module('starter.controllers', [])
.controller('DashCtrl', function($scope, $rootScope, $ionicUser, $ionicPush) {
// Identifies a user with the Ionic User service
$scope.identifyUser = function() {
console.log('Ionic User: Identifying with Ionic User service');
var user = $ionicUser.get();
if(!user.user_id) {
// Set your user_id here, or generate a random one.
user.user_id = $ionicUser.generateGUID();
};
// Add some metadata to your user object.
angular.extend(user, {
name: 'Ionitron',
bio: 'I come from planet Ion'
});
// Identify your user with the Ionic User Service
$ionicUser.identify(user).then(function(){
$scope.identified = true;
alert('Identified user ' + user.name + '\n ID ' + user.user_id);
});
};
$rootScope.$on('$cordovaPush:tokenReceived', function(event, data) {
console.log('Got token', data.token, data.platform);
// Do something with the token
});
// Registers a device for push notifications and stores its token
$scope.pushRegister = function() {
console.log('Ionic Push: Registering user');
// Register with the Ionic Push service. All parameters are optional.
$ionicPush.register({
canShowAlert: true, //Can pushes show an alert on your screen?
canSetBadge: true, //Can pushes update app icon badges?
canPlaySound: true, //Can notifications play a sound?
canRunActionsOnWake: true, //Can run actions outside the app,
onNotification: function(notification) {
// Handle new push notifications here
// console.log(notification);
return true;
}
});
};
// Handles incoming device tokens
$rootScope.$on('$cordovaPush:tokenReceived', function(event, data) {
alert("Successfully registered token " + data.token);
console.log('Ionic Push: Got token ', data.token, data.platform);
$scope.token = data.token;
});
})
.controller('ChatsCtrl', function($scope, Chats) {
// With the new view caching in Ionic, Controllers are only called
// when they are recreated or on app start, instead of every page change.
// To listen for when this page is active (for example, to refresh data),
// listen for the $ionicView.enter event:
//
//$scope.$on('$ionicView.enter', function(e) {
//});
$scope.chats = Chats.all();
$scope.remove = function(chat) {
Chats.remove(chat);
};
})
.controller('ChatDetailCtrl', function($scope, $stateParams, Chats) {
$scope.chat = Chats.get($stateParams.chatId);
})
.controller('AccountCtrl', function($scope) {
$scope.settings = {
enableFriends: true
};
});
I follow the ionic guide step-by-step
In order to access the token on ionic.io , you have to push it through:
var push = new Ionic.Push();
var user = Ionic.User.current();
var callback = function(pushToken) {
console.log('Registered token:', pushToken.token);
user.addPushToken(pushToken);
user.save(); // you NEED to call a save after you add the token
}
push.register(callback);
as mentioned in the docs.
I've an app built with cordova and InAppBrowser. I'm trying to show a "loading spinner" in every page.
In iOS it's working well on every page I load, but Android fails.
On iOS I just edited self.spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] this line in CDVInappBrowser.m and works.
Does Android have a similar feature ?
Here is my code:
// Cordova is ready
function onDeviceReady() {
var ref = window.open("http://m.estadao.com.br/?load-all=true", "_blank", "location=no", "toolbar=no", "closebuttoncaption=a", "EnableViewPortScale=no");
navigator.notification.activityStart("Loading", "Loading...");
setTimeout(function(){
navigator.notification.activityStop();
}, 5000);
}
Check this plugin:
https://github.com/Paldom/SpinnerDialog
Working for me in Android. You should use this method to show a spinner with title and message:
window.plugins.spinnerDialog.show("Loading","Loading...");
Your code would be:
function onDeviceReady() {
var ref = window.open("http://m.estadao.com.br/?load-all=true", "_blank", "location=no", "toolbar=no", "closebuttoncaption=a", "EnableViewPortScale=no");
window.plugins.spinnerDialog.show("Loading","Loading...");
setTimeout(function(){
window.plugins.spinnerDialog.hide();
}, 5000);
}
Resvolvi dessa forma
//window.open Example
// Wait for device API libraries to load
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
// external url
// var ref = window.open(encodeURI('http://mfsom.com.br/'), '_blank', 'location=no','toolbar=no');
//relative document
ref = window.open('http://mfsom.com.br/','_self',',location=no');
ref.addEventListener('loadstart', loadstartCallback);
ref.addEventListener('loadstop', loadstopCallback);
ref.addEventListener('loadloaderror', loaderrorCallback);
ref.addEventListener('exit', exitCallback);
function loadstartCallback(event) {
showSpinnerDialog();
}
function loadstopCallback(event) {
hideSpinnerDialog();
}
function loaderrorCallback(error) {
console.log('Erro ao carregar: ' + error.message)
}
function exitCallback() {
console.log('O navegador está fechado...')
}
function showSpinnerDialog() {
navigator.notification.activityStart("Carregando..");
//$.mobile.loading("show");
}
function hideSpinnerDialog() {
navigator.notification.activityStop();
//$.mobile.loading("hide");
}
// Handle the Cordova pause and resume events
document.addEventListener( 'pause', onPause.bind( this ), false );
document.addEventListener( 'resume', onResume.bind( this ), false );
// TODO: Cordova has been loaded. Perform any initialization that requires Cordova here.
};
As both the answers here use the activityStop() which is deprecated, use your own spinner which you use in your app to prevent InAppBrowser's blank opening screen
Open the InAppBrowser in using hidden=yes option and later in loadstop event listener show the InAppBrowser. Till then you can show your custom loader
var ref = window.open("http://m.estadao.com.br/?load-all=true", "_blank", "location=no,toolbar=no,closebuttoncaption=a,EnableViewPortScale=no,hidden=yes");
ref.addEventListener('loadstart', function() {
showLoader();//`showLoader()` is your own loader function to show loader within your app
});
ref.addEventListener('loadstop', function() {
ref.show();
hideLoader();//`hideLoader()` is your own loader function to hide loader within your app
});