Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Notification onTap : Launch activity based on condition

On tapping the notification if the application is logged in and in foreground then I just want to take the user to activity NEWS. If the application is in background then bring it to foreground and goto a NEWS activity. If the app is not launched or not in background then Show the LOGIN activity and then after the success full login take the user to NEWS activity.

With my test code I can take the user to news activity but not to the Login activity if the user is not logged in!

NotificationManager mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);

final PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, NewsActivity.class), 0);

final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
    .setSmallIcon(R.drawable.ic_launcher)
    .setContentTitle(this.getApplicationContext().getString(R.string.app_name))
    .setStyle(new NotificationCompat.BigTextStyle().bigText(msg)).setContentText(msg);

mBuilder.setContentIntent(contentIntent);
mBuilder.setAutoCancel(true);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());

From other threads I came to know that we should not use ActivityManager.getRunningTasks to check if the app is in foreground! Is setting flags on onResume and onPause of all the activities to check whether app is in the foreground is the only best way available?

like image 982
kumar Avatar asked May 26 '26 09:05

kumar


1 Answers

You can use some singleton instance to hold the user state.

final PendingIntent contentIntent = PendingIntent.getActivity(this, 0, createIntent(), 0);

private Intent createIntent() {
    boolean isLoggedIn = Singleton.getInstance().isUserLoggedIn();
    //choose activity depends on is user logged in now
    Class<? extends Activity> clazz = isLoggedIn ? NewsActivity.class : LoginActivity.class;

    Intent intent = new Intent(this, clazz);
    //if not then we need notify login activity that it should force us to news after successful login, so we can use this extra inside login
    if (!isLoggedIn) {
        intent.putExtra("forceToNews",true);
    }
    return intent;
}
like image 163
Orest Savchak Avatar answered May 27 '26 22:05

Orest Savchak