Notification在android 8.0以上设置时,需要设置渠道信息才能够正常显示通知。 直接上代码:
String id = "my_channel_01";
String name="my_channel_name";
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_LOW);
Toast.makeText(this, mChannel.toString(), Toast.LENGTH_SHORT).show();
Log.i(TAG, mChannel.toString());
notificationManager.createNotificationChannel(mChannel);
notification = new Notification.Builder(this)
.setChannelId(id)
.setContentTitle("This is content title")
.setContentText("This is content text")
.setSmallIcon(R.mipmap.ic_launcher).build();
} else {
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setContentTitle("This is content title")
.setContentText("This is content text")
.setSmallIcon(R.mipmap.ic_launcher)
.setOngoing(true)
notification = notificationBuilder.build();
}
notificationManager.notify(1, notification);