【问题标题】:How to reuse top activity from notification created using startForeground?如何重用使用 startForeground 创建的通知中的顶级活动?
【发布时间】:2012-10-24 13:59:53
【问题描述】:

我有一项服务,当用户执行操作时,它会使用 Service.startForeground(..) 更改为在前台运行,因为杀死它会对用户造成干扰。

我使用以下代码构建一个通知来创建它的待处理意图:

Intent topActivityIntent = new Intent(this, topActivityClass);
// Rebuild the task stack
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack
stackBuilder.addParentStack(topActivityClass);
stackBuilder.addNextIntent(topActivityIntent);
for (int i = 0; i < stackBuilder.getIntentCount(); i++) {
    Intent currentIntent = stackBuilder.editIntentAt(i);
    // Set flags to tell that we want to re-use the existing
    // topActivity if possible
    currentIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | 
        Intent.FLAG_ACTIVITY_SINGLE_TOP | 
        Intent.FLAG_ACTIVITY_NEW_TASK);
}
// Adds the Intent to the top of the stack
// Gets a PendingIntent containing the entire back stack
PendingIntent pendingIntent = stackBuilder.getPendingIntent(0,
    PendingIntent.FLAG_UPDATE_CURRENT);

topActivityClass 是用户当前看到的活动,因为我希望他/她回到相同的活动。

这里的问题是,当用户点击通知时,会创建一个新的Activity,而不是使用任务堆栈中的那个。

我已尝试将标志仅设置为 topActivityIntent 和几种标志组合。

我应该使用哪些标志来避免创建新活动?是否可以重用堆栈中的活动?

【问题讨论】:

    标签: android android-intent android-service android-notifications


    【解决方案1】:

    只需从意图中删除FLAG_ACTIVITY_NEW_TASK,它就会重用现有任务

    【讨论】:

      猜你喜欢
      • 2017-05-15
      • 2014-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-31
      • 1970-01-01
      相关资源
      最近更新 更多