Setting up your project to work with the SDK - GlobalMessageServices/BCS-GMS-SDK-Android GitHub Wiki

Table of contents

  1. Add Firebase cloud messaging to your project
  2. Get credentials for your app
  3. Add the SDK to your project
  4. Extend the PushKFirebaseService
  5. Start using the SDK
  6. More

Add Firebase cloud messaging to your project

You need to connect your app to your firebase project

  • Create a project at https://console.firebase.google.com/ (or use an existing one) image
  • Add required dependencies to your android studio project (either manually or use Firebase Assistant plugin for Android Studio) image image image

Recommended dependency versions to use within your app (or use whatever would be compatible with what is used within the SDK):

  • Project (top-level) build.gradle:
buildscript {
   dependencies {
       ...
       classpath 'com.google.gms:google-services:4.3.4'
   }
}
  • Module (app-level) build.gradle:
plugins {
    ...
    id 'com.google.gms.google-services'
}

dependencies {
    ...
    implementation 'com.google.firebase:firebase-messaging:21.0.0'
}
  • Make sure you add proper google-services.json file to the root of your app module Read more at: https://firebase.google.com/docs/android/learn-more !!!Starting with Gradle 7 repositoriesMode in settings.gradle (Project Settings) should be changed as showed below:
	dependencyResolutionManagement {
		repositoriesMode.set(RepositoriesMode.PREFER_PROJECT)
		repositories{
                            
		}
	}

Get credentials for your app

Provide your firebase project's cloud messaging server key and application fingerpint to the PushSDK representative, and obtain required credentials to work with the SDK

image image

Follow the next steps to get app fingerprint:

Generate key and keystore

  1. In the menu bar, click Build > Generate Signed Bundle/APK.
  2. In the Generate Signed Bundle or APK dialog, select Android App Bundle and click Next.
  3. Below the field for Key store path, click Create new.
  4. On the New Key Store window, provide the following information for your keystore and key.
  5. Keystore
    • Key store path: Select the location where your keystore should be created. Also, a file name should be added to the end of the location path with the .jks extension.
    • Password: Create and confirm a secure password for your keystore.
  6. Key
    • Alias: Enter an identifying name for your key.
    • Password: Create and confirm a secure password for your key. This should be the same as your keystore password.
    • Validity (years): Set the length of time in years that your key will be valid. Your key should be valid for at least 25 years, so you can sign app updates with the same key through the lifespan of your app.
    • Certificate: Enter some information about yourself for your certificate. This information is not displayed in your app, but is included in your certificate as part of the APK.
      image
  7. Once you complete the form, click OK.

Sign your app with your key

To sign your app using Android Studio, and export an existing app signing key, follow these steps:

  1. If you don’t currently have the Generate Signed Bundle or APK dialog open, click Build > Generate Signed Bundle/APK.
  2. In the Generate Signed Bundle or APK dialog, select either Android App Bundle click Next.
  3. Select a module from the drop down.
  4. Specify the path to your keystore, the alias for your key, and enter the passwords for both.
    image
  5. Click Next
  6. In the next window, select a destination folder for your signed app, select the build variant.
    image
  7. Click Finish.

To get the certificate fingerprint run the keytool utility provided with Java:

keytool -list -v -keystore C:\Users\user_name\debug-keystore.jks

where C:\Users\user_name\debug-keystore.jks is key store path.
Read more at: https://developer.android.com/studio/publish/app-signing#generate-key and https://developers.google.com/android/guides/client-auth

Add the SDK to your project

Make sure you have declared maven repository in your project (top-level) build.gradle

allprojects {
    repositories {
        ...
        maven {
            url 'https://jitpack.io'
        }
    }
}

Add SDK dependency to your module (app-level) build.gradle.

dependencies {
    ...
    //or use a newer version if available
    'com.github.GlobalMessageServices:Hyber-GMS-SDK-Android:v1.0.0.55-RELEASE'
}

v1.0.0.50 and higher now supports http protocol (in case your remote api is using http)
To use http protocol instead of https, add android:usesCleartextTraffic="true" to your application tag inside android manifest

<application
        ...

        android:usesCleartextTraffic="true"
        >

Extend the PushKFirebaseService

Create a class that extends PushKFirebaseService
Specify title and text which may be displayed by the system in the "summary notification".
Read more about receiving push messages and displaying notifications using the PushSDK here.

