Notification的使用——针对Android8.0

实现简单的notification的代码如下:

		String id = "channel";
		String name = "name";
		NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		Notification notification = null;
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
			NotificationChannel mChannel = new NotificationChannel(id, name,
					NotificationManager.IMPORTANCE_HIGH);
			//Android8.0之后,渠道必须要有应用的权限,从手机上设置
			mChannel.enableLights(true);
			mChannel.setLightColor(Color.RED); //小红点颜色
			mChannel.setShowBadge(true);
			notificationManager.createNotificationChannel(mChannel);
			notification = new Notification.Builder(this).setChannelId(id)
					.setContentTitle("标题").setContentText("内容")
					.setSmallIcon(R.drawable.icon).setAutoCancel(true).build();
		} else {
			NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(
					this).setContentTitle("标题")
					.setContentText("内容").setSmallIcon(R.drawable.icon)
					.setOngoing(true).setAutoCancel(true).setDefaults(Notification.DEFAULT_ALL);
			notification = notificationBuilder.build();
		}
		notificationManager.notify(1111, notification);


设置手机应用允许通知的权限:

设置——应用管理——通知管理——打开“允许通知”——在类别里找到相应的渠道,上述代码对应的渠道名为name——打开“允许通知”,其他的铃声或振动权限,看情况而定

你可能感兴趣的:(android)