Android:使用 Viewpager 将 Activity 置于最前面的通知

标签 android android-fragments notifications

我的 Android 应用程序由一个 Activity 组成,该 Activity 包含两个使用选项卡访问的 fragment (我使用的是 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);

如果在应用程序仍在前台时单击它,通知行为将是正确的(即通知抽屉将自行关闭)但是,如果我使用主页按钮返回主屏幕,然后单击通知, 没有任何反应。

如果我使用第一个 Intent 定义(使用 MainActivity.class),则没有任何标志对 Intent 有任何影响。这也适用于 list 中定义的 launchMode。

编辑2

添加了解决方案。我不太确定它为什么起作用,所以任何额外的输入将不胜感激!

最佳答案

我用这个方法,问题解决了。希望这也能帮到你。

Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setClass(this, Main.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);

关于Android:使用 Viewpager 将 Activity 置于最前面的通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23643616/

相关文章:

android - 条形图在 AchartEngine 中不起作用

android - fragment 不显示第二次使用

java - Android 在 View Pager 的 Parent Activity fragment 中设置 View

PHP MySQL 查询结果在 HTML 表中通过电子邮件发送

Android:使用动画显示/隐藏 View

android - 避免在收件箱中接收短信 ..android

java - 使用 Eclipse 的 Android 应用程序

android - 带导航组件的 backstack

iphone - 当用户将文件拖到 iTunes 文件共享中并且同步完成时,有没有办法得到通知?

ios - 在允许通知设置更改时收到通知 iOS swift