How do I process PendingIntent in already running activity

505 views Asked by At

I have a small app where the main activity is already in front and a notification may show. When the user taps on the notification I would like to have the main activity get the intent extras and act on them, but not sure how since it is already running.

My code that returns the PendingInent for use in the NotificationCompat.Builder:

private static PendingIntent getPendingIntent(Context ctx, String brandId) {
    Intent showIntent = new Intent(ctx, MainActivity.class);
    showIntent.setAction(Intent.ACTION_MAIN);
    showIntent.addCategory(Intent.CATEGORY_LAUNCHER);
    showIntent.putExtra(PUSH_NOTIFICATION, true);
    showIntent.putExtra(BRAND_ID, brandId);

    return PendingIntent.getActivity(ctx, 0, showIntent, PendingIntent.FLAG_UPDATE_CURRENT);
}

I thought that maybe my MainActivity would be relaunched, but it isn't

How can I do this?

3

There are 3 answers

0
RhysP On BEST ANSWER

Have you tried overriding the "onNewIntent" method within your MainActivity class?

For example:

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    //handle new intent here
}

As your activity is already running the new intent should come in here.

0
Santanu Sur On

Do something like this onResume()....{ if(intent.getExtras().get("your_required_thing")!=null){ // do your stuff} or you cant also use broadCastReceiver and register the receiver in onResume ... and get the intent extras at onReceive of broadcast

0
Hamza On
private static PendingIntent getPendingIntent(Context ctx, String brandId) {
    Intent showIntent = new Intent(ctx, MainActivity.class);
    showIntent.setAction(Intent.ACTION_MAIN);
    showIntent.addCategory(Intent.CATEGORY_LAUNCHER);
    showIntent.putExtra(PUSH_NOTIFICATION, true);
    showIntent.putExtra(BRAND_ID, brandId);
return PendingIntent.getBroadcast(this, 0, showIntent, 0);;
}

and then create broadcast class

public static class myNotificationCloseButtonHandler extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(context, "Close Clicked", Toast.LENGTH_SHORT).show();
            Intent startIntent = new Intent(context, PlayerForegroundService.class);
            startIntent.setAction(PlayerForegroundService.STOP_FOREGROUND_ACTION);
            context.startService(startIntent);
        }


}