Android8.0中通知无法正常使用问题
问题描述
Android O做很多修改,如悬浮窗、通知、广播、WiFi、蓝牙等。
近期我在往Android8.0 porting项目过程中就遇到了无法正常发送通知的问题
问题分析
当APP往通知栏发送通知时显示不出来,Toast显示...Failed topost notification on channel "null"...
查看官方文档 https://developer.android.com/preview/features/notification-channels.html
文档里是这样写的:
If you targetAndroid O and post a notification without specifying a valid
notificationschannel, the notification fails to post and the system logs an error.
大意就是说,如果在Android O发送通知需要设置notificationchannel,否则通知会发送失败。
解决思路:
文档中已经说明了,Android O 中发送通知需要设置notification channel。用法如下:
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// The id of the channel.
String id ="my_channel_01";
// The user-visible nameof the channel.
CharSequence name = getString(R.string.channel_name);
// The user-visibledescription of the channel.
String description = getString(R.string.channel_description);
int importance =NotificationManager.IMPORTANCE_LOW;
NotificationChannel mChannel =newNotificationChannel(id, name,importance);
// Configure thenotification channel.
mChannel.setDescription(description);
mChannel.enableLights(true);
// Sets the notificationlight color for notifications posted to this
// channel, if the devicesupports this feature.
mChannel.setLightColor(Color.RED);
mChannel.enableVibration(true);
mChannel.setVibrationPattern(newlong[]{100,200,300,400,500,400,300,200,400});
mNotificationManager.createNotificationChannel(mChannel);
然后应用到Notification中:
mNotificationManager =(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
// Sets an ID for the notification, so it can be updated.
int notifyID =1;
// The id of the channel.
String CHANNEL_ID ="my_channel_01";
// Create a notification and set the notification channel.
Notification notification =newNotification.Builder(MainActivity.this)
.setContentTitle("New Message")
.setContentText("You've received new messages.")
.setSmallIcon(R.drawable.ic_notify_status)
.setChannelId(CHANNEL_ID)
.build();
// Issue the notification.
mNotificationManager.notify(id, notification);
NotificationCompat 使用方法:
NotificationCompat.Builder mBuilder;
mBuilder =newNotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.mipmap.ic_launcher_icon)
.setContentTitle("Title")
.setContentText("Text")
.setOngoing(true)
.setChannelId(id);