《第一行代码-Android》学习笔记(十四)

来源:互联网 发布:知乎 德昌路 编辑:程序博客网 时间:2024/06/05 02:11

1.通知:

a) 通知的基本用法:

i. 通知可以在活动,广播,服务里面创建,并且创建的方法一样

ii. 相比广播接收器和服务,通知更多的是在后台创建。

          NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);

                     Notification notification = new Notification(R.drawable.ic_launcher"test", System.currentTimeMillis());

                    notification.setLatestEventInfo(this"hello""this is content"null);

           manager.notify(1, notification);

 

b) pendingIntent:可以简单的理解为是延迟的Intent

        PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent(this 

         NotificationActivity.class),PendingIntent.FLAG_CANCEL_CURRENT);

将这个pendingIntent对象传入到上面的setLatestEventInfo中代替上面的null即可;

   pendingIntent的几个flags标签意义详解:

1.FLAG_CANCEL_CURRENT :如果AlarmManager管理的PendingIntent已经存在,那么将会取消当前的PendingIntent,从而创建一个新的PendingIntent 

2.FLAG_UPDATE_CURRENT:如果AlarmManager管理PendingIntent已经存在,可以让新的Intent更新之前PendingIntent中的Intent对象数据,例如更新Intent中的Extras,另外,我们也可以在PendingIntent的原进程中调用PendingIntent的cancel ()把其从系统中移除掉

 3.FLAG_NO_CREATE :如果AlarmManager管理的PendingIntent已经存在,那么将不进行任何操作,直接返回已经 存在的PendingIntent,如果PendingIntent不存在了,那么返回null

c) 如何关闭notification:上面notify时,传入了id=1,在关闭的时候就起了作用:

     NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    manager.cancel(1);

 

d) 通知的高级技巧:

i. 加入音乐铃声:

                            Uri soundUri = Uri.fromFile(new File("/mnt/sdcard/Music/111.mp3"));

     notification.sound = soundUri;

ii. 加入振动:使手机振动需要声明权限:

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

              long[] vibrates = { 0, 1000, 1000, 1000 };

              notification.vibrate = vibrates;

              振动属性是一个长整型数组,用于设置手机静止和振动的市场,以毫秒为单位,0下标表 示静止,1表示振动,2又表示静止。。。以此内推。。。

 

iii. 使指示灯发光:

        notification.ledARGB = Color.GREEN;//指示灯的颜色

                           notification.ledOnMS = 1000;//亮起的时长

                          notification.ledOffMS = 1000;//暗去的时长

notification.flags = Notification.FLAG_SHOW_LIGHTS;//指定通知的一些行为=》显示指示灯

 

iv. 使用缺省:当使用下面的代码时:

notification.defaults = Notification.DEFAULT_ALL;

机器会根据手机环境决定播放什么铃声。

0 0
原创粉丝点击