Search code examples
androidfirebaseandroid-notificationsfirebase-cloud-messagingfirebase-notifications

Handle notifications from Firebase Android


I tried to learn about Firebase. And I successfully received notification from it. But how I can open another activity when click on the notification?

This my code:

public class MyFirebaseMessagingService extends FirebaseMessagingService {

private static final String TAG = "MyFirebaseMsgService";

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    super.onMessageReceived(remoteMessage);
    Log.d("msg", "onMessageReceived: " + remoteMessage.getData().get("message"));
    NotificationCompat.Builder builder = new  NotificationCompat.Builder(this)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle("test")
            .setContentText(remoteMessage.getData().get("message"));
    NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    manager.notify(0, builder.build());



}

Solution

  • You need to build a PendingIntent and notify using NotificationManager

    Intent intent = new Intent(this, MyActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
    
    Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.your_icon)
            .setContentTitle("Notification Title")
            .setContentText(messageBody)
            .setAutoCancel(true)
            .setContentIntent(pendingIntent);
    
    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(0, notificationBuilder.build());
    

    As Tosin suggested, if you're sending push notification from Firebase console, you need to put your payload into data key