概述

Notification,是一种具有全局效果的通知,可以在系统的通知栏中显示。当 APP 向系统发出通知时,它将先以图标的形式显示在通知栏中。用户可以下拉通知栏查看通知的详细信息。通知栏和抽屉式通知栏均是由系统控制,用户可以随时查看。

添加支持库

dependencies {
    implementation "com.android.support:support-compat:28.0.0"
}

创建基本通知

最基本和紧凑形式的通知(也称为折叠表单)显示图标,标题和少量内容文本。在本部分中,您将学习如何创建用户可以单击以在应用中启动活动的通知。

Android 不可折叠通知 安卓通知折叠_优先级

//获取NotificationManager实例
NotificationManager notifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//实例化NotificationCompat.Builde并设置相关属性
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
        .setSmallIcon(R.mipmap.ic_launcher)//设置小图标
        .setContentTitle(textTitle)//设置通知标题
        .setContentText(textContent);//设置通知内容
//通过builder.build()方法生成Notification对象,并发送通知,id=1      
notifyManager.notify(1, mBuilder.build());

设置通知内容

  • 小图标,通过 setSmallIcon() 方法设置
  • 标题,通过 setContentTitle() 方法设置
  • 内容,通过 setContentText() 方法设置
  • 设置通知时间, setWhen(System.currentTimeMillis()) 默认为系统发出通知的时间,通常不用设置
  • 设置优先级 setPriority(NotificationCompat.PRIORITY_DEFAULT)

显示通知

NotificationManagerCompat.notify()

更新通知

要在发出通知后更新此通知,请NotificationManagerCompat.notify()再次调用,并向其发送一个通知,其中包含您之前使用的相同ID。如果先前的通知已被取消,则会创建新通知。

可以 setOnlyAlertOnce()以便您的通知仅在通知第一次出现时才会中断用户(有声音,振动或视觉线索),而不是以后的更新。

删除通知

在发生以下情况之一之前,通知仍然可见:

  • 用户驳回通知。
  • 用户单击通知,并setAutoCancel()在创建通知时调用 。
  • 您需要cancel()特定的通知ID。此方法还会删除正在进行的通知。
  • 您拨打电话cancelAll(),删除之前发出的所有通知。
  • 如果在使用创建通知时设置超时 setTimeoutAfter(),系统会在指定的持续时间过后取消通知。如果需要,您可以在指定的超时持续时间过去之前取消通知。

Notification 设置可点击操作

//获取PendingIntent
   Intent mainIntent = new Intent(this, MainActivity.class);
   PendingIntent mainPendingIntent = PendingIntent.getActivity(this, 0, mainIntent, PendingIntent.FLAG_UPDATE_CURRENT);
   //创建 Notification.Builder 对象
   NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
           .setSmallIcon(R.mipmap.ic_launcher)
           .setAutoCancel(true)//点击通知后自动清除
           .setContentTitle("我是带Action的Notification")
           .setContentText("点我会打开MainActivity")
           .setContentIntent(mainPendingIntent);
   //发送通知
   mNotifyManager.notify(3, builder.build());