Search code examples
androidpush-notificationfirebase-cloud-messaging

How to open specific activity from push notification in Android&FCM?


I receive a notification about a new message in chat using FCM while the application is closed. When I click on it, I want to open chat activity, but instead main activity opens.

Clicking on the push notification will open main activity. In it, I can get a type of notification from intent and open another activity:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    processNotification()
}

private fun processNotification() {
    val notificationCategory = intent?.extras?.getString("category") ?: return
    if (notificationCategory == "new_message") {
        startMessagingActivity()
        finish()
    }
}

This method seems to me dirty and not convenient. Is it possible to specify the activity that will open when you click on the push-notification?

EDIT: Steps to solve:

  1. Add an intent-filter to the activity you want to open:

    <activity android:name=".messages.chatroom.ChatRoomActivity">
        <intent-filter>
            <action android:name="*your-action-name*"/>
            <category android:name="android.intent.category.DEFAULT"/>
        </intent-filter>
    </activity>
    
  2. Add 'click_action="your-action-name"' field to your FCM message.

Android will automatically open activity with action same as click_action


Solution

  • You will need to use Android Deep linking.

    Your notification (FCM) should have a payload of some data (Message ID all depends on your design) for the given screen you want to consume in this case your chat Activity.

    The chat Activity will need to have a host and schema declared in the manifest, below is the instructions and code for Deep Linking:

    https://developer.android.com/training/app-links/deep-linking

    Happy coding.