通知(Notification)初探

通知用法:1.在活动里创建;2.在广播接收器里创建;3.在服务里创建


步骤:

1.通过NotificationManager来对通知进行管理,调用Context的getSystemService()方法获取到(参数为Context.NOTIFICATION_SERVICE);

2.创建一个Notification对象。参数一:指定通知的图标;参数二:指定通知ticker内容;参数三:指定通知被创建的时间,以毫秒为单位

3.对通知的布局进行设定,调用Notification的setLatestEventInfo()方法来设置。参数一:Context;参数二:标题内容;参数三:正文内容;参数四:点击事件

4.设置点击效果,PendingIntent,可根据需求使用getActivity()、getBroadcast()、getService()方法获取。参数一:Context;参数二:0;参数三:Intent对象;参数四:PendingItent的行为

5.显示通知,调用NotificationManager的notify()方法。参数一:id,每个通知所指定的id是唯一的;参数二:Notification对象

NotificationManager mamager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.ic_launcher, "This is ticker text",System.currentTimeMillis());
Intent intent = new Intent(this, NotificationActivity.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
notification.setLatestEventInfo(this, "This is content title", "This is content text", pi);
mamager.notify(1, notification);

6.使通知消失

NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.cancel(1);
想要取消哪一条通知,就在cancel()方法中传入该通知的id



高级技巧

1.音频

Uri soundUri = Uri.fromFile(new File("/system/media/audio/ringtones/...."));

notification.sound = soundUri;

2.震动

long[] vibrates = {0, 1000, 1000, 1000};
notification.vibrate = vibrates;
下标为0: 表示手机静止时常。下标为1:表示手机震动时常。依次类推

权限:<uses-permission android:name="android.permission.VIBRATE"/>

3.LED灯

			notification.ledARGB = 0xFF0000;
			notification.ledOnMS = 1000;
			notification.ledOffMS = 1000;
			notification.flags = Notification.FLAG_SHOW_LIGHTS;

也可以默认设置,会根据手机的具体环境来设置

notification.defaults = Notification.FLAG_SHOW_LIGHTS;



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值