How to use OneSignal notification buttons in Flutter - flutter

I am using OneSignal API for sending and receiving notifications with my Flutter app. And I don't know how to use the buttons that can be added to the notification to open my flutter app to a specific screen.
My use case of the API is to create a notification template that has a button on it and send it to my users. But I don't know how to set a listener on that button that will open my flutter app.
I am using onesignal-node package for my node server.
let firstNotification = new OneSignal.Notification({
template_id: "727f42a8-0b45-470e-ac9e-908f64af44ba",
include_external_user_ids: [_id]
});
myClient.sendNotification(firstNotification, function (err, httpResponse, data) {
if (err) {
return res.status(500).send(err);
} else {
console.log(data, httpResponse.statusCode);
return res.status(200).send("Notification sent to " + user);
}
});

This is the solution
buttons: [
OSActionButton(text: "text button 1", id: "id1"),
OSActionButton(text: "text button 2", id: "id2")
],
but i dont know how i set an event to the button =(

Related

Ionic4 OneSignal open push notification redirect page

Was hoping to achieve when OneSignal push notification was being opened would redirect to a certain page in the App. Following is my code to redirect to a page called positions but it didn't seem to work. When the push notification is opened, it still opens up the url in the InAppBrowser. Any idea what went wrong? Thanks in advance.
if (this.appConfig.Onesignal_Enable == true) {
this.oneSignal.startInit(this.appConfig.OneSignal_AppID, this.appConfig.GCM_SenderID);
this.oneSignal.handleNotificationReceived().subscribe(() => {
// do something when notification is received
});
this.oneSignal.handleNotificationOpened().subscribe((data) => {
// do something when a notification is opened
// the following two lines pass data I send with the push notification so the app knows what to open
let pushaction = data.notification.payload.additionalData.action;
let pushactionvalue = data.notification.payload.additionalData.actionvalue;
// this fires up the tab-switching
this.runNotificationAction(pushaction, pushactionvalue);
});
this.oneSignal.endInit();
}
runNotificationAction(pushaction, pushactionvalue){
// this is the data passed the the other page
let data = {"action": pushaction, "value:": pushactionvalue};
this.navCtrl.navigateForward('positions');
}
Hello I'm using v4 ionic too and I achieved this with this implementation on my project:
let self = this;
var notificationOpenedCallback = async function(jsonData) {
//I use info data previous saved, but you can use jsonData
switch (self.user.role) {
case "customer":
self.router.navigate(["history-customer"]);
break;
case "provider":
self.router.navigate(["history-provider"]);
}
};
window["plugins"].OneSignal.startInit(
"0*************7",
"1*********2"
)
.handleNotificationOpened(notificationOpenedCallback)
.endInit();
window["plugins"].OneSignal.setSubscription(true);
I use
let self = this
because startInit receive a callback so is necessary to do that, in your case I don't know if inside subscribe need also use "self" and I use Router to navigate between pages.
import { Router } from "#angular/router";
And on my app-routing.module.ts
{ path: 'history-provider', loadChildren: './pages/history-provider/history-provider.module#HistoryProviderPageModule' },
{ path: 'history-customer', loadChildren: './pages/history-customer/history-customer.module#HistoryCustomerPageModule' }

Ionic FCM push notifications observable does not emit

I am doing the following in an ionic application:
When a user is logged in, subscribe to their user ID topic
When a push notification arrives, console.log something.
this.authState.subscribe((state) => {
if (state) {
this.fcmPush.subscribeToTopic(state.uid);
this.fcmPush.onNotification().subscribe(notification => {
if (notification.wasTapped) {
console.log('Received in background', notification);
} else {
console.log('Received in foreground', notification);
}
});
}
});
Source: https://github.com/AmitMY/ionic-starter-firebase/blob/master/src/app/app.component.ts#L118
Sending a notification to my own topic arrives (after a few minutes), but I never see anything in console, both from outside the app, and inside the app.
What am I doing wrong?
Sending a notification from firebase messaging does not work.
However, using the sdk I must add:
click_action: "FCM_PLUGIN_ACTIVITY",
Which is in the usage guide but I missed

How to dismiss alert on back key press in android?

I'm trying to close alert when the alert is present with back key press else the page will be navigated to another page. I've tried alert.dismiss(), but how to find out if the alert is present or not? I want also to do the same with ion-select.
Ionic 3 way of doing it:
showAlert() {
let alert = this.alertCtrl.create({
title: 'My Title',
buttons: [
{
text: 'Ok'
}
]
});
alert.present();
let deregisterBackButton = this.platform.registerBackButtonAction(() => {
// dismiss on back press
alert.dismiss();
}, 401);
// deregister handler after modal closes
alert.onDidDismiss(() => {
deregisterBackButton();
});
}
You could try this using registerBackButtonAction
this.platform.registerBackButtonAction(() => {
try {
this.viewController.dismiss()
}
catch(e) {
... no overlay component open
}
})
To check if an alert is present, you can do a check to see if an overlay is present using something like this proposed solution.

implement Push Notifications in Ionic 2 with the Pub/Sub Model

Hi this is a duplicate of the question at
Push Notifications in Ionic 2 with the Pub/Sub Model
i have already implemented push notifications following this article >
https://medium.com/#ankushaggarwal/push-notifications-in-ionic-2-658461108c59#.xvoeao59a
what i want is to be able to send notifications to users when some events take place in the app like chat or booking or new job post.
how to go further , this is my first app.
NOTE: code is almost exactly the same as the tutorial, Java has only been converted to Kotlin
This is my acutal ionic side code (on login page). The push.on('registration') will be fired when the user opens the app, the variable this.device_id will later (on succesfull login) be sent to my Kotlin REST API so I know the device_id and have coupled it to a user. This way you can send targeted push notifications.
If you send a push notification from Kotlin (code shown below, looks a bit like Java), the (always open, even opens after startup) connection to Google will send your device (defined by the device_id a message with the notification data (title, message, etc.) after which your device will recognize the senderID and match it to use your ionic application.
initializeApp() {
this.platform.ready().then(() => {
let push = Push.init({
android: {
senderID: "1234567890"
},
ios: {
alert: "true",
badge: false,
sound: "true"
},
windows: {}
});
//TODO - after login
push.on('registration', (data) => {
this.device_id = data.registrationId;
});
push.on('notification', (data) => {
console.log('message', data.message);
let self = this;
//if user using app and push notification comes
if (data.additionalData.foreground) {
// if application open, show popup
let confirmAlert = this.alertCtrl.create({
title: data.title,
message: data.message,
buttons: [{
text: 'Negeer',
role: 'cancel'
}, {
text: 'Bekijk',
handler: () => {
//TODO: Your logic here
this.navCtrl.setRoot(EventsPage, {message: data.message});
}
}]
});
confirmAlert.present();
} else {
//if user NOT using app and push notification comes
//TODO: Your logic on click of push notification directly
this.navCtrl.setRoot(EventsPage, {message: data.message});
console.log("Push notification clicked");
}
});
push.on('error', (e) => {
console.log(e.message);
});
});
}
Kotlin code (converted from the Java example, basically the same
package mycompany.rest.controller
import mycompany.rest.domain.User
import java.io.OutputStream
import java.net.HttpURLConnection
import java.net.URL
class PushNotification {
companion object {
val SERVER_KEY = "sOmE_w31rD_F1r3Ba5E-KEy";
#JvmStatic fun sendPush(user: User, message: String, title: String) {
if(user.deviceId != "unknown"){
val pushMessage = "{\"data\":{\"title\":\"" +
title +
"\",\"message\":\"" +
message +
"\"},\"to\":\"" +
user.deviceId +
"\"}";
val url: URL = URL("https://fcm.googleapis.com/fcm/send")
val conn: HttpURLConnection = url.openConnection() as HttpURLConnection
conn.setRequestProperty("Authorization", "key=" + SERVER_KEY)
conn.setRequestProperty("Content-Type", "application/json")
conn.setRequestMethod("POST")
conn.setDoOutput(true)
//send the message content
val outputStream: OutputStream = conn.getOutputStream()
outputStream.write(pushMessage.toByteArray())
println(conn.responseCode)
println(conn.responseMessage)
}else {
println("Nope, not executed")
}
}
#JvmStatic fun sendPush(users: List<User>, message: String, title: String) {
for(u in users) {
PushNotification.sendPush(u, message, title)
}
}
}
}
Then the method can be called as PushNotification.sendPush(user1, "Hello world!", "my title");
(btw realized you won't need to run the pushnotification from a server (localhost/external). You can just create a main class which sends it with your hardcoded deviceId for testing purposes.

BlackBerry WebWorks to invoke popping BB10 Share panel/screen

How can u get my webworks app to pop open the blackberry 10 share panel?
Ex: open a website in the browser, click the overflow button and then click share
Thank you!
You'll want to look at the invokeTargetPicker API.
Essentially, you create a request
var request = {
action: 'bb.action.SHARE',
// for a file
uri: 'file://' + path,
// for text you'd use 'data'
data: 'I am awesome',
target_type: ["APPLICATION", "VIEWER", "CARD"]
};
Then you call the API
blackberry.invoke.card.invokeTargetPicker(request, "Your Title",
// success callback
function() {
console.log('success');
},
// error callback
function(e) {
console.log('error: ' + e);
}
);
API Documentation is available here: https://developer.blackberry.com/html5/apis/blackberry.invoke.card.html#.invokeTargetPicker
I wrote a sample app, which you can test out on our GitHub repo: https://github.com/ctetreault/BB10-WebWorks-Samples/tree/master/ShareTargets
This should be an option that appears on any link, image or Text: "Share". Is the item not present in the Cross Cut menu shown?