andrid 通知栏的使用

想做个通知栏提示,写下如下代码

  Notification notification2 = new Notification(R.mipmap.ic_launcher,   "通知", System.currentTimeMillis());

  notification2.setLatestEventInfo(getActivity(), "testTitle", "testContent", null);   

居然报错了,我的AS没有找到setLatestEventInfo()方法,怎么办呢,只能百度了,最后还是圆满的解决了.到这里你是不是想问为什么会找不到方法呢,经过查证,官方在API Level 11中,该函数已经被替代,不推荐使用了。古在4.0.3平台也就是API Level 15中,使用Notification的setLatestEventInfo()函数时,显示setLatestEventInfo()效果。建议使用Notification.Builder来创建 notification 实例.


下面给出代码示例:

 NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
 Notification.Builder builder = new Notification.Builder(MainActivity.this);
 builder.setSmallIcon(R.mipmap.ic_launcher); //设置图标
 builder.setTicker("你有一个新通知");
 builder.setContentTitle("通知"); //设置标题
 builder.setContentText("点击查看通知内容"); //消息内容
 builder.setWhen(System.currentTimeMillis()); //发送时间
 //builder.setDefaults(Notification.DEFAULT_ALL); //设置默认的提示音,振动方式,灯光

 builder.setSound(Uri.fromFile(new File("/system/media/audio/ringtones/basic_tones.ogg")));//声音提示
 builder.setAutoCancel(true);//打开程序后图标消失


 Intent intent = new Intent(MainActivity.this, NoticeActivity.class);
 //pendingIntent的参数分别是:1上下文 2. 一般用不到,传0即可  3. 一个Intent的对象
 // 4. 用于确定pendingIntent的行为 有四个值FLAG_ONE_SHOT FLAG_NO_CREATE  FLAG_CANCEL_CURRENT FLAG_UPDATE_CURRENT
 PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 0, intent,  PendingIntent.FLAG_ONE_SHOT);
 builder.setContentIntent(pendingIntent);
 Notification notification1 = builder.build();

 long []vibrates = {0,1000,1000,1000};
 notification1.vibrate=vibrates;    //让手机到通知栏的时候立刻震动1s,再静止1s.再震动1s
 manager.notify(1, notification1); // 通过通知管理器发送通知

andrid 通知栏的使用_第1张图片

你可能感兴趣的:(通知栏)