Android开发学习——使用通知

在按照书中的例子使用通知在设备上没有通知,查找资料后发现Android8后通知需要NotificationChannel,兼容 Android 8.0的通知如下:
               NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

                Intent intent = new Intent(this,NotificationMain2Activity.class);
                PendingIntent pi = PendingIntent.getActivity(this,0,intent,0);

                // 构建 Notification
                Notification.Builder builder = new Notification.Builder(this);
                builder.setContentTitle("ContentTitle")
                        .setSmallIcon(R.drawable.ic_launcher_background)
                        .setContentText("Content Text Here")
                        .setContentIntent(pi)
                        .setAutoCancel(true);

                // 兼容 Android 8.0
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
                    String channelId = "ET_Notification_001";
                    String channelName = "ETtNotificationName";
                    // 第三个参数表示通知的重要程度
                    NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_DEFAULT);
                    // 册后除非卸载再安装否则不改变
                    notificationManager.createNotificationChannel(notificationChannel);
                    builder.setChannelId(channelId);
                }
                // 发出通知
                notificationManager.notify(1, builder.build());

Android开发学习——使用通知

上一篇:Android Service作为后台一直运行监测案例


下一篇:springboot +dubbo项目启动后获取ApplicationContext为null