如何在Android中实现通知栏

  介绍

今天就跟大家聊聊有关如何在Android中实现通知栏,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

一、设置通知内容

//CHANNEL_ID,渠道ID, Android  8.0及更高版本必须要设置
  ,,,NotificationCompat.Builder  builder =, new  NotificationCompat.Builder(这个,,CHANNEL_ID)
  ,,,,//设置小图标
  ,,,,,,,,,,,.setSmallIcon (R.drawable.notification_icon)
  ,,,,,,,,,,,//设置标题
  ,,,,,,,,,,,.setContentTitle (textTitle)
  ,,,,,,,,,,,//设置内容
  ,,,,,,,,,,,.setContentText (textContent)
  ,,,,,,,,,,,//设置等级
  ,,,,,,,,,,,.setPriority (NotificationCompat.PRIORITY_DEFAULT); 

二、创建渠道

在Android 8.0及更高版本上提供通知,需要在系统中注册应用的通知渠道。

private  void  createNotificationChannel (), {   ,,,,,,,if  (Build.VERSION.SDK_INT 祝辞=,Build.VERSION_CODES.O), {   ,,,,,,,,,,,CharSequence  name =, getString (R.string.channel_name);   ,,,,,,,,,,,String  description =, getString (R.string.channel_description);   ,,,,,,,,,,,//不同的重要程度会影响通知显示的方式   ,,,,,,,,,,,int  importance =, NotificationManager.IMPORTANCE_DEFAULT;   ,,,,,,,,,,,NotificationChannel  channel =, new  NotificationChannel (CHANNEL_ID、,名称,重要性);   ,,,,,,,,,,,channel.setDescription(描述);      ,,,,,,,,,,,NotificationManager  NotificationManager =, getSystemService (NotificationManager.class);   ,,,,,,,,,,,notificationManager.createNotificationChannel(渠道);   ,,,,,,,}   ,,,}

上述代码应该在应用启动时立即执行,可以放在应用程序中进行初始化。

三,设置通知栏的点击操作

一般点击通知栏会打开对应的活动界面,具体代码如下:

//点击时想要打开的界面
  ,,,Intent  Intent =, new 意图(这个,,AlertDetails.class);
  ,,,//一般点击通知都是打开独立的界面,为了避免添加到现有栈的活动中,可以设置下面的启动方式
  ,,,intent.setFlags (Intent.FLAG_ACTIVITY_NEW_TASK  |, Intent.FLAG_ACTIVITY_CLEAR_TASK);
  ,,,//创建活动类型的pendingIntent,还可以创建广播等其他组件
  ,,,PendingIntent  PendingIntent =, PendingIntent.getActivity(这个,,0,,意图,,0);
  
  ,,,NotificationCompat.Builder  builder =, new  NotificationCompat.Builder(这个,,CHANNEL_ID)
  ,,,,,,,,,,,.setSmallIcon (R.drawable.notification_icon)
  ,,,,,,,,,,,.setContentTitle (“My  notification")
  ,,,,,,,,,,,.setContentText (“Hello 世界!“)
  ,,,,,,,,,,,.setPriority (NotificationCompat.PRIORITY_DEFAULT)
  ,,,,,,,,,,,//设置pendingIntent
  ,,,,,,,,,,,.setContentIntent (pendingIntent)
  ,,,,,,,,,,,//设置点击后是否自动消失
  ,,,,,,,,,,,.setAutoCancel(真正);

四,显示通知

NotificationManagerCompat  notificationManager =, NotificationManagerCompat.from(这个);   ,,,//notificationId 相当于通知的唯一标识,用于更新或者移除通知   ,,,notificationManager.notify (notificationId, builder.build ());

看完上述内容,你们对如何在Android中实现通知栏有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注行业资讯频道,感谢大家的支持。

如何在Android中实现通知栏