Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include GCM/FCM in an android library module?

Am not able to generate google-services json for an android library because its asking for the application id. I know how to add it in a project.

like image 756
NIJESH ku Avatar asked Feb 06 '23 22:02

NIJESH ku


2 Answers

FCM client setup

Libraries don't have an application ID. Application ID is supplied by the consumer of your library. Just include the dependency and that's it. Don't apply the google services plugin on a library.

Your client would have presumably followed https://firebase.google.com/docs/cloud-messaging/android/client tutorial. Which means you have to create your library's push message processor to which your client will delegate work. Example:

your.client.app.package.fcm.MyFirebaseMessagingService.kt

class MyFirebaseMessagingService() : FirebaseMessagingService() {
    override fun onMessageReceived(p0: RemoteMessage) {
        super.onMessageReceived(p0)

        // Your client's message handling.
        // ...

        // If not handled by client, delegate to library.
        AwesomeLibrary.processPushMessage(this, p0)
}

your.awesome.library.package.fcm.AwesomeLibraryFcm.kt

object AwesomeLibraryFcm {
    fun processPushMessage(context: Context, message: RemoteMessage) {
        // TODO Your job.
    }
}

As you can see connecting Firebase to your library is handled entirely by your library's consumer. You don't touch Firebase on client side at all.

FCM server setup

You need an application ID to setup FCM. One application ID can only be associated to one Firebase Project, which would be that of your library's consumer. Dead end.

If you're running an online service and need to send push messages on behalf of your client you need them to create a Server key (restricted to your server's IP address) in Google Dev console and upload it along with Project ID to your server. These would allow your server to send push messages. This is essentially your client giving you permission to send push mesages on their behalf.

Mind potential security risks and abuse of your service.

like image 177
Eugen Pechanec Avatar answered Feb 13 '23 06:02

Eugen Pechanec


I integrated FCM in library project and used that library in a new app project. I copied google service json file from library and paste it in new app project's app module. After this I modified this google service json file. I renamed"package_name" under "client_info" to app package name and I was able to get notification.

like image 31
Pradeep Sharma Avatar answered Feb 13 '23 05:02

Pradeep Sharma