FCM Util Android

TerraCore v0

Overview#

FCM Util is a helper module for integrating FCM to your application easier.

Prerequisite#

  • You has set up FCM for your app on firebase.

Installation#

Firstly please refer to Teko repository access guide for instruction to setup the environment.

When the environment is ready, add the code below to import FCM Util:

Using Gradle

Add to your project's build.gradle.kts

implement("vn.teko.notification:fcm-util:$version")
kapt("vn.teko.notification:fcm-util-processor:$version")

Usage#

Implement worker for creating a notification when receiving message from FCM#

@TargetApi(Build.VERSION_CODES.O)
@Notification
@NotificationChannelId("<notification-channel>")
@NotificationName("<notificationn-name>")
@NotificationDescription("<notification-description>")
@NotificationImportance(NotificationManager.IMPORTANCE_HIGH)
@FcmWorker
class ExampleNotificationWorker(
val context: Context,
val params: WorkerParameters
) : AbstractNotificationWorker(context, params) {
override var smallIcon: Int = R.drawable.ic_notification
override var largeIcon: Int? = R.drawable.ic_notification
override var color: Int? = ContextCompat.getColor(context, R.color.notificationColor)
// default activity to open when user clicks the notification
override var targetActivity: Class<out Activity> = ExampleActivity::class.java
// override intent (activity) to open when user clicks the notification
override suspend fun getIntent(data: Data): PendingIntent {
val intent = Intent(context, ExampleActivity::class.java)
intent.putExtra("args", getBundle(params.inputData.keyValueMap))
return PendingIntent.getActivity(
context, getMessageID(data), intent, PendingIntent.FLAG_ONE_SHOT
)
}
private fun getMessageID(data: Data): Int {
return try {
data.getString("messageId")?.toInt() ?: 0
} catch (exception: Throwable) {
0
}
}
override suspend fun doWork(): Result {
// broadcast an event to refresh notification count in app
context.sendBroadcast(NewNotificationIntent)
return super.doWork()
}
}

Initialize NotificationUtil in Application#

class ExampleApp : Application() {
override fun onCreate() {
//...
NotificationUtil.initialize(this)
}
//...
}

Add MessagingService to AndroidManifest file#

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.notification.example">
<application
<!-- ... -->
<service
android:name="vn.teko.notification.util.fcm.MessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
</application>
</manifest>

Note: If your want to customize the MessagingService class, please create a class that extends BaseMessagingService class and use this class in AndroidManifest instead of MessagingService class.

Now, your app is ready to receive notifications.