Bhola Nath Mahto
Bhola Nath Mahto

Reputation: 484

How to detect whether app is opened using app icon click or opened from notification click?

There are 3 cases in Push Notification.

  1. Case 1 : App is already running and notification appears.
  2. Case 2 : App is closed and notification appears but app is opened by clicking app icon
  3. Case 3 : App is closed and app is opened from notification click

My question is how to detect whether app is opened from case 2 or case 3? If I able to detect than I can save some value in preference and using that value I can differentiate whether I have to open Main Activity or Notification Activity.

If you have better idea to decide which activity should be opened after splash (either Main Activity or Notification Activity) than Kindly tell me.

Notification notification = new Notification.Builder(context)
    .setAutoCancel(true)
    .setContentTitle("My Notification")
    .setContentText("You have a received notification.")
    .setSmallIcon(getNotificationIcon())
    .setLargeIcon(BitmapFactory.decodeResource(context.getResources(),
           R.drawable.ic_launcher))
    .build();
    notification.defaults=Notification.DEFAULT_SOUND;
    notification.number = notificationCount++;
    Intent notificationIntent = new Intent(context, SplashActivity.class);
notificationIntent.putExtra("pushClicked", true);
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
    System.out.println("title="+title+"message="+message);
    notification.setLatestEventInfo(context, title, message, contentIntent);
    int SERVER_DATA_RECEIVED = 1;
    NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
    notificationManager.notify(SERVER_DATA_RECEIVED, notification);

In the Target(Splash) activity

boolean pushClicked = false;
if(getIntent()!=null){
     pushClicked  = getIntent().getStringExtra("pushClicked");
    System.out.println("pushClicked="+pushClicked); 
    }
System.out.println(pushClicked );

Always getting false

Upvotes: 3

Views: 1871

Answers (1)

Febi M Felix
Febi M Felix

Reputation: 2849

Add an extra boolean value along with the intent created to open up application activity inside notification receiver. For example :

@Override
public void onReceive(Context context, Intent intent) {
    if (intent == null)
        return;
    Intent splashIntent = new Intent(context, TargetActivity.class);
            splashIntent.putExtra("pushClicked", true);
    context.startActivity(splashIntent);
}

Check for this boolean value inside the TargetActivity to distinguish between push click and app icon click.

Upvotes: 4

Related Questions