Android Notification 通知封装成工具类

本文介绍了一个用于创建Android系统通知的实用工具类。通过该工具类,开发者可以方便地为应用程序创建带有自定义内容、标题及操作的通知。文章详细展示了如何设置通知的各项属性,包括图标、提示文本、主内容等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. public class NotificationUtils {  
  2.   
  3.     private static NotificationManager mNotificationManager;  
  4.     private static Notification notification;  
  5.   
  6.     /** 
  7.      * 创建通知,  * 请在调用此方法时开启子线程 
  8.      * 
  9.      * @param context    上下文 
  10.      * @param icon       通知图片 
  11.      * @param tickerText 通知未拉开的内容 
  12.      * @param title      通知标题 
  13.      * @param content    通知主内容 
  14.      * @param intent     意图 
  15.      * @param id 
  16.      * @param time       控制线程睡眠时间 
  17.      */  
  18.     public static void createNotif(Context context, int icon, String tickerText, String title, String content, Intent intent, int id, long time) {  
  19.         intent.addCategory(Intent.CATEGORY_LAUNCHER);  
  20.         intent.setAction(Intent.ACTION_MAIN);  
  21.         //intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);  
  22.         PendingIntent pendingIntent = PendingIntent.getActivity(context, id, intent, PendingIntent.FLAG_UPDATE_CURRENT);  
  23.   
  24.         mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);  
  25.         NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);  
  26.         mBuilder.setContentTitle(title)  
  27.                 .setContentText(content)  
  28.                 .setContentIntent(pendingIntent)  
  29.                 .setTicker(tickerText)  
  30.                 .setWhen(System.currentTimeMillis())  
  31.                 .setPriority(Notification.PRIORITY_DEFAULT)  
  32.                 .setOngoing(false)  
  33.                 .setAutoCancel(true)  
  34.                 .setDefaults(Notification.DEFAULT_SOUND)  
  35.                 .setSmallIcon(icon);  
  36.   
  37.         notification = mBuilder.build();  
  38.   
  39.         notification.flags = Notification.FLAG_ONGOING_EVENT;  
  40.         notification.flags = Notification.FLAG_AUTO_CANCEL;  
  41.   
  42.         mNotificationManager.notify(id, notification);  
  43.   
  44.         try {  
  45.             Thread.sleep(time);  
  46.         } catch (InterruptedException e) {  
  47.             e.printStackTrace();  
  48.         }  
  49.   
  50.     }  
  51.   
  52.   
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值