Android 状态栏通知 - 选择通知时打开正确的 Activity

发布于 2024-09-02 17:53:32 字数 966 浏览 2 评论 0原文

我遇到了一个问题:通知在单击后无法打开/转到正确的活动。

我的通知代码(位于扩展服务的类中):

Context context = getApplicationContext();

    CharSequence contentTitle = "Notification";

    CharSequence contentText = "New Notification";

    final Notification notifyDetails =
        new Notification(R.drawable.icon, "Consider yourself notified", System.currentTimeMillis());

    Intent notifyIntent = new Intent(context, MainActivity.class);

    PendingIntent intent =
          PendingIntent.getActivity(context, 0,
          notifyIntent,  PendingIntent.FLAG_UPDATE_CURRENT | Notification.FLAG_AUTO_CANCEL);

    notifyDetails.setLatestEventInfo(context, contentTitle, contentText, intent);

    ((NotificationManager)getSystemService(NOTIFICATION_SERVICE)).notify(NOTIFICATION_ID, notifyDetails);

如果我在创建服务的应用程序打开时单击通知,则通知会消失(由于 FLAG_AUTO_CANCEL),但活动不会切换。

如果我从主屏幕单击通知,通知就会消失,并且我的应用程序会被带到前面,但它仍然保留在进入主屏幕之前打开的活动上,而不是进入主屏幕。

我做错了什么?如何指定要拉起的活动?

I have been having a problem with a notification not opening/going to the correct activity when it has been clicked.

My notification code (located in a class which extends Service):

Context context = getApplicationContext();

    CharSequence contentTitle = "Notification";

    CharSequence contentText = "New Notification";

    final Notification notifyDetails =
        new Notification(R.drawable.icon, "Consider yourself notified", System.currentTimeMillis());

    Intent notifyIntent = new Intent(context, MainActivity.class);

    PendingIntent intent =
          PendingIntent.getActivity(context, 0,
          notifyIntent,  PendingIntent.FLAG_UPDATE_CURRENT | Notification.FLAG_AUTO_CANCEL);

    notifyDetails.setLatestEventInfo(context, contentTitle, contentText, intent);

    ((NotificationManager)getSystemService(NOTIFICATION_SERVICE)).notify(NOTIFICATION_ID, notifyDetails);

If I click the notification while the application which created the service is open, the notification disappears (due to the FLAG_AUTO_CANCEL) but the activity does not switch.

If I click the notification from the home screen, the notification disappears and my app is brought to the front, however it remains on the activity which was open before going to the home screen, instead of going to the main screen.

What am I doing wrong? How do I specify the activity that will be pulled up?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

丿*梦醉红颜 2024-09-09 17:53:32

可能实际上回答了我自己的问题:

Intent notifyIntent = new Intent(Intent.ACTION_MAIN);
notifyIntent.setClass(getApplicationContext(), Main.class);

May have actually answered my own question:

Intent notifyIntent = new Intent(Intent.ACTION_MAIN);
notifyIntent.setClass(getApplicationContext(), Main.class);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文