关于Notification通知的基本使用

来源:互联网 发布:淘宝店铺设计师 编辑:程序博客网 时间:2024/06/06 19:41

1.创建通知管理对象:

 NotificationManager notificationManager =                (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

2.创建一个通知对象:

 Notification notification = new NotificationCompat.Builder(this)                .setContentTitle("您有新的消息")                .setContentText("恭喜您中了500万人民币")                .setWhen(System.currentTimeMillis())                .setSmallIcon(R.mipmap.ic_launcher)                .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))                // 有这句,下拉的通知可以点击了                .setContentIntent(pi)                // 加这句后,点击通知后,通知栏的通知才会消失                .setAutoCancel(true)                /**                 * 以下这句是在通知发出的时候播放一段音频                 */                .setSound(Uri.fromFile(new File(Environment.getExternalStorageDirectory().getPath()+"/Music/bingo.mp3")))                /**                 * .setVibrate(new long[]{})方法设置手机来通知时震动,方法参数是个长整形数组,                 * 数组第1个元素值表示来通知时手机静止时间长度,第2个元素值表示手机震动时长,第3个表示                 * 手机静止时长,第4个元素值表示手机震动时长,以此类推。                 * 下面设置来通知时静止0,震动1s,静止1s,震动1s                 */                .setVibrate(new long[]{0,1000,1000,1000})                /**                 * setLights()方法设置来通知后像微信信息来了一样 LED 灯开始闪烁,                 * 方法第一个参数用于指定 LED 灯颜色                 * 第2个参数用于指定 LED 灯亮起的时长                 * 第3个参数用于指定 LED 灯暗下去的时长                 */                .setLights(Color.GREEN,1000,1000)                .build();

注意,默认通知显示通知栏是不点击的,如果想下拉的通知可以点击,需要加: .setContentIntent(pi),那么在创建通知对象前得先创建PendingIntent对象:

 Intent intent = new Intent(this,NotificationActivity.class);        PendingIntent pi = PendingIntent.getActivity(this,0,intent,0);

此处,PendingIntent包含了一个页面跳转的intent,于是点击通知后可实现页面跳转。

3.发送通知:

notificationManager.notify(1,notification);

如果觉得以上创建Notification对象时设置这么多太麻烦,可以使用手机的默认设置,它会根据当前手机的环境来决定播放什么铃声,以及如何震动等。创建默认通知对象写法:

 Notification defaultNotification = new NotificationCompat.Builder(this)                .setContentTitle("您有新的消息")                .setContentText("恭喜您中了500万人民币")                .setWhen(System.currentTimeMillis())                .setSmallIcon(R.mipmap.ic_launcher)                .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))                // 有这句,下拉的通知可以点击了                .setContentIntent(pi)                // 加这句后,点击通知后,通知栏的通知才会消失                .setAutoCancel(true)                .setDefaults(NotificationCompat.DEFAULT_ALL)                .build();

就是加一句:.setDefaults(NotificationCompat.DEFAULT_ALL)即可。

一篇写的比较详细的Notification的文章,包含使用RemoteView实现自定义布局:http://www.cnblogs.com/zhangyingai/p/7087377.html

1 0
原创粉丝点击