导语:
今天想完成一个站内信的小功能,第一个想到了用广播强调内容下面来看看详细的代码过程**
1:先给大家填平一个小坑,刚开始使用了这个方法创建对象
Notification notification = new Notification();
notification.icon = R.drawable.ok;
notification.when = System.currentTimeMillis();
notification.tickerText = "接收到了一条通知";
notification.defaults = Notification.DEFAULT_ALL;
NotificationManager manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
manager.notify(NOTIFICATION_ID, notification);
错误,一运行就报错,发现是这样的错误
Java.lang.IllegalArgumentException: contentView required: pkg=com.carter id=43 notification=Notification(vibrate=default,sound=default,defaults=0xffffffff,flags=0x0)
查阅资料发现这个问题是没有发通知之前调用这个方法引起的
Notification.setLatestEventInfo();
修改之后加上这句话
` notification.setLatestEventInfo(NotificationTestActivity.this, “点击查看”, “点击查看详细内容”, pendIntent);
`的版本直接代码报错,根本没有这个方法让使用,最后经过资料查阅,发现这个创建notification的方法已经被舍弃了,官方推荐通过build来创建notification对象
Notification.Builder builder1 = new Notification.Builder(MainActivity.this);
builder1.setSmallIcon(R.drawable.advise2); //设置图标
builder1.setTicker("显示第二个通知");
builder1.setContentTitle("通知"); //设置标题
builder1.setContentText("点击查看详细内容"); //消息内容
builder1.setWhen(System.currentTimeMillis()); //发送时间
builder1.setDefaults(Notification.DEFAULT_ALL); //设置默认的提示音,振动方式,灯光
builder1.setAutoCancel(true);//打开程序后图标消失
Intent intent =new Intent (MainActivity.this,Center.class);
PendingIntent pendingIntent =PendingIntent.getActivity(MainActivity.this, 0, intent, 0);
builder1.setContentIntent(pendingIntent);
Notification notification1 = builder1.build();
notificationManager.notify(124, notification1); // 通过通知管理器发送通知
这样直接就ok了,
2:如果你不想点击之后执行跳转的功能,那么连intent,pendingIntent得内容也能忽略不写
Notification.Builder builder = new Notification.Builder(MainActivity.this);
builder.setSmallIcon(R.drawable.advise);
builder.setTicker("显示第一个通知");
builder.setContentTitle("第一个通知");
builder.setContentText("每天进步一点点");
builder.setWhen(System.currentTimeMillis()); //发送时间
builder.setDefaults(Notification.DEFAULT_ALL);
Notification notification = builder.build();
notificationManager.notify(123, notification);
总结:Android 2.3.3以下的系统中,setLatestEventInfo()方法被遗弃了