不一样版本通知栏的建立方式不尽相同,当前官方推荐使用 NotificationCompat
相关的API,兼容到Android 4.0,可是部分新功能,好比内嵌回复操做,旧版本是没法支持的。java
//CHANNEL_ID,渠道ID,Android 8.0及更高版本必需要设置
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
//设置小图标
.setSmallIcon(R.drawable.notification_icon)
//设置标题
.setContentTitle(textTitle)
//设置内容
.setContentText(textContent)
//设置等级
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
复制代码
在 Android 8.0 及更高版本上提供通知,须要在系统中注册应用的通知渠道。android
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, name, importance);
channel.setDescription(description);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
复制代码
上述代码应该在应用启动时当即执行,能够放在 Application
中进行初始化。markdown
通常点击通知栏会打开对应的 Activity
界面,具体代码以下:oop
//点击时想要打开的界面
Intent intent = new Intent(this, AlertDetails.class);
//通常点击通知都是打开独立的界面,为了不添加到现有的activity栈中,能够设置下面的启动方式
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
//建立activity类型的pendingIntent,还能够建立广播等其余组件
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
//设置pendingIntent
.setContentIntent(pendingIntent)
//设置点击后是否自动消失
.setAutoCancel(true);
复制代码
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
//notificationId 至关于通知的惟一标识,用于更新或者移除通知
notificationManager.notify(notificationId, builder.build());
复制代码
还有不少特殊功能,能够直接查看官网教程进行设置。ui