Android 8通知无法显示求助:我的代码存在什么问题?
问题分析与解决:Android 8通知无法显示
你遇到的问题核心在于Android 8.0(API 26)及以上版本的通知频道机制——你虽然创建了NotificationChannel对象,但没有将它注册到系统的NotificationManager中,系统会直接忽略未归属已注册频道的通知。
修改后的NotificationHelper代码:
public class NotificationHelper { final static String CHANNEL_ID = "MY_CHANNEL_ID"; final static String CHANNEL_NAME = "MY_CHANNEL_NAME"; public static Notification buildNotificationInstance(Context ctx, String title, String message) { Notification notification; NotificationCompat.Builder mBuilder; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH); // 关键:将创建好的通知频道注册到系统 NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.createNotificationChannel(notificationChannel); mBuilder = new NotificationCompat.Builder(ctx, CHANNEL_ID); } else { mBuilder = new NotificationCompat.Builder(ctx); } mBuilder.setContentTitle(title) .setContentText(message) .setSmallIcon(R.drawable.ic_android_black_24dp); Bitmap bm = BitmapFactory.decodeResource(ctx.getResources(), R.mipmap.ic_launcher); mBuilder.setLargeIcon(bm); notification = mBuilder.build(); return notification; } }
关键说明:
- Android O引入通知频道的目的是让用户可以对不同类型的通知进行精细化管理(比如静音、关闭等),所以所有通知必须绑定一个已注册的频道才能显示
- 通知频道只需要注册一次,后续重复调用
createNotificationChannel不会产生副作用,所以你不需要额外判断频道是否已存在 - 你在Activity中调用
notificationManager.notify()的代码是正确的,不需要修改
内容的提问来源于stack exchange,提问作者Adam Varhegyi
相关产品推荐
相关产品推荐

