Notification的使用

本文详细介绍了如何在Android中创建和定制通知,包括设置图标、默认行为(如灯光、声音和震动)、通知的显示方式及如何通过Intent启动特定的Activity。

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

		// NotificationManager
		NotificationManager notificationManager = (NotificationManager) this
				.getSystemService(Context.NOTIFICATION_SERVICE);
		// Notification
		Notification notification = new Notification();
		// 标致
		notification.icon = R.drawable.ic_launcher;
		// 灯光
		notification.defaults = Notification.DEFAULT_LIGHTS;
		// 声音
		notification.defaults |= Notification.DEFAULT_SOUND;
		// 震动
		notification.defaults |= Notification.DEFAULT_VIBRATE;
		// 点一下就消失
		notification.flags |= Notification.FLAG_AUTO_CANCEL;
		// 时间
		notification.when = System.currentTimeMillis();
		// 内容
		notification.tickerText = "八月中秋,紫禁一战!";

		Intent intent = new Intent(this, ResultActivity.class);
		intent.putExtra("title", "title");
		intent.putExtra("when", "2013-08-01");
		intent.putExtra("tickerText", "紫禁一战");

		/**
		 * 系统会检查当前所有已创建的Task中是否有该要启动的Activity的Task,若有,则在该Task上创建Activity,
		 * 若没有则新建具有该Activity属性的Task,并在该新建的Task上创建Activity。
		 */
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
		intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
		intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
		/**
		 * 如果在当前Task中,有要启动的Activity,那么把该Acitivity之前的所有Activity都关掉,
		 * 并把此Activity置前以避免创建Activity的实例
		 */
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		/**
		 * PendingIntent 为Intent的包装,这里是启动Intent的描述,
		 * PendingIntent.getActivity返回的PendingIntent表示
		 * ,此PendingIntent实例中的Intent是用于启动 Activity
		 * 的Intent。PendingIntent.getActivity的参数依次为:Context,发送者的请求码(可以填0),
		 * 用于系统发送的Intent,标志位。
		 * 
		 * 其中 PendingIntent.FLAG_UPDATE_CURRENT 表示如果该描述的PendingIntent已存在,
		 * 则改变已存在的PendingIntent的Extra数据为新的PendingIntent的Extra数据。
		 */
		PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
				intent, PendingIntent.FLAG_UPDATE_CURRENT);
		
		// 设置在nority列表里的该norifycation得显示情况。
		notification.setLatestEventInfo(this, "致中秋", "床前明月光,疑是地上霜!",
				contentIntent);
		/**
		 * 在你的程序中标识Notification的id值(用来区分同一程序中的不同Notifycation,
		 * 如果程序中只有一个Notification那么这里随便你填什么都可以,不过类型必须要为int),要通知的Notification。
		 */
		notificationManager.notify(new Random().nextInt(), notification);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值