Android通知未显示即被取消,无报错问题排查求助
针对你遇到的Android 10设备上通知未显示且日志提示No vibration for canceled notification的问题,以下是几个排查方向和修复方案:
1. 修复NotificationChannel的振动配置
日志明确指向振动相关异常,你的代码仅开启了振动但未设置具体振动模式。Android 8.0+的NotificationChannel启用振动时,必须明确指定振动节奏,否则可能触发系统对通知的异常拦截。
修改通道创建代码,补充振动模式设置:
CharSequence name = "My Upload"; String description = "Upload confirmation to firestore"; int importance = NotificationManager.IMPORTANCE_HIGH; NotificationChannel channel = new NotificationChannel(Constants.CHANNEL_UPLOAD_ID, name, importance); channel.setDescription(description); channel.enableVibration(true); // 添加自定义振动节奏,可根据需求调整数组内的毫秒值 channel.setVibrationPattern(new long[]{100, 200, 300, 400, 500}); // 注册通道到系统 NotificationManager notificationManager = getSystemService(NotificationManager.class); notificationManager.createNotificationChannel(channel);
2. 检查通知小图标有效性
Android系统对通知小图标有严格规范:必须是纯色(建议白色)的矢量图或PNG图,不能包含透明以外的杂色(针对Android 7.0+状态栏图标)。如果R.drawable.ic_official_nichx_logo不符合要求,通知会被系统隐藏。
可临时替换为系统默认图标测试:
.setSmallIcon(android.R.drawable.stat_notify_sync)
若替换后通知正常显示,说明你的自定义图标不符合规范,需要调整图标资源。
3. 确保通知通道提前完成注册
虽然Fragment与创建通道的Activity同属一个页面,但如果通道创建代码在Activity生命周期较晚阶段执行(如onStart之后),而Fragment提前调用sendNotification,此时通道可能未完成注册,导致通知无法正常推送。
建议将通道创建逻辑移至Application类的onCreate方法,确保应用启动时就完成通道注册:
public class MyApp extends Application { @Override public void onCreate() { super.onCreate(); createNotificationChannels(); } private void createNotificationChannels() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { CharSequence name = "My Upload"; String description = "Upload confirmation to firestore"; int importance = NotificationManager.IMPORTANCE_HIGH; NotificationChannel channel = new NotificationChannel(Constants.CHANNEL_UPLOAD_ID, name, importance); channel.setDescription(description); channel.enableVibration(true); channel.setVibrationPattern(new long[]{100, 200, 300, 400, 500}); NotificationManager notificationManager = getSystemService(NotificationManager.class); notificationManager.createNotificationChannel(channel); } } }
记得在AndroidManifest.xml中配置该Application类:
<application android:name=".MyApp" ...> ... </application>
4. 排查系统级通知拦截设置
Android 10设备可能存在以下系统设置导致通知被拦截:
- 检查应用通知权限:进入「设置」→「应用和通知」→「你的应用」→「通知」,确保「My Upload」通道的通知权限处于开启状态。
- 检查电池优化设置:若应用被设为「电池优化」模式,系统可能限制通知显示。进入「设置」→「电池」→「电池优化」,找到你的应用并设置为「不优化」。
5. 规范通知ID的使用(非核心但建议优化)
你的代码生成了notificationId变量但未实际使用,而是固定用1作为通知ID。虽然这不会直接导致通知不显示,但重复发送相同ID的通知会覆盖之前的通知,建议使用生成的动态ID:
manager.notify(notificationId, notification.build());
内容的提问来源于stack exchange,提问作者mike

