我们的手机,每天只要数据开了,一些应用都会有每天的及时推送,告诉我们最新的消息,提醒我们版本的更新,那么这个技术点就是使用了通知机制的通知栏框架,它使用于交互事件的通知,它是位于顶层可以展开的通知列表
Notification有哪些功能作用呢
1》显示接收的短信,消息(QQ,微信,新浪,爱奇艺等)
2》显示客户端的推送消息
3》显示正在进行的事务(正在播放的音乐,下载进度条)
通知状态栏主要涉及到两个类,Notification、NotificationManager
Notification是通知消息类,它里面对应的通知栏的各种属性
NotificationManager是状态栏通知的管理类,负责发送,清除消息通知等
Notification使用步骤
<1>.得到通知管理者,因为NotificationManager是一个系统Service,所以需要通过getService得到
NotificationManager notificationManager= (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
<2>.创建Notification
NotificationCompat.Builder builder=new NotificationCompat.Builder(this);
<3>.为Notification设置各种属性
<4>.通过通知管理者NotificationManager发送通知
notificationManager.notify(0x101,notification);
<5>.删除通知
notificationManager.cancel(NOTIFICATION_ID);
然后再看看完整的代码
布局
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="sendNotification" android:text="发送通知" />
Activity
public void sendNotification(View view){ //实例化通知管理器 NotificationManager notificationManager= (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); //实例化通知 NotificationCompat.Builder builder=new NotificationCompat.Builder(this); builder.setContentTitle("大事件");//设置通知标题 builder.setContentText("不要放孔明灯,容易起火");//设置通知内容 builder.setDefaults(NotificationCompat.DEFAULT_ALL);//设置通知的方式,震动、LED灯、音乐等 builder.setAutoCancel(true);//点击通知后,状态栏自动删除通知 builder.setSmallIcon(android.R.drawable.ic_media_play);//设置小图标 builder.setContentIntent(PendingIntent.getActivity(this,0x102,new Intent(this,RaingRecived.class),0)); //设置点击通知后将要启动的程序组件对应的PendingIntent Notification notification=builder.build(); //发送通知 notificationManager.notify(0x101,notification); }
如果使用手机的震动,闪光灯的话就需要添加权限
<1>.震动权限:<uses-permission android name="android.permission.VIBRATE">
<2>.闪光灯权限:<uses-permission android name="android.permission.FLASHLIGHT">
如果是自定义不带按钮的通知栏
实现方法同上,只是再实例化通知后加上两句代码:
RemoteViews remoteViews=new RemoteViews("com.aa.familyapp",R.layout.activity_mynotification); builder.setCustomContentView(remoteViews);
相当于解析了一个布局文件
转载自:http://blog.csdn.net/qiuqiu_qiuqiu123/article/details/55191991