Android中Notification的简单使用

1.发送通知

        //1.获取通知管理器类
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        /**
         * 兼容Android版本8.0系统
         */
        String channeId = "1";
        String channelName = "default";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channeId, channelName, NotificationManager.IMPORTANCE_DEFAULT);
            channel.enableLights(true);         // 开启指示灯,如果设备有的话
            channel.setLightColor(Color.RED);   // 设置指示灯颜色
            channel.setShowBadge(true);         // 检测是否显示角标
            notificationManager.createNotificationChannel(channel);
        }
        //2.构建通知类
        NotificationCompat.Builder builder = new NotificationCompat.Builder(Main2Activity.this, "1");
        builder.setSmallIcon(R.mipmap.ic_launcher);//设置小图标
        builder.setContentTitle("微信");//标题
        builder.setContentText("您有一条未读消息!");//内容
        builder.setWhen(System.currentTimeMillis());    //时间

        //3.获取通知
        Notification notification = builder.build();

        //4.发送通知
        notificationManager.notify(100, notification);

2.取消通知

        //取消通知
       NotificationManager service = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
       service.cancel(100);
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容