Android8.0中通知无法正常使用问题

 

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);

 

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值