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——打開“允許通知”,其他的鈴聲或振動權限,看情況而定

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章