Android开发 Notification.Builder通知不显示的问题

问题描述

  在一些国内的一些机型与Android版本上,通知可能会出现不显示的问题。

问题原因

  使用了Notification.Builder构建通知,这个方法可能8.0(可能包含8.0)以下的版本无法正常创建通知了

解决问题

  参考:https://www.jianshu.com/p/cb8426620e74

  使用兼容模式的通知 NotificationCompat.Builder,进行创建。

        NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notify = null;
        int code = Integer.parseInt(RandomUtils.getRandomString(5));
        PendingIntent pendingIntent3 = PendingIntent.getActivity(context.getApplicationContext(), code,
                intent, 0);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context.getApplicationContext())
                .setSmallIcon(R.mipmap.app_icon)
                .setContentTitle(messageBean.getTitle())
                .setContentText(messageBean.getReason())
                .setContentIntent(pendingIntent3);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel("to-do"
                    , "待办消息",
                    NotificationManager.IMPORTANCE_HIGH);
            channel.enableVibration(true);
            channel.setVibrationPattern(new long[]{500});
            manager.createNotificationChannel(channel);
            builder.setChannelId("to-do");
            notify = builder.build();
        } else {
            notify = builder.build();
        }
        //使用默认的声音
        notify.defaults |= Notification.DEFAULT_SOUND;
        notify.sound = Uri.parse("android.resource://" + context.getPackageName() + "/" + R.raw.doorbell);
        notify.defaults |= Notification.DEFAULT_VIBRATE;
        notify.flags |= Notification.FLAG_AUTO_CANCEL; // 但用户点击消息后,消息自动在通知栏自动消失

        manager.notify(code, notify);// 步骤4:通过通知管理器来发起通知。如果id不同,则每click,在status哪里增加一个提示
    }

猜你喜欢

转载自www.cnblogs.com/guanxinjing/p/12802275.html