注:代码几乎是完全一样的教程,Java已经仅被转换为科特林
这是我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);
});
});
}
科特林代码(从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");
(顺便说一句,你不需要从服务器(localhost/external)运行pushnotification。您可以创建一个主类,将其与您的硬编码deviceId
一起发送用于测试目的。
你有你的离子应用程序链接到某种后端(f.e. Java REST API)吗? – Ivaro18
不,我正在使用firebase作为数据库和文件存储 – dhruv
@ Ivaro18将后端为服务器设置代码所需? – dhruv