{"id":18242669,"url":"https://github.com/sherryzia/fcm_notification_kotlin","last_synced_at":"2026-04-16T04:32:05.346Z","repository":{"id":260642527,"uuid":"881928551","full_name":"sherryzia/FCM_Notification_Kotlin","owner":"sherryzia","description":"This repository shows how to implement Firebase Cloud Messaging (FCM) in a Kotlin Android app for sending and receiving push notifications. It includes examples for setting up FCM, managing tokens, sending notification payloads, and handling incoming messages, providing a complete guide for adding notifications to your app.","archived":false,"fork":false,"pushed_at":"2024-11-01T14:30:55.000Z","size":8,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-02-14T13:50:38.299Z","etag":null,"topics":["android","api","api-integration","fcm","firebase","kotlin","kotlin-coroutines","okhttp","push-notifications"],"latest_commit_sha":null,"homepage":"","language":"Kotlin","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/sherryzia.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-11-01T14:11:46.000Z","updated_at":"2025-01-12T17:59:01.000Z","dependencies_parsed_at":null,"dependency_job_id":"fa2cd0e1-242e-4c4b-a6d7-b58aef2a33a2","html_url":"https://github.com/sherryzia/FCM_Notification_Kotlin","commit_stats":null,"previous_names":["sherryzia/fcm_notification_kotlin"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sherryzia%2FFCM_Notification_Kotlin","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sherryzia%2FFCM_Notification_Kotlin/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sherryzia%2FFCM_Notification_Kotlin/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sherryzia%2FFCM_Notification_Kotlin/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/sherryzia","download_url":"https://codeload.github.com/sherryzia/FCM_Notification_Kotlin/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247895638,"owners_count":21014343,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["android","api","api-integration","fcm","firebase","kotlin","kotlin-coroutines","okhttp","push-notifications"],"created_at":"2024-11-05T07:07:26.564Z","updated_at":"2026-04-16T04:32:05.301Z","avatar_url":"https://github.com/sherryzia.png","language":"Kotlin","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Firebase Cloud Messaging (FCM) Notifications with Kotlin\n\nThis guide details how to set up and send push notifications with Firebase Cloud Messaging (FCM) in a Kotlin Android app. Each section covers one of the essential functions needed to build a notification system for messaging.\n\n## Overview\nOur FCM notification system consists of the following core components:\n\n`sendNotification`: Constructs and sends a notification with a JSON payload.\n\n`callApi`: Performs an API call to FCM to send the notification.\n\n`getFcmToken`: Retrieves and updates the FCM token for the user.\n\n`AccessToken`: Generates an OAuth token for accessing FCM APIs.\n\n## Prerequisites\nEnsure the following steps are completed before diving into the code:\n\n### Set up Firebase in your Android project.\nDownload the JSON file for your Firebase service account credentials:\nGo to Firebase Console \u003e Project Settings \u003e Service accounts and Generate a new private key.\n\n## Code Implementation\n### 1. Sending Notifications with sendNotification\nThe sendNotification function constructs a JSON payload containing the notification details (title, body, and additional data) and initiates the notification send request using the callApi function.\n\n```kotlin\nfun sendNotification(message: String?) {\n    Log.d(\"otherUserID\", \"sendNotification: ${otherUserModel.fcmToken}\")\n    currentUserDetails { userRef -\u003e\n        userRef?.get()?.addOnCompleteListener { task -\u003e\n            if (task.isSuccessful) {\n                val currentUser = task.result.toObject(UserModel::class.java)\n                currentUser?.let {\n                    try {\n                        // Build JSON payload\n                        val jsonObject = JSONObject()\n                        val messageObject = JSONObject()\n                        val notificationObject = JSONObject()\n                        val dataObject = JSONObject()\n\n                        // Set notification title and body\n                        notificationObject.put(\"title\", currentUser.name)\n                        notificationObject.put(\"body\", message)\n\n                        // Add user data\n                        dataObject.put(\"userId\", currentUser.userId)\n\n                        // Construct message with notification and data\n                        messageObject.put(\"notification\", notificationObject)\n                        messageObject.put(\"data\", dataObject)\n                        messageObject.put(\"token\", otherUserModel.fcmToken)\n                        jsonObject.put(\"message\", messageObject)\n\n                        // Call FCM API to send notification\n                        callApi(jsonObject)\n                    } catch (e: Exception) {\n                        e.printStackTrace()\n                    }\n                }\n            } else {\n                Log.e(\"sendNotification\", \"Failed to fetch current user details.\")\n            }\n        }?.addOnFailureListener { exception -\u003e\n            Log.e(\"sendNotification\", \"Error retrieving user data\", exception)\n        }\n    }\n}\n```\n### 2. Making API Calls with callApi\nThe callApi function performs the HTTP request to FCM's API endpoint using OkHttpClient. This includes setting up headers with the OAuth token generated from AccessToken.\n\n```kotlin\nfun callApi(jsonObject: JSONObject) {\n    val JSON: MediaType = \"application/json; charset=utf-8\".toMediaTypeOrNull() ?: return\n    val client = OkHttpClient()\n    val url = \"https://fcm.googleapis.com/v1/projects/chatappfirebase-3ebb8/messages:send\"\n    val body: RequestBody = jsonObject.toString().toRequestBody(JSON)\n\n    lifecycleScope.launch(Dispatchers.IO) {\n        val accessToken = AccessToken().accessToken\n\n        Log.d(\"xyz\", \"Retrieved OAuth token: $accessToken\")\n\n        // Create request with the OAuth token\n        val request: Request = Request.Builder()\n            .url(url)\n            .post(body)\n            .addHeader(\"Authorization\", \"Bearer $accessToken\")\n            .addHeader(\"Content-Type\", \"application/json\")\n            .build()\n\n        client.newCall(request).enqueue(object : Callback {\n            override fun onFailure(call: Call, e: IOException) {\n                e.printStackTrace()\n            }\n\n            override fun onResponse(call: Call, response: Response) {\n                if (response.isSuccessful) {\n                    Log.d(\"FCM\", \"Notification sent successfully: ${response.body?.string()}\")\n                } else {\n                    Log.e(\"FCM\", \"Error sending notification: ${response.body?.string()}\")\n                }\n            }\n        })\n    }\n}\n\n```\n### 3. Retrieving the FCM Token with getFcmToken\nThis function retrieves the device's FCM token and updates the user’s document in Firestore with this token, ensuring notifications can be targeted correctly.\n\n```kotlin\nfun getFcmToken() {\n    FirebaseUtils.collectionUserDetails\n        .whereEqualTo(\"userId\", currentUid)\n        .limit(1)\n        .get()\n        .addOnSuccessListener { querySnapshot -\u003e\n            if (!querySnapshot.isEmpty) {\n                val userDocument = querySnapshot.documents[0]\n                val uid = userDocument.getString(\"phone\").toString()\n\n                FirebaseMessaging.getInstance().getToken().addOnSuccessListener {\n                    if (it != null) {\n                        val token = it\n                        FirebaseUtils.collectionUserDetails.document(uid).update(\"fcmToken\", token)\n                    }\n                }\n            }\n        }\n        .addOnFailureListener { exception -\u003e\n            Log.e(\"fetchUserDetails\", \"Failed to fetch user details\", exception)\n        }\n}\n```\n### 4. Generating Access Tokens with AccessToken\nThe AccessToken class retrieves an OAuth token required to authorize FCM API requests. Replace jsonString with the JSON credentials from your Firebase service account.\n\n```java\npublic class AccessToken {\n    private static final String firebaseMessagingScope = \"https://www.googleapis.com/auth/firebase.messaging\";\n\n    public String getAccessToken() {\n        try {\n            String jsonString = \"{ /* JSON credentials */ }\";\n            InputStream stream = new ByteArrayInputStream(jsonString.getBytes(StandardCharsets.UTF_8));\n            GoogleCredentials googleCredentials = GoogleCredentials.fromStream(stream).createScoped(firebaseMessagingScope);\n            googleCredentials.refresh();\n            return googleCredentials.getAccessToken().getTokenValue();\n        } catch (Exception e) {\n            Log.e(\"AccessToken\", \"getAccessToken: \" + e.getLocalizedMessage());\n            return null;\n        }\n    }\n}\n```\n### 5. Configuring FcmNotificationService in AndroidManifest.xml\nFinally, add the Firebase Messaging service to your Android manifest file to handle incoming messages.\n\n```xml\n\u003cservice\n    android:name=\".FcmNotificationService\"\n    android:exported=\"false\"\u003e\n    \u003cintent-filter\u003e\n        \u003caction android:name=\"com.google.firebase.MESSAGING_EVENT\" /\u003e\n    \u003c/intent-filter\u003e\n\u003c/service\u003e\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsherryzia%2Ffcm_notification_kotlin","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsherryzia%2Ffcm_notification_kotlin","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsherryzia%2Ffcm_notification_kotlin/lists"}