Nofification是显示在手机状态栏的消息(手机状态栏位于手机的最顶端),代表一种
全局效果的通知。
1、获取NotificationManager
2、显示通知栏:notify(id,notification);
3、取消通知栏:cancle(id);
4、构造Notification并设置显示内容
5、通知栏通知可以设置声音提示,指示灯,以及震动效果
分步解释
第一步:创建Builder对象(是notification的builder)并new出Notification.Builder(this),通过调用builder的方法来设置,setSmallIcon(R.drawable…),setTicker;
第二步(点击后的响应):创建PendingIntent对象并赋值为PendingIntent.getActivity(context,requestCode,intent,flags):
context:this;
requestCode:请求码,0;
intent:创建Intent对象,在new中根据需求选择构造的类.class;
flags–0;
第三步:创建Notification对象,并将builder.build()赋值//4.1即以上,要用builder.build()方法,以下要用builder.getNotification()方法;
第四步:创建NotificationManager对象,因为是系统的常用服务,赋值为getSystemService(Context.NOTIFICATION_SERVICE),需强制转化;调用成员函数notify(id,notification)来加载Notification,id是一个int值,表示notification的id,自行赋值即可
// 发送notification通知
NotificationManager manager;
manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);// 取到通知控制类
private void sendNotification() {
Intent intents = new Intent(this, MainActivity.class);
//制造一个点击通知意图
PendingIntent pdIntent = PendingIntent.getActivity(this, 0, intents, 0);
Notification.Builder builder = new Notification.Builder(
this);
builder.setSmallIcon(R.drawable.ic_launcher);// 设置小图标
builder.setTicker("hello");// 设置手机状态提示内容
builder.setWhen(System.currentTimeMillis());// 设置当前时间
builder.setContentTitle("通知栏通知");// 设置展开后标题
builder.setContentText("本内容来至notification");// 设置展开后内容
builder.setContentIntent(pdIntent);//点击通知栏意图
//builder.setDefaults(Notification.DEFAULT_SOUND);//设置提示声音
//builder.setDefaults(Notification.DEFAULT_LIGHTS);//设置指示灯
//builder.setDefaults(Notification.DEFAULT_VIBRATE);//设置震动
builder.setDefaults(Notification.DEFAULT_ALL);
// 需要添加指示灯和震动的权限
Notification notification = builder.build();// 获取notification
manager.notify(notification_ID, notification);
// 显示通知栏,id自定义一个就行
}
//取消notification通知
private void cancelNotification() {
manager.cancel(notification_ID);//取消通知
}