首先欢迎使用 stackoverflow。我想提醒您,这不是一个学习如何编程的网站,而是一个可以帮助社区提出实际问题的网站。您的问题必须针对您的代码或尝试以及错误日志详细而具体。
话虽如此,这是创建通知的最佳方式:
第 1 步 - 创建通知生成器
第一步是使用 NotificationCompat.Builder.build() 创建一个通知构建器。您可以使用 Notification Builder 设置各种通知属性(小图标、大图标、标题、优先级等)
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
第 2 步 - 设置通知属性
拥有 Builder 对象后,您可以根据需要使用 Builder 对象设置其 Notification 属性。但这必须至少设置以下 -
第 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());
我希望这能回答你的问题。