通知渠道的创建:
@RequiresApi(Build.VERSION_CODES.O)
public void createChannelId(String channelId){
String group_primary = "group_second";
NotificationChannelGroup ncp1 = new NotificationChannelGroup(group_primary, "通知渠道组2");
getmNotificationManager().createNotificationChannelGroup(ncp1);
NotificationChannel chan = new NotificationChannel(channelId,
"通知渠道2",
NotificationManager.IMPORTANCE_DEFAULT);
chan.setLightColor(Color.GREEN);
chan.setGroup(group_primary);
//锁屏的时候是否展示通知
chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
getmNotificationManager().createNotificationChannel(chan);
}
1.使用系统sdk里面的Notification对象创建通知:
public void sendSimpleNotification(Context context) {
int id = 1000;
String channelId = "channel_first";
//这里必须设置chanenelId,要不然该通知在8.0手机上,不能正常显示
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createChannelId(channelId);
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, channelId);
builder.setContentTitle("简单的通知的标题")
.setContentText("这是通知内容")
.setLargeIcon(BitmapFactory.decodeResource(
context.getResources(),
R.drawable.ic_launcher))
.setAutoCancel(true)
.setSmallIcon(R.drawable.ic_launcher)
.setPriority(NotificationCompat.PRIORITY_HIGH);
mNotificationManager.notify(id, builder.build());
}
2.使用v4-26兼容包里面的NotificationCompat类创建通知:
public void sendSimpleNotificationSecond(Context context) {
int id = 1002;
String channelId = "channel_second";
Notification.Builder builder = new Notification.Builder(context);
builder.setContentTitle("简单的通知的标题2")
.setContentText("这是通知内容2")
.setLargeIcon(BitmapFactory.decodeResource(
context.getResources(), R.drawable.ic_launcher))
.setAutoCancel(true)
.setSmallIcon(R.drawable.ic_launcher);
//这里必须设置chanenelId,要不然该通知在8.0手机上,不能正常显示
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createChannelId(channelId);
builder.setChannelId(channelId);
}
//发送通知
mNotificationManager.notify(id, builder.build());
}