Search code examples
androidpush-notificationandroid-notificationsfirebase-notifications

Clicking on notification doesn't open activity on background


I send notification from the firebase, while the app run on foreground clicking on notification will work perfectly. But if the app goes on background then clicking on notification won't work. It doesn't open the MainActivity. Please help me where i am wrong.

onMessageReceived()

if (remoteMessage.getNotification() != null) {
            //Foreground
            Log.d(TAG, "Message Notification Body: " +
                    remoteMessage.getNotification().toString());
            showNotification(remoteMessage.getNotification().getTitle(),
                    String.valueOf(remoteMessage.getNotification().getBody()));
        }
else if (remoteMessage.getData().size() > 0) {
           showNotification(remoteMessage.getData().get("title"),
                    remoteMessage.getData().get("data"));

        }

showNotification()

Intent i = new Intent(this, MainActivity.class);
    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_ONE_SHOT);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
            .setAutoCancel(true)
            .setContentTitle(title)
            .setContentText(body)
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentIntent(pendingIntent);

    NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    manager.notify(0, builder.build());

Solution

  • Please use click_action.

    for e.g.

    In your android.manifest file

    Add the following code where you registered your activity

         <activity
                    android:name="your activity name">
                    <intent-filter>
                        <action android:name="your activity name" />
                       <category android:name="android.intent.category.DEFAULT"/>
                   </intent-filter>
       </activity>
    

    Same click action you have to register in your server side.

    for e.g.

    $noti = array
        (
        'icon' => 'your_icon_name',
        'title' => 'title',
        'body' => 'msg',
        'click_action' => 'your activity name comes here'
    );