【发布时间】:2016-07-01 00:53:51
【问题描述】:
我有两个活动A 和B,其中 A 是 B 的父级。现在我显示一个启动 B 的通知。当我点击通知时,B 启动。然后我点击 up 按钮。当活动 A 在后台堆栈中时它可以正常工作,否则应用程序只会关闭并且不启动活动 A。
我的设置。
我已在清单中声明 A 为 B 的父级,而 A 在 SingleTop 启动模式中
<activity
android:name=".A"
android:label="@string/app_name"
android:screenOrientation="portrait"
android:launchMode="singleTop"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="<packegeName>.Home" />
</intent-filter>
</activity>
<activity
android:name=".B"
android:label="@string/app_name"
android:screenOrientation="portrait"
android:parentActivityName=".A"
android:theme="@style/AppTheme.NoActionBar">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".A" />
</activity>
这是通知意图:
Intent intent = new Intent(this, B.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
在活动 B 中:
@Override
public void onCreate(Bundle savedInstanceState) {
....
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
....
}
我尝试过的
为了调试,我尝试在 Activity B 的onResume 中手动触发这个向上导航,所有这些:
1)
Intent upIntent = NavUtils.getParentActivityIntent(this);
upIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
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);
}
2)
onNavigateUp();
3)
NavUtils.navigateUpFromSameTask(this);
但是当 Activity A 不在 Backstack 中时,这些似乎都不起作用,应用程序就退出了。
我已经搜索了 SO 和 Google(甚至是 bing!)寻找答案,并尝试了我能找到的一切都无济于事。由于没有错误或日志输出,我也不知道如何调试。
我们将不胜感激任何有关找出问题的解决方案或提示。
谢谢。
【问题讨论】:
-
您提到您在 Activity B 的 onResume 中尝试了方法 1、2 和 3。我认为您应该在 onMenuItemSelected 内部执行这些操作,以便可以拦截主页图标上的单击事件。对我来说 1 看起来是正确的方法。
-
您也可以使用 FLAG_ACTIVITY_REORDER_TO_FRONT,但我认为您所做的更正确:stackoverflow.com/a/32427484/6526330
-
@Dr.Nitpick 我在 onResume 中这样做是因为出于测试目的,因为如果不满足某个条件,我的应用程序需要立即转到父级。无论如何,我已经在
onMenuItemSelected中尝试了所有 3 个。但它是一样的。应用程序刚刚退出。 -
该死,我希望能轻松搞定:P 只是好奇,当单击主页图标时,您在
onMenuItemSelected中返回 true 还是 false? -
case android.R.id.home: NavUtils.navigateUpFromSameTask(this); return true;
标签: android android-intent android-activity android-notifications