Push-Notification Using Firebase

Push-Notification Using Firebase

 

Implementation By Example

  1. Apply this Changes
    1. In your root-level (project-level) Gradle file <project>/build.gradle.kts or <project>/build.gradle), add the Google services plugin as a dependency:
      1. plugins { id("com.android.application") version "7.3.0" apply false // ... // Add the dependency for the Google services Gradle plugin id("com.google.gms.google-services") version "4.4.0" apply false }
    2. In your module (app-level) Gradle file (usually <project>/<app-module>/build.gradle.kts or <project>/<app-module>/build.gradle), add the Google services plugin:
    3. plugins {   id("com.android.application") // Add the Google services Gradle plugin   id("com.google.gms.google-services")   // ... }
    4. In your module (app-level) Gradle file usually <project>/<app-module>/build.gradle.kts or <project>/<app-module>/build.gradle), add the dependency for the Firebase Cloud Messaging library for Android. We recommend using the Firebase Android BoM to control library versioning.
      • For an optimal experience with Firebase Cloud Messaging, we recommend enabling Google Analytics in your Firebase project and adding the Firebase SDK for Google Analytics to your app.
      dependencies { // Import the BoM for the Firebase platform     implementation(platform("com.google.firebase:firebase-bom:32.7.1")) // Add the dependencies for the Firebase Cloud Messaging and Analytics libraries     // When using the BoM, you don't specify versions in Firebase library dependencies implementation("com.google.firebase:firebase-messaging") // OR either can work Not both at same time implementation("com.google.firebase:firebase-messaging-ktx:23.4.0")     implementation("com.google.firebase:firebase-analytics") }
       
  1. Important : Add all the tag with comments defined , in your AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"> <!-- For Notification Permission --> <uses-permission android:name="android.permission.POST_NOTIFICATIONS" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" tools:ignore="GoogleAppIndexingWarning"> <!-- [START fcm_default_icon] --> <!-- Set custom default icon. This is used when no icon is set for incoming notification messages.--> <meta-data android:name="com.google.firebase.messaging.default_notification_icon" android:resource="@drawable/ic_stat_ic_notification" /> <!-- Set color used with incoming notification messages. This is used when no color is set for the incoming notification message.--> <meta-data android:name="com.google.firebase.messaging.default_notification_color" android:resource="@color/colorAccent" /> <!-- [END fcm_default_icon] --> <!-- [START fcm_default_channel] --> <meta-data android:name="com.google.firebase.messaging.default_notification_channel_id" android:value="@string/default_notification_channel_id" /> <!-- [END fcm_default_channel] --> <activity android:name=".EntryChoiceActivity" android:label="@string/app_name" android:exported="true"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".kotlin.MainActivity" /> <!-- Service Cretex from FireBase Messaging Service Class--> <service android:name=".MyFirebaseMessagingService" android:exported="false"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT" /> </intent-filter> </service> </application> </manifest>
 
  1. Create this new class extends from FirebaseMessagingService()
      • (Optional ) add methods in them as below
package com.example.firebase_demo import android.util.Log import android.widget.Toast import com.google.firebase.messaging.FirebaseMessagingService import com.google.firebase.messaging.RemoteMessage class MyFirebaseMessagingService : FirebaseMessagingService(){ override fun onNewToken(token: String) { Log.d("=====", "Refreshed token: $token") // If you want to send messages to this application instance or // manage this apps subscriptions on the server side, send the // FCM registration token to your app server. // sendRegistrationToServer(token) } override fun onMessageReceived(message: RemoteMessage) { super.onMessageReceived(message) Toast.makeText(this,"onMessageReceived",Toast.LENGTH_SHORT).show() } }
  1. Add this into to HomeActivity Or MainActivity where first page opens after starting app
      • use import android.Manifest for user permission check
// Declare the launcher at the top of your Activity/Fragment: private val requestPermissionLauncher = registerForActivityResult( ActivityResultContracts.RequestPermission(), ) { isGranted: Boolean -> if (isGranted) { // FCM SDK (and your app) can post notifications. } else { // TODO: Inform user that that your app will not show notifications. } } private fun askNotificationPermission() { // This is only necessary for API level >= 33 (TIRAMISU) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED ) { // FCM SDK (and your app) can post notifications. } else if (shouldShowRequestPermissionRationale(Manifest.permission.POST_NOTIFICATIONS)) { // TODO: display an educational UI explaining to the user the features that will be enabled // by them granting the POST_NOTIFICATION permission. This UI should provide the user // "OK" and "No thanks" buttons. If the user selects "OK," directly request the permission. // If the user selects "No thanks," allow the user to continue without notifications. } else { // Directly ask for the permission requestPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS) } } } fun getToken(){ FirebaseMessaging.getInstance().token.addOnCompleteListener(OnCompleteListener { task -> if (!task.isSuccessful) { Log.w("_MS_", "Fetching FCM registration token failed", task.exception) return@OnCompleteListener } // Get new FCM registration token val token = task.result // Log and toast Log.d("_MS_", token) // Toast.makeText(baseContext, token, Toast.LENGTH_SHORT).show() }) }

Don’t Forget to call askNotificationPermission() method from onCreate() method of Activity

 
  1. Set Up Notification From Firebase Console
    1. Make sure you have setup SHA-1 Key with your project
    2. And Added google-services.json file in your root directory of your app ( means in src folder)
    3. Open Your App Project in Firebase Console
    4. On Home Page of your project left hand side click on Engage > Messaging
    5. click on Create your first campaign (if Not Created Before) else New campaign
    6. Select Firebase Notification messages and click create
    7.  
  1. Notification
    1. Enter Title in notification title
    2. Enter subText / details in notification text
    3. Provide link of your image if you want in notification image
    4. give name to your notification
    5. click on next
    6. Target
      1. select your app (target user) to send notification (your app domain name / package name)
      1. click on next
      Scheduling
      1. Select when you want to send notification
      1. select now if you want urgent notification
      1. else select Scheduled and choose date and time to send notification
      Add Additional Info if you want
       
    7. Click On Review to review your notification and than Publish your notification
 

For More Details Read Below Documentation:

Edit your app manifest

Add the following to your app's manifest:
  • A service that extends FirebaseMessagingService. This is required if you want to do any message handling beyond receiving notifications on apps in the background. To receive notifications in foregrounded apps, to receive data payload, to send upstream messages, and so on, you must extend this service.
AndroidManifest.xml
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" tools:node="remove"/>
<service     android:name=".java.MyFirebaseMessagingService"     android:exported="false">     <intent-filter>         <action android:name="com.google.firebase.MESSAGING_EVENT" />     </intent-filter> </service>
  • Within the application component, metadata elements to set a default notification icon and color.
  • Android uses these values whenever incoming messages do not explicitly set icon or color.
<!-- Set custom default icon. This is used when no icon is set for incoming notification messages. --> <meta-data     android:name="com.google.firebase.messaging.default_notification_icon"     android:resource="@drawable/ic_stat_ic_notification" /> <!-- Set color used with incoming notification messages. This is used when no color is set for the incoming notification message. --> <meta-data     android:name="com.google.firebase.messaging.default_notification_color"     android:resource="@color/colorAccent" />
  • provides a default notification channel with basic settings. If you prefer to create and use your own default channel, set default_notification_channel_id to the ID of your notification channel object as shown; FCM will use this value whenever incoming messages do not explicitly set a notification channel.
  • Basically create tag in strings.xml file with default_notification_channel_id name and as value set channel id in it (Basically any String for test)
<meta-data     android:name="com.google.firebase.messaging.default_notification_channel_id"     android:value="@string/default_notification_channel_id" />

Request runtime notification permission on Android 13+

  • Android 13 introduces a new runtime permission for showing notifications.
  • This affects all apps running on Android 13 or higher that use FCM notifications.
  • By default, the FCM SDK (version 23.0.6 or higher) includes the POST_NOTIFICATIONS permission defined in the manifest.
  • However, your app will also need to request the runtime version of this permission via the constant, android.permission.POST_NOTIFICATIONS.
  • Your app will not be allowed to show notifications until the user has granted this permission.
 
MainActivity.kt
// Declare the launcher at the top of your Activity/Fragment: private val requestPermissionLauncher = registerForActivityResult( ActivityResultContracts.RequestPermission(), ) { isGranted: Boolean -> if (isGranted) { // FCM SDK (and your app) can post notifications. } else { // TODO: Inform user that that your app will not show notifications. } } private fun askNotificationPermission() { // This is only necessary for API level >= 33 (TIRAMISU) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED ) { // FCM SDK (and your app) can post notifications. } else if (shouldShowRequestPermissionRationale(Manifest.permission.POST_NOTIFICATIONS)) { // TODO: display an educational UI explaining to the user the features that will be enabled // by them granting the POST_NOTIFICATION permission. // This UI should provide the user "OK" and "No thanks" buttons. If the user selects "OK", // directly request the permission. // If the user selects "No thanks," allow the user to continue without notifications. } else { // Directly ask for the permission requestPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS) } } }
  • add registerForActivityResult to get result from permission request , define this in HomeActivity / MainActivity
  • also define this askNotificationPermission() in same Activity (mostly where user will first land after splash screen )
  • call askNotificationPermission() function from onCreate() method in which activity this has been defined
  • Generally, you should display a UI explaining to the user the features that will be enabled if they grant permissions for the app to post notifications. This UI should provide the user options to agree or deny, such as OK and No thanks buttons. If the user selects OK, directly request the permission. If the user selects No thanks, allow the user to continue without notifications.
 

Notification permissions for apps targeting Android 12L (API level 32) or lower

  • Android automatically asks the user for permission the first time your app creates a notification channel, as long as the app is in the foreground.
 

Access the device registration token

  • On initial startup of your app, the FCM SDK generates a registration token for the client app instance. If you want to target single devices or create device groups, you'll need to access this token by extending FirebaseMessagingService and overriding onNewToken()
The registration token may change when:
  • The app is restored on a new device
  • The user uninstalls/reinstall the app
  • The user clears app data.

Retrieve the current registration token

When you need to retrieve the current token, call FirebaseMessaging.getInstance().getToken():
FirebaseMessaging.getInstance().token.addOnCompleteListener(OnCompleteListener { task ->     if (!task.isSuccessful) {         Log.w(TAG, "Fetching FCM registration token failed", task.exception)         return@OnCompleteListener     }     // Get new FCM registration token     val token = task.result     // Log and toast     val msg = getString(R.string.msg_token_fmt, token)     Log.d(TAG, msg)     Toast.makeText(baseContext, msg, Toast.LENGTH_SHORT).show() })

Monitor token generation

The onNewToken callback fires whenever a new token is generated.
/**  * Called if the FCM registration token is updated. This may occur if the security of  * the previous token had been compromised. Note that this is called when the  * FCM registration token is initially generated so this is where you would retrieve the token.  */ override fun onNewToken(token: String) {     Log.d(TAG, "Refreshed token: $token")     // If you want to send messages to this application instance or     // manage this apps subscriptions on the server side, send the     // FCM registration token to your app server.     sendRegistrationToServer(token) }
After you've obtained the token, you can send it to your app server and store it using your preferred method.
 
  1. In your root-level (project-level) Gradle file <project>/build.gradle.kts or <project>/build.gradle), add the Google services plugin as a dependency:
    1. plugins { id("com.android.application") version "7.3.0" apply false // ... // Add the dependency for the Google services Gradle plugin id("com.google.gms.google-services") version "4.4.0" apply false }
  1. In your module (app-level) Gradle file (usually <project>/<app-module>/build.gradle.kts or <project>/<app-module>/build.gradle), add the Google services plugin:
plugins {   id("com.android.application") // Add the Google services Gradle plugin   id("com.google.gms.google-services")   // ... }
  1. In your module (app-level) Gradle file usually <project>/<app-module>/build.gradle.kts or <project>/<app-module>/build.gradle), add the dependency for the Firebase Cloud Messaging library for Android. We recommend using the Firebase Android BoM to control library versioning.
  • For an optimal experience with Firebase Cloud Messaging, we recommend enabling Google Analytics in your Firebase project and adding the Firebase SDK for Google Analytics to your app.
dependencies { // Import the BoM for the Firebase platform     implementation(platform("com.google.firebase:firebase-bom:32.7.1")) // Add the dependencies for the Firebase Cloud Messaging and Analytics libraries     // When using the BoM, you don't specify versions in Firebase library dependencies implementation("com.google.firebase:firebase-messaging") // OR either can work Not both at same time implementation("com.google.firebase:firebase-messaging-ktx:23.4.0")     implementation("com.google.firebase:firebase-analytics") }
  1. Sync your Android project with Gradle files.