Android Sinch Push SDK

This is documentation how to easily implement our SDK for push features.

Prerequisites

  • Android Studio and Android SDK tools available here .
  • Android 5.0 Lollipop - min SDK 21
  • Access to SDK GitHub repository

Create Android Studio project

Create a new Android Studio project using the 'Empty activity' template.

Setting up Maven and adding dependencies

In your Android project tree, open the settings.gradle file and add the following code to the repositories element under dependencyResolutionManagement:

Copy
Copied
maven({
   url "https://raw.githubusercontent.com/sinchlabs/sinch-chat-android-sdk/master/releases"
   credentials(HttpHeaderCredentials) {
      name = "Authorization"
      value = "Bearer {your github personal token}"
   }
   authentication {
      header(HttpHeaderAuthentication)
   }
})

Next, open the application's build.gradle file and add the following line to the dependencies element:

Copy
Copied
implementation 'com.sinch.chat.sdk:sinch-sdk:{version}'

Save both files and build your project.

Overview

To set up your application to start sending notifications, you need to perform the following steps:

  1. Initialize the SDK as soon as the application starts.
  2. Set the identity of the user.
  3. Set up push notifications.

Initialize the SDK

To initialize the SDK, you need to add the SinchChatActivity activity to the AndroidManifest.xml file:

Copy
Copied
<activity android:name="com.sinch.chat.sdk.SinchChatActivity"/>

Then we need to call the initialize method. Since we want to initialize the SDK as soon as possible, the best place to do this is in the MainActivity.kt file, in the onCreate method. It looks something like this:

Copy
Copied
override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            SinchChatSDK.initialize(applicationContext)
        }
    }

Set the identity

We need to authorize the user next. To do that, call this method as early as possible to authorize the user:

Copy
Copied
fun setIdentity(config: SinchConfig, identity: SinchIdentity, completion: (Result<Unit>) -> Unit)

Example:

Copy
Copied
val currentIdentity = SinchIdentity.SelfSigned({your_user_id}, {signed token})
val currentEnvironment = SinchConfig({client_id}, {project_id}, {config_id}, {region}, {language})

SinchChatSDK.setIdentity(
    currentEnvironment,
    currentIdentityType
) {
  if (it.isSuccess) {
        Toast.makeText(this, "Set Identity success", Toast.LENGTH_LONG).show()
        Log.d(TAG, "Set Identity success")
    } else {
        Toast.makeText(this, "Set Identity failed", Toast.LENGTH_LONG).show()
        Log.d(TAG, "Set Identity failed with message: ${it.exceptionOrNull()?.message}")
    }
}

You can call this method as many times as you want. Depending on your needs, you can place the method in the MainActivity.kt file or another file which will be run early in the application lifecycle.

Set the configuration parameters

To connect your Sinch Push client to your Sinch account, you need to set the following parameters in the MainActivity.kt file:

Parameter Description
project_id Get your project ID from your Sinch Dashboard.
client_id Get your client ID from your Sinch Dashboard.
region Use either EU1 for Europe or US1 for the United States.
config_id Get your configuration ID from your Sinch Dashboard
secret If you have configured an optional secret token in your Sinch Dashboard, enter it here.

Generating a signed token

Sinch must recognize your users somehow, and the most secure way to authenticate is with a signed token.

It is NOT recommended to sign user_id on mobile app.

Important!

You should implement this algorithm and serve it from your backend infrastructure via API interface to prevent any kind of attacks.

Algorithm implementation in Kotlin:

Copy
Copied
object HmacSha512 {

    fun generate(message: String, key: String): String {
        val mac: Mac = Mac.getInstance("HmacSHA512")
        mac.init(SecretKeySpec(key.encodeToByteArray(), mac.algorithm))
        return mac.doFinal(message.encodeToByteArray()).joinToString(separator = "") { "%02x".format(it) }
    }
}

Example of usage in app:

Copy
Copied
    val tokenSecret = "{{token-secret}}"
    val userID = "{{your-internal-id}}"
    val signedUUID = HmacSha512.generate(userID, tokenSecret)
    val currentIdentityType = SinchIdentity.SelfSigned(userID, signedUUID)

And now you can use SDK functionalities like push.

Set up push notifications

To use push notifications with this SDK you have to provide a Firebase token and upload it to the dashboard.

Note:

Push notifications work via the Firebase service so you need to make sure we have your server token.

Initialize SDK with push notification token

If you want to initialize SDK with push notification support you should put this snippet of code into your MainActivity class.

Example:

Copy
Copied
// MainActivity.kt

FirebaseMessaging.getInstance().token.addOnCompleteListener { task ->

   val options = SinchInitializationOptions(null)
   if (task.isSuccessful) {
      options.pushDeviceToken = task.result
   }
   SinchChatSDK.initialize(applicationContext, options)
}

Setup Firebase Messaging service

Add the following dependencies to your app in the build.gradle file:

Copy
Copied
implementation platform('com.google.firebase:firebase-bom:{version}')
implementation 'com.google.firebase:firebase-messaging:{version}'
implementation 'com.google.firebase:firebase-analytics-ktx'

In the AndroidManifest.xml file, add the new service for push notifications:

Copy
Copied
<service
   android:name=".AppFirebaseMessagingService"
   android:exported="false">
   <intent-filter>
      <action android:name="com.google.firebase.MESSAGING_EVENT" />
   </intent-filter>
</service>

Create a file called: AppFirebaseMessagingService to match android:name and paste this code into the file:

Copy
Copied
class AppFirebaseMessagingService : FirebaseMessagingService() {

   override fun onNewToken(p0: String) {
      super.onNewToken(p0)
      SinchChatSDK.push.onNewToken(p0)
   }

   override fun onMessageReceived(p0: RemoteMessage) {
      super.onMessageReceived(p0)
      if (SinchChatSDK.push.onMessageReceived(p0)) {
         // This notification belongs to SinchChatSDK.
         return
      }
   }
}

Troubleshooting

You may experience errors with building your application. The errors are related to dependencies which we're using which are related to Protobuf.

Paste the following lines in your the android element in the build.gradle file:

Copy
Copied
    configurations {
        implementation.exclude module:'protolite-well-known-types'
        implementation.exclude module:'protobuf-lite'
        implementation.exclude module:'javax.annotation-api'
    }

Next steps

After your client is set up, now you can configure the Sinch Push channel in the Conversation API and start sending notifications.

We'd love to hear from you!
Rate this content:
Still have a question?
 
Ask the community.