class MyPushKFirebaseService : PushKFirebaseService(
    summaryNotificationTitleAndText = Pair("title", "text")
) {

    override fun setNotificationStyle(
        notificationConstruct: NotificationCompat.Builder,
        data: Map<String, String>,
        notificationStyle: NotificationStyle
    ) {
        super.setNotificationStyle(notificationConstruct, data, notificationStyle)
    }

    /**
     * Called when data push is received from the Messaging Hub
     */
    override fun onReceiveDataPush(
        appIsInForeground: Boolean,
        isDoNotDisturbModeActive: Boolean,
        areNotificationsEnabled: Boolean,
        isNotificationChannelMuted: Boolean,
        remoteMessage: RemoteMessage
    ) {
        super.onReceiveDataPush(
            appIsInForeground,
            isDoNotDisturbModeActive,
            areNotificationsEnabled,
            isNotificationChannelMuted,
            remoteMessage
        )

        //can be used to configure, for example set "isDoNotDisturbModeActive" to false,
        // to send notifications in "Do not disturb mode" anyways
//        super.onReceiveDataPush(
//            appIsInForeground = appIsInForeground,
//            isDoNotDisturbModeActive = false,
//            areNotificationsEnabled = areNotificationsEnabled,
//            isNotificationChannelMuted = isNotificationChannelMuted,
//            remoteMessage = remoteMessage
//        )
    }

    /**
     * Callback - when notification is sent
     */
    override fun onNotificationSent(
        appIsInForeground: Boolean,
        isDoNotDisturbModeActive: Boolean,
        areNotificationsEnabled: Boolean,
        isNotificationChannelMuted: Boolean,
        remoteMessage: RemoteMessage
    ) {
        super.onNotificationSent(
            appIsInForeground,
            isDoNotDisturbModeActive,
            areNotificationsEnabled,
            isNotificationChannelMuted,
            remoteMessage
        )
    }

   

 /**
     * Callback - when notification will not be sent
     */
    override fun onNotificationWontBeSent(
        appIsInForeground: Boolean,
        isDoNotDisturbModeActive: Boolean,
        areNotificationsEnabled: Boolean,
        isNotificationChannelMuted: Boolean,
        remoteMessage: RemoteMessage
    ) {
        super.onNotificationWontBeSent(
            appIsInForeground,
            isDoNotDisturbModeActive,
            areNotificationsEnabled,
            isNotificationChannelMuted,
            remoteMessage
        )
    }
    /**
     * Prepares NotificationCompat.Builder object for showing
     */
    override fun prepareNotification(data: Map<String, String>): NotificationCompat.Builder? {
        return super.prepareNotification(data)
        //can customize NotificationCompat.Builder object here, e.g.:
//        val notificationConstruct = pushSdkNotificationManager.constructNotification(data, PushSdkNotificationManager.NotificationStyle.BIG_TEXT)
//        notificationConstruct?.apply {
//            setContentText("some new text")
//        }
//        return notificationConstruct
    }
}

Add the service to your AndroidManifest.xml

<application
...>
<service
    android:name=".MyPushKFirebaseService"
    android:enabled="true"
    android:exported="true"
    android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE"
    android:stopWithTask="false">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
</service>
</application>

Start using the SDK

Make sure you have extended the PushKFirebaseService and added it to the AndroidManifest.xml

Init the SDK with the following basic parameters:

  • context - the context you would like to use
  • baseApiUrl - base URL path to the API
val pushSDK = PushSDK(
    context = this,
    baseApiUrl = "https://yourapilink.com/version/3.0" // API url that you would be provided with
)

Register your device/application:

  • Either register your device by using:
val answer1 = pushSDK.registerNewDevice(
    "clientAPIKey",  //API key that you would be provided with
    "appFingerprint", //APP fingerprint 
    "88002000600", //Device's phone number
    "UserPassword" //password, associated with Device's phone number (legacy - it is unused, you can put any value))
Log.d("TAG", answer1.toString())

Which would produce a similar output if successful:

D/TAG: PushKFunAnswerRegister(code=200, result=Ok, description=Success, deviceId=1066, token=c71b4bc05ee24f8eac007cc63d8ff2c4, userId=82, userPhone=88002000600, createdAt=2020-10-29T08:12:33.194942+00)

Then update registration:

val answer2 = pushSDK.updateRegistration()
Log.d("TAG", answer2.toString())

Which would produce a similar output if successful:

D/TAG: PushKFunAnswerGeneral(code=200, result=OK, description=Success, body={"deviceId": 1066})

This will register the device within the system and automatically pick up your current firebase cloud messaging token

  • Or register your device by manually specifying your firebase cloud messaging token:
val answer1 = pushSDK.registerNewDevice(
    "clientAPIKey",  //API key that you would be provided with
    "appFingerprint", //APP fingerprint 
    "userMsisdn", //Device's phone number
    "userPassword", //password, associated with Device's phone number (legacy - it is unused, you can put any value)
    "firebaseToken" //your firebase cloud messaging token  (Optional)
)
Log.d("TAG", answer1.toString())

This will register the device within the system and use the specified firebase cloud messaging token
Note: In case you are trying out this code for the first time, you may want to unregister all devices before registering a new one, so that registration would pass every time. You may do so by adding the following code before registering a device:

val answer0 = pushSDK.unregisterAllDevices()
Log.d("TAG", answer0.toString())

Your application should now be able to receive push messages from the api

Note: By default, notifications would only appear when your application is in background.

For more usage information - please see:

Receiving push messages and showing notifications

⚠️ **GitHub.com Fallback** ⚠️