Skip to content Skip to sidebar Skip to footer

Start An Activity When Clicking A Notification

I'm trying to start an activity by clicking on a notification but that only works when I'm already in the app. Here's the code I think has to do with it: private void sendNotificat

Solution 1:

The following works in my app:

privatevoidsendReminderNotification(Context context) {
    Resourcesresources= context.getResources();
    IntentnotificationIntent=newIntent(context, TitleActivity.class);
    PendingIntentcontentIntent= PendingIntent.getActivity(context, 0, notificationIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builderbuilder=newNotificationCompat.Builder(context)
                    .setSmallIcon(android.R.drawable.ic_lock_idle_alarm)
                    .setLargeIcon(BitmapFactory.decodeResource(resources, R.drawable.my_diary_launcher_icon))
                    .setContentTitle("MyDiary")
                    .setContentText("Reminder to input entry.")
                    .setDefaults(Notification.DEFAULT_ALL)
                    .setAutoCancel(true)
                    .setPriority(NotificationCompat.PRIORITY_MAX)
                    .setContentIntent(contentIntent);

    // Add as notificationNotificationManagermanager= (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    manager.notify(NOTIFICATION_ID, builder.build());
}

Solution 2:

Use pendingIntent to pass data of intent:

privatevoidsendReminderNotification(Context context) {

NotificationCompat.BuildernotificationBuilder=newNotificationCompat.Builder(this)
        .setSmallIcon(R.mipmap.ic_launcher)
        .setContentTitle("Implementation TFA")
        .setContentText(body)
        .setAutoCancel(true)
        .setSound(notificationSound);

Intentintent=newIntent(ImpFirebaseMessagingService.this, codeActivity.class);
intent.putExtra("body", body);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

PendingIntentpendingIntent= PendingIntent.getActivity(this, 0, intent,PendingIntent.FLAG_UPDATE_CURRENT);
notificationBuilder.setContentIntent(pendingIntent);

NotificationManagernotificationManager= (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}

Post a Comment for "Start An Activity When Clicking A Notification"