Configurer des notifications push dans votre Android application

  • Rversion finale: Xanadu
  • Mis à jour 1 août 2024
  • 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 consiste à récupérer le NowPushService du NowSDK. Ajoutez un code similaire à l’extrait de code suivant au début de votre corps de 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 à NowPushSDK : makePushService(instanceURL : URL).

    Enregistrer le jeton push

    Google Firebase fournit un jeton push unique qui identifie l’appareil et l’application pour recevoir des 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 à modifier 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 : runnable, errorcallback : Consumer<Throwable>).

    Annuler l’inscription du jeton push

    Vous devez annuler l’inscription du jeton push chaque fois que l’utilisateur quitte votre application, par exemple lorsqu’il se déconnecte. Utilisez un code similaire à l’extrait de code suivant pour annuler l’inscription du jeton push. Veillez à modifier 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 : Consumer<Throwable>).

    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 d’Android Firebase.

    Une fois la configuration effectuée, remplacez la méthode onMessageReceived() et transmettez-la RemoteMessage à NowPushService. Si NowPushService reconnaît la notification, il la traite et renvoie l’objet de notification pour que l’application la gère. 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>).

    De plus, vous devez remplacer onNewToken(token : String). Assurez-vous de transmettre le jeton à pushService.registerPushToken(), comme dans la section « Enregistrer le jeton push ».