我正在通知抽屉中的通知中开始一项活动 - 谁有父活动。子活动已启用导航功能。我希望在单击向上导航按钮时子活动返回到父活动。此行为适用于正常的应用程序流。但是,当用户通过通知输入子活动时,单击向上导航按钮不会将用户带到父活动;相反,它结束了申请。
以下是单击通知时应启动的活动的清单。它有一个父TabbedActivity
<activity
android:name=".activity.AnimalDetailsActivity"
android:parentActivityName=".activity.TabbedActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".activity.TabbedActivity"/>
</activity>
这是我生成通知和意图的地方:
Intent resultIntent = new Intent(context.getApplicationContext(), AnimalDetailsActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context.getApplicationContext());
stackBuilder.addParentStack(AnimalDetailsActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setSmallIcon(icon_resource_id)
.setLargeIcon(large_icon)
.setContentTitle(title)
.setContentText(text)
.setContentIntent(resultPendingIntent)
.setAutoCancel(true);
return builder.build();
然后我把它们发送出去
private static void sendNotifications(List<android.app.Notification> notifications) {
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
for (android.app.Notification notification : notifications) {
manager.notify(++drawerId, notification);
}
}
在目标活动中,我启用向上按钮箭头和向上导航:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().setHomeButtonEnabled(true);
getActionBar().setDisplayHomeAsUpEnabled(true);
我相信我正确地遵循指南。那么为什么向上箭头没有将用户带到父活动?
答案 0 :(得分:6)
根据documentation,如果您使用新的后台堆栈启动活动,则应按如下方式实施onOptionsItemSelected()
回调:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
Intent upIntent = NavUtils.getParentActivityIntent(this);
if (NavUtils.shouldUpRecreateTask(this, upIntent)) {
// 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(upIntent)
// Navigate up to the closest parent
.startActivities();
} else {
// This activity is part of this app's task, so simply
// navigate up to the logical parent activity.
NavUtils.navigateUpTo(this, upIntent);
}
return true;
}
return super.onOptionsItemSelected(item);
}
答案 1 :(得分:1)
要添加到接受的答案,我会添加isTaskRoot()
检查:
if (NavUtils.shouldUpRecreateTask(this, upIntent) || isTaskRoot()) {
/* ... */
}
因为当应用程序从通知启动时,启动的Activity是应用程序堆栈的一部分,但我们仍然希望为父母重新创建任务。