嗨,这是
中问题的副本Push Notifications in Ionic 2 with the Pub/Sub Model
我已经在本文后面实现了推送通知> https://medium.com/@ankushaggarwal/push-notifications-in-ionic-2-658461108c59#.xvoeao59a
我想要的是能够在应用程序中发生某些事件(如聊天或预订或新职位)时向用户发送通知。
如何更进一步,这是我的第一个应用程序。
答案 0 :(得分:1)
注意:代码与教程几乎完全相同,Java只转换为Kotlin
这是我的实际离子侧代码(在登录页面上)。当用户打开应用程序时,push.on('registration')
将被触发,稍后(成功登录时)变量this.device_id
将被发送到我的Kotlin REST API,因此我知道device_id并将其耦合到用户。这样您就可以发送有针对性的推送通知。
如果您从Kotlin发送推送通知(代码如下所示,看起来有点像Java),那么(通常打开,甚至在启动后打开)与Google的连接将发送您的设备(由device_id
定义带有通知数据(标题,消息等)的消息,在此消息之后,您的设备将识别senderID
并将其匹配以使用离子应用程序。
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代码(从Java示例转换,基本相同
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)
}
}
}
}
然后该方法可以被称为PushNotification.sendPush(user1, "Hello world!", "my title");
(btw意识到你不需要从服务器(localhost / external)运行推送通知。你可以创建一个主类,用你的硬编码deviceId
发送它以进行测试强>