【问题标题】:Launching existing Activity on Notification click在通知单击时启动现有活动
【发布时间】:2014-11-04 12:24:05
【问题描述】:

在片段上创建了一个 CountDownTimer。如果 CountDownTimer 正在运行,用户可以在应用程序内部导航,也可以在应用程序外部进行导航。每当用户超出 CountDownTimer 片段时,顶部应该有一个通知。如果用户点击通知,他应该被引导到 CountDownTimer 片段并且计时器应该显示正确的倒计时。下面的代码打开了创建 CountDownTimer 的活动。但它会启动该 Activity 的新实例。有什么方法可以获取同一活动的旧实例,以便我可以从相同的先前状态恢复活动?

            {
                Notification.Builder noti = new Notification.Builder(getActivity());
                noti.setContentTitle("kick counter").setSmallIcon(R.drawable.mom_ic_launcher).setAutoCancel(true);
                Intent notificationIntent = new Intent(getActivity(), KickCounterActivity.class);
                notificationIntent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
                PendingIntent contentIntent = PendingIntent.getActivity(getActivity(), 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                noti.setContentIntent(contentIntent);
                NotificationManager notifier = (NotificationManager)getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
                notifier.notify(1, noti.build());
             }

【问题讨论】:

  • @NaveenTamrakar 链接文章中的代码不会阻止创建活动的新实例,这正是 OP 想要的。
  • 不要将标志 Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT 添加到 Intent。此标志不会改变任何行为。如果在特定情况下将 Activity 置于最前面,则由 Android 设置。

标签: java android android-intent android-activity android-fragments


【解决方案1】:

看看Intent-flags。我是这样做的:

final Intent openActivityIntent = new Intent(context, MainActivity.class);
openActivityIntent.setAction("YOUR_ACTION");
openActivityIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(openActivityIntent);

在您的活动中,如果您将其注册为侦听器并对其进行操作,您将收到该操作,例如导航到您的计时器。如果您需要额外的数据,您可以使用openActivityIntent.putExtras(bundle)添加它

【讨论】:

    【解决方案2】:

    您可以尝试将活动的启动模式设置为“singleTop”,请参阅http://developer.android.com/guide/topics/manifest/activity-element.html#lmode

    或者使用 FLAG_ACTIVITY_SINGLE_TOP Intent,见http://developer.android.com/reference/android/content/Intent.html#FLAG_ACTIVITY_SINGLE_TOP

    【讨论】:

      【解决方案3】:

      您可以在意图中添加额外内容。在正在启动的活动中,您可以添加类似的内容。

      //Notification Intent
      notificationIntent.putExtra("Fragment",1);
      
      //MainActivity.class
      Bundle extras = getIntent().getExtras();
      if(extras.getInt("Fragment") == 1){
      //Load Fragment Here
      }
      

      试试这个,让我知道它是否有效。

      【讨论】:

      • 这不会阻止创建活动的新实例,这是 OP 想要做的。
      【解决方案4】:

      使用这个标志

      intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
              | Intent.FLAG_ACTIVITY_SINGLE_TOP
              | Intent.FLAG_ACTIVITY_NEW_TASK);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-04-28
        • 2017-05-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-21
        • 1970-01-01
        相关资源
        最近更新 更多