【通知栏】notification

本文详细介绍如何在安卓设备上实现通知栏消息的创建、显示及取消。包括使用Notification.Builder设置图标、提示文字等内容,通过PendingIntent处理点击响应,以及设置声音、指示灯和震动等效果。

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);//取消通知
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值