Search code examples
androidandroid-intentandroid-activitynotifications

Starting Activity from a notification - Android Studio


I am trying to start an activity from a notification. Upon starting that activity, I add data via intent.putextra to the intent so the activity shows the right content for the situation.

The activity that is being started is supposed to be open only once in the stack. I did achieve this via

android:launchMode="singleTop"

in my manifest.

However - and now I come to my question - if this activity is already running, I want it to close and replace it with the instance I am creating with the specific additional data (put extra). How can I achieve this?

Heres the code of my notification:

public void newMessageNotification(String title, String message, String otherusernumber, String requestStatus, String sendername) {


        notificationManager = NotificationManagerCompat.from(this);

        Intent chatIntent = new Intent(this,ChatActivity.class);

        //these three strings define the behaviour of the chat activtity

        chatIntent.putExtra("otherUsername", sendername);
        chatIntent.putExtra("otherUsernumber", otherusernumber);
        chatIntent.putExtra("requestStatus", requestStatus);


        chatIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent contentIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), chatIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);;


        Notification notification = new NotificationCompat.Builder(this, CHANNEL_1_ID)
                .setSmallIcon(R.drawable.ic_new_message)
                .setContentTitle(title)
                .setContentText(message)
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setCategory(NotificationCompat.CATEGORY_MESSAGE)
                .setContentIntent(contentIntent)
                .setAutoCancel(true)
                .build();

        notificationManager.notify(1, notification);
    }

Solution

  • Try below code

    Add PendingIntent in notification

    Intent intent = new Intent(this, OpenActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    pendingIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent,
                        PendingIntent.FLAG_UPDATE_CURRENT);
    

    Full create notification code

    Intent intent = new Intent(this, OpenActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent,
                            PendingIntent.FLAG_UPDATE_CURRENT);
    
    NotificationManager notificationManager =
            (NotificationManager) getSystemService (Context.NOTIFICATION_SERVICE);
            Uri defaultSoundUri = RingtoneManager . getDefaultUri (RingtoneManager.TYPE_NOTIFICATION);
    
            Notification notification;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                // The id of the channel.
                String Ch_id = "yourappname_01";
                // The user-visible name of the channel.
                CharSequence name = "Notification";
                // The user-visible description of the channel.
                //String description = getString(R.string.channel_description);
                int importance = NotificationManager . IMPORTANCE_HIGH;
                NotificationChannel mChannel = new NotificationChannel(Ch_id, name, importance);
                mChannel.setSound(defaultSoundUri, new AudioAttributes . Builder ().build());
                notificationManager.createNotificationChannel(mChannel);
                // Create a notification and set the notification channel.
                notification = new Notification . Builder (this, Ch_id)
                .setSmallIcon(R.drawable.notify)
                    .setContentTitle(getResources().getString(R.string.app_name))
                    .setContentText(remoteMessage.getData().get("title"))
                    .setAutoCancel(true)
                    .setContentIntent(pendingIntent) //Add PendingIntent
                    .setChannelId(Ch_id)
                    .build();
            } else {
                // Create a notification
                notification = new Notification . Builder (this)
                    .setSmallIcon(R.drawable.notify)
                    .setContentTitle(getResources().getString(R.string.app_name))
                    .setContentText(remoteMessage.getData().get("title"))
                    .setAutoCancel(true)
                    .setSound(defaultSoundUri)
                    .setContentIntent(pendingIntent) //Add PendingIntent
                    .build();
            }
            //Generate Diff Notification
            int m =(int)((new Date ().getTime() / 1000L) % Integer.MAX_VALUE);
            notificationManager.notify(m, notification);
    

    Update

    Intent intent = new Intent(this, OpenActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    
    PendingIntent pendingIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent,
                    PendingIntent.FLAG_ONE_SHOT);
    

    I hope this can help you!

    Thank You.