【问题标题】:Android Notification onTap : Launch activity based on conditionAndroid Notification onTap:根据条件启动活动
【发布时间】:2015-12-16 10:27:39
【问题描述】:

如果应用程序已登录并在前台点击通知,那么我只想将用户带到活动新闻。如果应用程序处于后台,则将其置于前台并转到 NEWS 活动。如果应用程序未启动或不在后台,则显示 LOGIN 活动,然后在成功完全登录后将用户带到 NEWS 活动。

使用我的测试代码,如果用户未登录,我可以将用户带到新闻活动,但不能带到登录活动!

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 上设置标志以检查应用程序是否在前台是唯一可用的最佳方法吗?

【问题讨论】:

    标签: android android-activity notifications google-cloud-messaging


    【解决方案1】:

    您可以使用一些单例实例来保存用户状态。

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

    【讨论】:

      【解决方案2】:

      您的测试代码总是将 NewsActivity 放入 Intent。

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

      我建议您编写一个通过 Intent 调用的简单类。 在此类中,您检查用户是否已登录并从该类中启动正确的 Activity。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-15
        • 2011-04-05
        相关资源
        最近更新 更多