【发布时间】:2014-05-14 00:09:44
【问题描述】:
我的 Android 应用由一个 Activity 组成,其中包含两个通过选项卡访问的片段(我使用的是 ViewPager)。
在 Fragment #2 中,通过按钮创建通知。例如,如果用户使用主页按钮将应用程序发送到后台,则此按钮启动需要继续的后台任务。
我希望用户能够在单击通知时将应用程序返回到前面,就像使用应用程序图标一样。这是我的代码:
Notification.Builder mBuilder =
new Notification.Builder(getActivity())
.setSmallIcon(R.drawable.ic_stat_av_play)
.setContentTitle("MyApp")
.setContentText("A background task is running");
Intent notificationIntent = new Intent(getActivity(), MainActivity.class);
notificationIntent.setAction(Intent.ACTION_MAIN);
notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER);
PendingIntent notificationPendingIntent = PendingIntent.getActivity(
getActivity(), 0, notificationIntent, 0);
mBuilder.setContentIntent(notificationPendingIntent);
mNotificationManager = (NotificationManager) getActivity().getSystemService(
Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());
很遗憾,单击通知会关闭当前正在运行的应用程序并重新启动它。
如您所见,我已经尝试过这里提出的解决方案:Resume application and stack from notification,但它不起作用。许多类似的问题也建议使用这些标志中的一个或多个:
FLAG_ACTIVITY_CLEAR_TOP
FLAG_ACTIVITY_SINGLE_TOP
FLAG_ACTIVITY_NEW_TASK
FLAG_ACTIVITY_REORDER_TO_FRONT
我发现这些都对我的通知行为没有任何影响。我是否缺少一些东西来使这项工作按预期进行?
编辑:
也许这会帮助你帮助我。问题似乎确实来自应用程序结构。
如果我替换这一行:
Intent notificationIntent = new Intent(getActivity(), MainActivity.class);
这个:
Intent notificationIntent = new Intent(getActivity(), Fragment2.class);
如果在应用程序仍在前台时单击通知行为将是正确的(即通知抽屉将自行关闭)但是,如果我使用主页按钮返回主屏幕,然后单击通知,什么都没有发生。
如果我使用第一个意图定义(使用 MainActivity.class),则没有任何标志对意图有任何影响。这也适用于清单中定义的 launchMode。
编辑 2
已添加解决方案。我不太确定它为什么起作用,所以任何额外的输入都将不胜感激!
【问题讨论】:
标签: android android-fragments notifications