August 13, 2021

Android – Handle additional parameter in onesignal

By lj007

Handle additional parameter in onesignal

This post is to demonstrate how we can handle additional parameters in onesignal. If you don’t know how to add onesignal in android, please visit my previous post.
We need to override OneSignal.NotificationOpenedHandler.

NotificationOpenedHandler

import android.app.Application
import android.content.Intent
import com.onesignal.OSNotificationOpenResult
import com.onesignal.OneSignal

class ITradeZonNotificationHandler(private val app: Application) : OneSignal.NotificationOpenedHandler{
    override fun notificationOpened(result: OSNotificationOpenResult?) {
        if(result == null) return
        val jsonData = result.notification.payload.additionalData

        if(jsonData != null){
            val orderId = jsonData.optString("orderId", null)
            if(orderId != null){
                //We are ready to open order details for this orderId
                app.startActivity(Intent(app, OrderDetailsActivity::class.java).putExtra("orderId", orderId))
            }
        }
    }
}

Note that, here we are passing application in class, it is required to start activity from Handler. This class will handle all push-notifications. We also need to add this class, when we init oneSignal. Look below code

      // This must be added in Application class to init onesignal
      OneSignal.startInit(this)
            .inFocusDisplaying(OneSignal.OSInFocusDisplayOption.Notification)
            .unsubscribeWhenNotificationsAreDisabled(true)
            .setNotificationOpenedHandler(ITradeZonNotificationHandler(this))
            .init()