Android – How to setup push notification

Step 1: Set Up Firebase Project

  1. Create a Firebase Project:
    • Go to the Firebase Console.
    • Click on “Add Project” and follow the instructions to create a new project.
  2. Add an Android App to Your Project:
    • In the Firebase console, click on “Add App” and select the Android icon.
    • Register your app by providing your app’s package name (you can find this in your AndroidManifest.xml).
    • Download the google-services.json file and add it to your project’s app/ directory.

Step 2: Add Firebase SDK to Your Android App

  1. Update build.gradle Files:
    • In your project-level build.gradle file, add the following:
      classpath ‘com.google.gms:google-services:4.3.10’ // Check for the latest version
    • In your app-level build.gradle file, add the following dependencies:
      implementation platform(‘com.google.firebase:firebase-bom:32.0.0’) // Use the latest BOM version
      implementation ‘com.google.firebase:firebase-messaging’
    • At the bottom of the same file, add:
      apply plugin: ‘com.google.gms.google-services’
  2. Sync the Gradle Files:
    Click “Sync Now” in Android Studio to download the necessary dependencies.

Step 3: Set Up Firebase Cloud Messaging (FCM)

Create a Service for Receiving Notifications:

  • Create a new class that extends FirebaseMessagingService. Override the onMessageReceived method to handle incoming messages.
    class MyFirebaseMessagingService : FirebaseMessagingService() {
        override fun onMessageReceived(remoteMessage: RemoteMessage) {
            // Handle FCM messages here.
            Log.d(TAG, "From: ${remoteMessage.from}")
    
            // Check if the message contains a notification payload.
            remoteMessage.notification?.let {
                Log.d(TAG, "Message Notification Body: ${it.body}")
                showNotification(it.title, it.body)
            }
        }
    
        private fun showNotification(title: String?, message: String?) {
            val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            val notification = NotificationCompat.Builder(this, "your_channel_id")
                .setContentTitle(title)
                .setContentText(message)
                .setSmallIcon(R.drawable.ic_notification)
                .build()
            notificationManager.notify(0, notification)
        }
    }
    

    Register the Service in AndroidManifest.xml:

    <service
        android:name=".MyFirebaseMessagingService"
        android:exported="false">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>
    

    Request Notification Permission (for Android 13+):

    • For Android 13 (API level 33) and above, you need to request the POST_NOTIFICATIONS runtime permission.
    • In your AndroidManifest.xml:
    <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
    • Request permission in your code:
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
        ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.POST_NOTIFICATIONS), 1)
    }

    Step 4: Sending Push Notifications

    1. Send Notifications from Firebase Console:
      • Go to the Firebase console.
      • Navigate to “Cloud Messaging” and click “Send your first message”.
      • Fill in the notification details and choose your target app.
    2. Send Notifications Programmatically Using Firebase Admin SDK:
      • Set up Firebase Admin SDK in your backend server to send notifications to your app programmatically.

    Step 5: Testing Push Notifications

    • Install the app on a physical device.
    • Send a test message from the Firebase console to verify that push notifications are working as expected.

    Additional Considerations

    • Notification Channels (Android 8.0+): For Android 8.0 and above, create notification channels to categorize your notifications.
    • Handling Different Types of Notifications: You can handle both data messages (sent to the app when it’s in the foreground or background) and notification messages (handled by the system when the app is in the background).

    Be the first to comment

    Leave a Reply

    Your email address will not be published.


    *