消息通知(工具类封装)"/>
android使用notification消息通知(工具类封装)
代码直接复制粘贴就可以用了,参数可以更具自己需求添加
private NotificationManager manager;private Notification notification;private static final String NORMAL_CHANNEL_ID = "my_notification_normal";private static final String IMPORTANT_CHANNEL_ID = "my_notification_important";/*** 实现包装方法(参数按自己需求来)* @param title 标题* @param content 内容* @param priorityType 通知级别:0为重要通知(有提示音),非0为普通通知(无提示音)*/public void sendNotify (String title, String content, int priorityType) {manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);NotificationChannel wsschannel; // channel(安卓8.0及以上才用到)String channel_id = IMPORTANT_CHANNEL_ID; // channelId用于绑定builder配置int priority = NotificationCompat.PRIORITY_LOW; // 通知级别// 判断是否8.0及以上版本,并选择发送消息的级别if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {if (priorityType == 0) {wsschannel = new NotificationChannel(IMPORTANT_CHANNEL_ID, "重要通知", NotificationManager.IMPORTANCE_HIGH);channel_id = IMPORTANT_CHANNEL_ID;} else {wsschannel = new NotificationChannel(NORMAL_CHANNEL_ID, "一般通知", NotificationManager.IMPORTANCE_LOW);channel_id = NORMAL_CHANNEL_ID;}manager.createNotificationChannel(wsschannel);}// 通知级别if (priorityType == 0) {priority = NotificationCompat.PRIORITY_HIGH;} else {priority = NotificationCompat.PRIORITY_LOW;}// 点击意图Intent intent = new Intent(this, MainActivity.class);PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE);// 通知配置notification = new NotificationCompat.Builder(this, channel_id).setContentTitle(title) // 标题.setContentText(content) // 内容.setSmallIcon(R.mipmap.user) // 小图标.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.setting)).setPriority(priority) // 7.0 设置优先级.setContentIntent(pendingIntent) // 跳转意图.setAutoCancel(true) // 点击后自动销毁.build();// 给每个通知随机idint id = (int) ((Math.random() * 9 + 1) * (6));// 生成通知manager.notify(id , notification);}
// 示例
sendNotify("服务关闭", "服务关闭成功", 0);
更多推荐
android使用notification消息通知(工具类封装)
发布评论