用Pub / Sub模型在Ionic 2中实现推送通知

嗨,这是一个重复的问题

用Pub / Sub模型在离子2中推送通知

我已经按照这篇文章实施了推送通知> https://medium.com/@ankushaggarwal/push-notifications-in-ionic-2-658461108c59#.xvoeao59a

我想要的是能够发送通知给用户,当一些事件发生在应用程序,如聊天或预订或新的工作岗位。

如何进一步,这是我的第一个应用程序。

注意:代码与教程几乎完全一样,Java只被转换为Kotlin

这是我的acutal离子代码(登录页面)。 当用户打开应用程序时, 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意识到你不需要从服务器(本地主机/外部)运行pushnotification。你可以创建一个主类,用硬编码的deviceId发送它deviceId进行测试。