【问题标题】:How to create a notification with Action in android如何在android中使用Action创建通知
【发布时间】:2017-03-11 16:14:16
【问题描述】:

我想知道如何在 android 中创建一个带有动作图标的通知,允许我在主活动中调用一个方法。

就像这张图片中的那个:Notification icon exemple

【问题讨论】:

  • 你能详细说明你想做什么吗?
  • 我想在 android 中创建一个通知,就像图片中显示的一样
  • 你在提问之前研究过这个问题吗?

标签: java android notifications bundle action


【解决方案1】:

首先欢迎使用 stackoverflow。我想提醒您,这不是一个学习如何编程的网站,而是一个可以帮助社区提出实际问题的网站。您的问题必须针对您的代码或尝试以及错误日志详细而具体。

话虽如此,这是创建通知的最佳方式:

第 1 步 - 创建通知生成器

第一步是使用 NotificationCompat.Builder.build() 创建一个通知构建器。您可以使用 Notification Builder 设置各种通知属性(小图标、大图标、标题、优先级等)

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)

第 2 步 - 设置通知属性

拥有 Builder 对象后,您可以根据需要使用 Builder 对象设置其 Notification 属性。但这必须至少设置以下 -

  • 一个小图标,由setSmallIcon()设置
  • 标题,由setContentTitle()设置
  • 详细文字,由setContentText()设置

    mBuilder.setSmallIcon(R.drawable.notification_icon);
    
    mBuilder.setContentTitle("I'm a notification alert, Click Me!");
    
    mBuilder.setContentText("Hi, This is Android Notification Detail!");
    

第 3 步 - 附加操作

这是可选的,仅当您想在通知中附加操作时才需要。操作将允许用户直接从通知转到应用程序中的 Activity(他们可以在其中查看一个或多个事件或做进一步的工作)。

该操作由一个 PendingIntent 定义,该 PendingIntent 包含一个在您的应用程序中启动一个 Activity 的 Intent。要将 PendingIntent 与手势相关联,请调用 NotificationCompat.Builder 的相应方法。

例如,如果您想在用户单击通知抽屉中的通知文本时启动 Activity,您可以通过调用 setContentIntent() 添加 PendingIntent。

PendingIntent 对象可帮助您代表您的应用程序执行操作,通常是在以后执行,无论您的应用程序是否正在运行。

还有一个stackBuilder 对象,它将包含一个用于启动的Activity 的人工回栈。这可确保从 Activity 向后导航会导致您的应用程序离开主屏幕。

Intent resultIntent = new Intent(this, ResultActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(ResultActivity.class);

// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =  stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);

第 4 步 - 发出通知

最后,您通过调用NotificationManager.notify() 将通知对象传递给系统以发送您的通知。确保在通知之前调用 builder 对象上的 NotificationCompat.Builder.build() 方法。该方法结合了所有已设置的选项并返回一个新的 Notification 对象。

NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

// notificationID allows you to update the notification later on.
mNotificationManager.notify(notificationID, mBuilder.build());

我希望这能回答你的问题。

【讨论】:

  • 什么是ResultActivity.class
  • 那么ResultActivity.class是一个用户必须自己创建的类,它处理结果?在你的链接中,类的内容没有定义,所以我在这里猜测一下。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多