参考链接:Notification通知栏 - 掘金
参考链接:
在此之前,需保证手机通知权限已打开
//发起通知栏推送 //此处判断安卓版本号是否大于或者等于Android8.0 public void launchPush() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { String channelId = "chat";//设置通道的唯一ID String channelName = "聊天消息";//设置通道名 int importance = NotificationManager.IMPORTANCE_MAX;//设置通道优先级 createNotificationChannel(channelId, channelName, importance, title, text); } else { sendSubscribeMsg(title, text); } } @TargetApi(Build.VERSION_CODES.O) private void createNotificationChannel(String channelId, String channelName, int importance, String title, String text) { NotificationChannel channel = new NotificationChannel(channelId, channelName, importance); LogUtils.i("channel---" + channel.getId());//chat channel.canBypassDnd();//是否绕过请勿打扰模式 channel.enableLights(true);//闪光灯 channel.setLockscreenVisibility(NotificationCompat.VISIBILITY_SECRET);//锁屏显示通知 channel.setLightColor(Color.RED);//闪关灯的灯光颜色 channel.canShowBadge();//桌面launcher的消息角标 channel.enableVibration(true);//是否允许震动 channel.getAudioAttributes();//获取系统通知响铃声音的配置 channel.getGroup();//获取通知取到组 channel.setBypassDnd(true);//设置可绕过 请勿打扰模式 channel.setVibrationPattern(new long[]{100, 100, 200});//设置震动模式 channel.shouldShowLights();//是否会有灯光 NotificationManager notificationManager = (NotificationManager) App.getApplication().getSystemService(NOTIFICATION_SERVICE); notificationManager.createNotificationChannel(channel); sendSubscribeMsg(title, text); } public void sendSubscribeMsg(String title, String text) { NotificationManager manager = (NotificationManager) App.getApplication().getSystemService(NOTIFICATION_SERVICE); Notification notification = new NotificationCompat.Builder(App.getApplication(), "chat") .setContentTitle(title) .setContentText(text) .setWhen(System.currentTimeMillis()) .setSmallIcon(R.mipmap.ic_launcher) .setDefaults(Notification.DEFAULT_ALL) .setLargeIcon(BitmapFactory.decodeResource(App.getApplication().getResources(), R.mipmap.ic_launcher)) .setAutoCancel(true) .build(); manager.notify(2, notification); }
通过该方法推送的消息,手动上滑悬浮框后,会进入一段休眠时间,悬浮窗不再出现,