1. 问题
在Andorid 8.0以上的设备集成推送SDK后,推送接收不到,日志显示通知已经从服务端发送到客户端,但是并未创建通知,这是怎么回事?应该如何解决?
2. 问题原因
自8.0(API Level 26)起,Android 推出了NotificationChannel机制,旨在对通知进行分类管理。如果用户App的targetSdkVersion
大于等于26,且并未设置NotificaitonChannel
,创建的通知是不会弹出的。
3. 解决方案
阿里云移动推送自v3.1.1
版本开始支持NotificationChannel
机制,以下是接入步骤:
3.1 集成新版
-
集成移动推送SDK
v3.1.1
及其以上版本 -
集成服务端OpenApi SDK
v3.9.0
及其以上版本:<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-push</artifactId>
<version>3.9.0</version>
</dependency>
3.2 注册NotificationChannel
在客户端创建自己的NotificationChannel
,可参考下面代码
具体调用位置为:Application的onCreate,云推初始化前后都可以,可参考 Demo
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager mNotificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
// 通知渠道的id
String id = "1";
// 用户可以看到的通知渠道的名字.
CharSequence name = "notification channel";
// 用户可以看到的通知渠道的描述
String description = "notification description";
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(id, name, importance);
// 配置通知渠道的属性
mChannel.setDescription(description);
// 设置通知出现时的闪灯(如果 android 设备支持的话)
mChannel.enableLights(true);
mChannel.setLightColor(Color.RED);
// 设置通知出现时的震动(如果 android 设备支持的话)
mChannel.enableVibration(true);
mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
//最后在notificationmanager中创建该通知渠道
if (mNotificationManager != null) {
mNotificationManager.createNotificationChannel(mChannel);
}
}
3.3 利用OpenApi推送
服务端推送时指定其NotificationChannel
id,可参考如下代码:
-
@Test public void testAdvancedPush() throws Exception { PushRequest pushRequest = new PushRequest(); // 推送目标 pushRequest.setAppKey(appKey); pushRequest.setTarget("DEVICE"); //推送目标: device:推送给设备; account:推送给指定帐号,tag:推送给自定义标签; all: 推送给全部 pushRequest.setTargetValue("xxxxxxxxxxxxxxx"); pushRequest.setPushType("NOTICE"); // 消息类型 MESSAGE NOTICE pushRequest.setDeviceType("ANDROID"); // 设备类型 ANDROID iOS ALL. // 推送配置 pushRequest.setTitle("ALi Push Title"); // 消息的标题 pushRequest.setBody("Ali Push Body"); // 消息的内容 // 推送配置: Android pushRequest.setAndroidNotifyType("BOTH");//通知的提醒方式 "VIBRATE" : 震动 "SOUND" : 声音 "BOTH" : 声音和震动 NONE : 静音 pushRequest.setAndroidOpenType("APPLIACTION"); //点击通知后动作 "APPLICATION" : 打开应用 "ACTIVITY" : 打开AndroidActivity "URL" : 打开URL "NONE" : 无跳转 // 指定notificaitonchannel id pushRequest.setAndroidNotificationChannel("1"); ...... }
注:指定NotificationChannel后,通知的提醒方式(震动、声音等)均为NotificationChannel所指定的提醒方式,服务端的提醒方式配置不再生效
详情可以参考官方文档:
Android 8.0以上设备接收不到推送通知_移动研发平台-阿里云帮助中心