添加依赖
虽然使用 Android Studio 创建的大部分项目包含使用 NotificationCompat 所必需的依赖项,但您还是应该验证模块级 build.gradle 文件是否包含以下依赖项
implementation "com.android.support:support-compat:28.0.0"
创建基本通知
对于8.0以上
首先创建渠道并设置重要性
必须先通过向 createNotificationChannel() 传递 NotificationChannel 的实例在系统中注册应用的通知渠道,然后才能在 Android 8.0 及更高版本上提供通知
private void createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String CHANNEL_ID = “your channel id”;
String CHANNEL_NAME = "your channel id";
String description = “”;
int importance = NotificationManager.IMPORTANCE_DEFAULT;//设置渠道重要性,分为4级
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, importance);
channel.setDescription(description);
// 注册渠道
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
由于必须先创建通知渠道,然后才能在 Android 8.0 及更高版本上发布任何通知,因此应在应用启动时(可以写到onCreate中)立即执行这段代码。
通知的重要性分为4级
设置优先级最高,可以直接出现在前台,但是如果用户设置了不允许在屏幕弹出,就不能弹出来了,直接收到状态栏。如果弹出的时候上划,也会有一段时间无法弹出,过一会就会恢复。
用户可见的重要性级别 | 重要性(Android 8.0 及更高版本) | 优先级(Android 7.1 及更低版本) |
紧急 :发出提示音,并以浮动通知的形式显示 | ||
高 :发出提示音 | ||
中 :无提示音 | ||
低 :无提示音,且不会在状态栏中显示。 |
如果需要实现点击动作的需要设置点击意图
Intent intent = new Intent(this,yourActivity.class);
PendingIntent pi = PendingIntent.getActivity(this,0,intent,0);
根据自己的需要选择getActivity(),getBroadcast(),getService()。
三个方法参数都相同,第一个是Context,第二个一般用不到,传入0即可。第三个参数是一个Intent对象,我可以通过这个对象构建出PendingIntent的意图。第四个参数用于确定PendingIntent的行为,有四个值可选,不过一般都写0
FLAG_ONE_SHOT:当前描述的PendingIntent只能被使用一次,同类型的通知栏只能使用一次,后续的通知栏单击后将无法打开。
FLAG_NO_CREATE:当之前的PendingIntent不存在,则返回null(基本用不到)
FLAG_CANCEL_CURRENT:如果PendingIntent已存在,都会被cancel,然后系统创建一个新的PendingIntent。
FLAG_UPDATE_CURRENT:如果PendingIntent已经存在,则他们都会被更新,就是Intent中的extra都会被更新。
然后需要使用 NotificationCompat.Builder 对象设置通知内容和渠道。
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon) //设置小图标
.setContentTitle(textTitle) //标题
.setContentText(textContent) //正文文本
.setContextIntent(pi)//实现点击
.setAutoCancel(true)//点击后是否关闭通知;
Notification notification = builder.build();
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(1, notification)//显示通知,第一个参数为id,int类型,要保证每个通知的ID不同;
这样,一个简单的通知就完成了
一些个性化设置后续补充--