Configuration des notifications push dans votre Android application

  • Rversion finale: Yokohama
  • Mis à jour 30 janv. 2025
  • 2 minutes de lecture
  • En plus des tâches que vous devez effectuer sur votre ServiceNow® instance pour configurer une notification push, vous devez également inclure du code spécifique dans votre Android application.

    Créer le NowSDK NowPushService

    L’une des premières choses à faire dans votre application est de récupérer le NowSDK NowPushService. Ajoutez du code similaire à l’extrait suivant au début dans le corps de votre code principal.

    /**
     * Helper class used to handle different Now service instances.
     */
    @Singleton
    class SdkManager @Inject constructor() {
    
        private var nowPushService: NowPushService? = null
    
        /**
         * Create the NowPushService once in the lifetime of the application inside the Application
         * class or another manager class that will be injected into other classes via dagger/hilt.
         * NowPushService should be created after initializing the NowSDK
         */
        suspend fun getNowPushService(): NowPushService? {
            if (nowPushService != null) return nowPushService
    
            return NowPushSDK.makePushService(URL("https://instance-name.service-now.com")).getOrThrow()
                .also { this.nowPushService = it }
        }
    }

    Pour plus d’informations sur la méthode NowPushSDK.makePushService(), reportez-vous à la section NowPushSDK : makePushService(instanceURL : URL).

    Enregistrer le jeton push

    Google Firebase Fournit un jeton push unique qui identifie l’appareil et l’application pour recevoir les notifications push. Pour qu’une application reçoive une notification push, vous devez enregistrer ce jeton à l’aide de NowPushService. Ajoutez une fonction similaire à l’extrait de code suivant dans votre Android application. Veillez à changer PushAppName le nom de votre Android application. Cette application doit être enregistrée auprès de votre ServiceNow® instance.

    FirebaseMessaging.getInstance().token.addOnCompleteListener {task ->
      val token = task.result
    
      if (!task.isSuccessfull || token == null) {
        throw Exception("Unable to fetch token"))
      }
    
      pushService.registerPushToken(token, "PushAppName", {
          Log.v(TAF, "Successfully registered push token")
      }, { e ->
          Log.e(TAG, "Error registrating push", e)
      })
    }

    Pour plus d’informations sur la méthode registerPushToken(), reportez-vous à .NowPushService : registerPushToken(pushToken : chaîne, pushApp : chaîne, successCallback : exécutable, errorCallback : consommateur<jetable>)

    Annuler l’enregistrement du jeton push

    Vous devez annuler l’enregistrement du jeton push chaque fois que l’utilisateur quitte votre application, par exemple lorsque l’utilisateur se déconnecte. Utilisez un code similaire à l’extrait de code suivant pour annuler l’inscription du jeton push. Veillez à changer PushAppName le nom de votre Android application.

    pushService.unregisterPushToken(token, "PushAppName", {
          Log.v(TAG, "Successfully unregistered push token")
    }, { e ->
          Log.e(TAG, "Error unregistering push", e)
    })

    Pour plus d’informations sur la méthode unregisterPushToken(), reportez-vous à .NowPushService : unregisterPushToken(pushToken : chaîne, pushApp : chaîne, successCallback : exécutable, errorCallback : consommateur<jetable>)

    Implémenter FirebaseMessagingService

    Vous devez implémenter FirebaseMessagingService au sein de votre application. Pour configurer et implémenter ce service, suivez les instructions de la documentation Android Firebase.

    Une fois la configuration effectuée, remplacez la méthode onMessageReceived() et transmettez la RemoteMessage méthode à NowPushService. Si le NowPushService reconnaît la notification, il la traite et renvoie l’objet de notification à l’application. Actuellement, la seule notification implémentée est NowPushVirtualAgent. Une notification inconnue renvoie un objet NotSupportedPushError .

    //Custom coroutineScope created in the Firebase service class
    private val serviceCoroutineScope = CoroutineScope(Dispatchers.IO)
    
    override fun onMessageReceived(remoteMessage: RemoteMessage) {
      serviceCoroutineScope.launch {
        val result = handleNowPush(remoteMessage)
    
        if (result.isSuccess) {
          when (val push = result.getOrNull()) {
            is NowPushVirtualAgent -> handleVirtualAgentPush(push)
          }
        } else {
          // Not a NowPush. Handle host app push notification message here
        }
      }
    }
    
    private suspend fun handleNowPush(remoteMessage: RemoteMessage): Result<NowPushPayload> {
      val nowPushService = sdkManager.getNowPushService()
    
      return suspendCoroutine { cont ->
        nowPushService?.handlePush(remoteMessage,
          { cont.resume(Result.success(it)) }, { cont.resumeWithException(it) })
      }
    }

    Pour plus d’informations sur la méthode handlePush(), reportez-vous à .NowPushService : handlePush(remoteMessage : RemoteMessage, successCallback : Consumer<NowPushPayload>, errorCallback : Consumer<Throwable>)

    En outre, vous devez remplacer onNewToken(token : String). Assurez-vous de transmettre le jeton à pushService.registerPushToken(), comme cela a été fait dans la section « Enregistrer le jeton push ».