在点击通知时,如果应用程序已登录并处于前台,则我只想带用户查看活动新闻。如果应用程序位于后台,则将其置于前台并转到新闻活动。如果应用程序未启动或不在后台,则显示登录活动,然后在成功完全登录后,将用户带到新闻活动。
使用我的测试代码,我可以让用户进入新闻活动,但如果用户没有登录,就不能进入登录活动!
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());
从其他线程我知道,我们不应该使用activitymanager.getrunningtasks来检查应用程序是否在前台!是否在所有活动的onresume和onpause上设置标志以检查应用程序是否在前台是唯一可用的最佳方法?
最佳答案
您可以使用一些单例实例来保存用户状态。
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;
}