14

I have an application that issues notifications that when selected start an activity. 根据 Android 文档,我可以使用 NavUtils.shouldUpRecreateTask 检查活动是直接启动(即从通知中启动)还是通过正常的活动堆栈启动。但是它给出了错误的答案。我正在 JellyBean 上对此进行测试,但使用了支持库。

基本上 shouldUpRecreateTask 总是返回 false,即使活动已经从通知中启动。

关于为什么 shouldUpRecreateTask 没有给出正确答案的任何想法?

4

3 回答 3

7

这是不正确的!当您从通知开始时,您必须在构建通知时创建堆栈,如下所述:http: //developer.android.com/guide/topics/ui/notifiers/notifications.html#NotificationResponse

因此,在创建通知时,您必须这样做:

Intent resultIntent = new Intent(this, ResultActivity.class);
// ResultActivity is the activity you'll land on, of course
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack
stackBuilder.addParentStack(ResultActivity.class);
// Adds the Intent to the top of the stack
// make sure that in the manifest ResultActivity has parent specified!!!
stackBuilder.addNextIntent(resultIntent);
// Gets a PendingIntent containing the entire back stack
PendingIntent resultPendingIntent =
        stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

然后当您单击 UP 按钮时,您需要常规代码,即:

if (NavUtils.shouldUpRecreateTask(this, intent)) {
    // This activity is NOT part of this app's task, so
    // create a new task when navigating up, with a
    // synthesized back stack.
    TaskStackBuilder.create(this)
    // Add all of this activity's parents to the back stack
            .addNextIntentWithParentStack(intent)
            // Navigate up to the closest parent
            .startActivities();
} else {
    NavUtils.navigateUpTo(this, intent);
}

这对我来说非常有效。

于 2014-01-08T10:29:43.417 回答
5

我仍然不知道为什么 shouldUpRecreateTask 失败 - 查看它的源代码并没有多大帮助。但解决方案非常简单——我只是在附加到通知的 Intent 中添加一个额外的标志值,然后在 onCreate() 中检查它。如果已设置,则已从通知中调用了 Activity,因此必须重新创建返回堆栈。

代码如下所示:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Bundle b = getIntent().getExtras();
    fromNotification = b.getInt("fromNotification") == 1;
    setContentView(R.layout.threadlist);
}

@Override
public boolean onHomeButtonPressed() {
    if(fromNotification) {
        // This activity is not part of the application's task, so create a new task
        // with a synthesized back stack.
        TaskStackBuilder tsb = TaskStackBuilder.from(this)
                .addNextIntent(new Intent(this, COPAme.class));
        tsb.startActivities();
    } 
        // Otherwise, This activity is part of the application's task, so simply
        // navigate up to the hierarchical parent activity.
    finish();
    return true;
}
于 2013-01-25T13:05:35.373 回答
4

我和OP有同样的问题。NavUtils.shouldUpRecreateTask 似乎总是返回 false。(JellyBean 也是) 我用下面的实现了同样的功能。

case android.R.id.home:
Intent upIntent = new Intent(this,ParentActivity.class);
upIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(upIntent);
finish();
return true;

可以通过这种方式获取“父”意图,而不是硬编码。

Intent upIntent = NavUtils.getParentActivityIntent(this);
于 2014-02-19T12:07:26.360 回答