ANDROID PUSH NOTIFICATION USING FCM (Firebase Cloud Messaging)

Firebase Cloud Messaging (FCM) is a cross-platform messaging solution that lets you reliably send messages at no cost. Using FCM, you can send notification messages to drive user re-engagement and retention .

Lets See Setting FCM Client to app .
  1. Go to the Firebase console.
  2. In the center of the project overview page, click the Android icon (plat_android) or Add app to launch the setup workflow.
  3. Enter your app's package name in the Android package name field.
  4. What's a package name, and where do you find it?
  5. Click Register app.
Application ID : com.tutorialsbuzz.fcmdemo
 Your package name is generally the applicationID in your app-level build.gradle file

Add a Firebase configuration file

1. Add the Firebase Android configuration file to your app:
  • Click Download google-services.json to obtain your Firebase Android config file (google-services.json).
  • Move your config file into the module (app-level) directory of your app.

2. To enable Firebase products in your app, add the google-services plugin to your Gradle files.
  •  In your root-level (project-level) Gradle file (build.gradle), add rules to include the Google Services Gradle plugin. Check that you have Google's Maven repository, as well.
    buildscript {
      repositories {
        // Check that you have the following line (if not, add it):
        google()  // Google's Maven repository
      }
      dependencies {
        ...
        // Add this line
        classpath 'com.google.gms:google-services:4.3.4'
      }
    }
    
    allprojects {
      ...
      repositories {
        // Check that you have the following line (if not, add it):
        google()  // Google's Maven repository
        ...
      }
    }

  • In your module (app-level) Gradle file (usually app/build.gradle), apply the Google Services Gradle plugin:
              
    apply plugin: 'com.android.application'
    // Add this line
    apply plugin: 'com.google.gms.google-services'
    
    dependencies {
      // Import the Firebase BoM
      implementation platform('com.google.firebase:firebase-bom:26.3.0')
    
      // Add the dependency for the Firebase SDK for Google Analytics
      // When using the BoM, don't specify versions in Firebase dependencies
      implementation 'com.google.firebase:firebase-analytics-ktx'
    
      // Add the dependencies for any other desired Firebase products
      // https://firebase.google.com/docs/android/setup#available-libraries
    }
     
  • Sync the project 

FCM Service


Create a class MyFirebaseMessagingService that extends FirebaseMessagingService , This is required if you want to do any message handling beyond receiving notifications on apps in the background .
  • Override the onNewToken : Inside this function your can print the access token , if your using custom server then you can send access token to server . 
  • Override the  onMessageReceived : Inside this function you will recieve the message token sent from fcm server Using Notification Manager we will show payload in notification template .

Compose and Retrieve Data From FCM Notification To Client App .



For NOTIFICATION Related Tutorial Please have a look : .

FCM Service Compelete code 

file : MyFirebaseMessagingService.kt
package com.tutorialsbuzz.fcmdemo


class MyFirebaseMessagingService : FirebaseMessagingService() {

    override fun onNewToken(token: String) {
        super.onNewToken(token)
        Log.d("MyFirebase", "onNewToken: " + token)
    }

    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        super.onMessageReceived(remoteMessage)
        Log.d(
            "MyFirebase",
            "onMessageReceived: FROM: " + remoteMessage.from + " \n DATA: " + remoteMessage.data
        )
        sendNotification(this, remoteMessage)
    }


    fun sendNotification(context: Context, remoteMessage: RemoteMessage) {

        val channelId = "tutorialsbuzz"

        // Create an explicit intent for an Activity in your app
        val intent = Intent(applicationContext, MainActivity::class.java)
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
        val extras = Bundle()
        extras.putString(notify_title, remoteMessage.notification?.title)
        extras.putString(notify_url, remoteMessage.data.get("pageUrl"))
        intent.putExtras(extras)
        intent.action = Intent.ACTION_VIEW

        val pendingIntent: PendingIntent =
            PendingIntent.getActivity(
                applicationContext,
                NotificationID.iD,
                intent,
                PendingIntent.FLAG_UPDATE_CURRENT
            )

        val notificationBuilder =
            NotificationCompat.Builder(context.getApplicationContext(), channelId)
                .setSmallIcon(R.drawable.small_icon)
                .setAutoCancel(true)
                .setLights(Color.BLUE, 500, 500)
                .setVibrate(longArrayOf(500, 500, 500))
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                .setContentIntent(pendingIntent)
                .setContentTitle(remoteMessage.notification?.title)
                .setContentText(remoteMessage.notification?.body)

        val notificationManager = NotificationManagerCompat.from(context)

        // Since android Oreo notification channel is needed.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                channelId,
                "news",
                NotificationManager.IMPORTANCE_HIGH
            )
            notificationManager.createNotificationChannel(channel)
        }

        GlideApp.with(applicationContext)
            .asBitmap()
            .load(remoteMessage.notification?.imageUrl)
            .into(object : CustomTarget<Bitmap>() {
                override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
                    //largeIcon
                    notificationBuilder.setLargeIcon(resource)
                    //Big Picture
                    notificationBuilder.setStyle(
                        NotificationCompat.BigPictureStyle().bigPicture(resource)
                    )
                    notificationManager.notify(NotificationID.iD, notificationBuilder.build())
                }

                override fun onLoadCleared(placeholder: Drawable?) {}
            })
    }

    companion object {
        const val notify_title: String = "notify_title"
        const val notify_url: String = "notify_url"
    }

}

internal object NotificationID {
    private val c = AtomicInteger(100)
    val iD: Int
        get() = c.incrementAndGet()
}



1. Activity


Handling Notification .
  1. The pending intent of notification target set to MainActivity , So onClick of notification MainActivity gets launch .
  2. Using intent we retrieve the data .
  3. Here in this example we get pageUrl from notification and that pageUrl to loaded into webview .

file : MainActivity.kt
package com.tutorialsbuzz.fcmdemo

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //Get Intent data which was set to notification
        val title = intent?.extras?.get(MyFirebaseMessagingService.notify_title) as String?
        val url = intent?.extras?.get(MyFirebaseMessagingService.notify_url) as String?

        url?.let { webView.loadUrl(it) };

        webView.settings.apply {
            javaScriptEnabled = true
            builtInZoomControls = true
        }

        setWebViewClient()
    }

    private fun setWebViewClient() {
        webView.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(
                view: WebView?,
                request: WebResourceRequest?
            ): Boolean {
                return false
            }

            override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
                super.onPageStarted(view, url, favicon)
                progressBar.visibility = View.VISIBLE
            }

            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)
                progressBar.visibility = View.GONE
            }

        }
    }

    override fun onBackPressed() {
        if (webView.canGoBack()) {
            webView.goBack()
        } else {
            super.onBackPressed()
        }
    }
}




No comments:

Post a Comment