Search code examples
ionic-frameworkpush-notificationcordova-pluginsionic2

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.


Solution

  • 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.