kumar
kumar

Reputation: 1854

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?

Upvotes: 3

Views: 923

Answers (2)

Orest Savchak
Orest Savchak

Reputation: 4569

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;
}

Upvotes: 2

carstenbaumhoegger
carstenbaumhoegger

Reputation: 1645

Your test code always puts the NewsActivity into the Intent.

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

I suggest that you write a simple class that get's called via the Intent. Inside this class you check if the user is logged in or not and launch the correct Activity from the class.

Upvotes: 1

Related Questions