【问题标题】:How to bring an Activity back to the front after i click home button(via notification)单击主页按钮后如何将活动带回前面(通过通知)
【发布时间】:2016-08-02 19:34:46
【问题描述】:

我有一个播放视频的 VideoActivity,我试图实现的是当我点击主页按钮时,我会显示一个通知,一旦我点击通知,它将把 VideoActivity 实例带回到前面。

这是我为通知定义 Intent 的方式:

Intent notificationIntent = new Intent(context, VideoActivity.class);
        notificationIntent.addFlags( Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);

但每次我点击通知时,都会创建一个新的 VideoActivity。

【问题讨论】:

标签: android android-intent


【解决方案1】:

使用它,因为它也会以更优雅的方式做同样的事情(没有任何副作用)

  final Intent notificationIntent = new Intent(context, YourActivity.class);
  notificationIntent.setAction(Intent.ACTION_MAIN);
  notificationIntent.setFlags(FLAG_ACTIVITY_NEW_TASK);
  notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER);

你也可以用这个

<activity 
  android:name=".YourActivity"
  android:launchMode="singleTask"/>

单任务说明

The system creates a new task and instantiates the activity at the root of the
new task. However, if an instance of the activity already exists in a separate
task, the system routes the intent to the existing instance through a call to 
its onNewIntent() method, rather than creating a new instance. Only one 
instance of the activity can exist at a time.

【讨论】:

  • 不不不!这不是解决这个问题的正确方法!为此,您不需要任何特殊的启动模式。使用特殊的启动模式会导致各种其他副作用。这不是一个好建议。
  • @DavidWasser:你建议的最合适的答案是什么?
  • 您只需要在通知中为任务提供一个“启动器”Intent。这会将任务从后台带到前台。见stackoverflow.com/questions/5502427/…
  • 您不认为使用启动模式比创建活动启动器好。 :?如果您在这里使用了 singleTop,那么您所说的副作用就是应用程序的一部分。单实例不会产生任何副作用:)
【解决方案2】:

你应该试试这个。

    Intent notificationIntent = new Intent(context, VideoActivity.class);     
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP|Intent.FLAG_ACTIVITY_CLEAR_TOP);

【讨论】:

  • 这也不是正确的方法。 OP 只是想把他的任务从后台带到前台。还有其他方法可以做到这一点。在问题和链接的问题/答案中查看我的 cmets。
【解决方案3】:

您必须使您的活动成为单一任务,这意味着当它已经在运行或处于后台状态时,不应创建其新实例,并且应将已运行的活动置于前面。

在你的 AndroidManifest.xml 中

你声明你的活动的地方添加

android:launchMode="singleTask"

在您的活动条目中。

【讨论】:

  • 不不不!这不是解决这个问题的正确方法!为此,您不需要任何特殊的启动模式。使用特殊的启动模式会导致各种其他副作用。这不是一个好建议。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多