Android中通知的简单使用和自定义通知样式
2016-04-06 20:47
330 查看
前言
通知Notification也是Android中很重要的一环。在API11以后,Notification类中的许多方法都被弃用了,因为现在大多数应用都最低支持API15了。所以,我们直接学习新的发送通知的方法就可以了。代码
NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); //获取的是v4包中的兼容构造器,如果不需要,也可以使用Notification.Builder NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this); //配置点击的意图 Intent intent = new Intent(getApplicationContext(), TargetActivity.class); intent.addCategory(Intent.CATEGORY_DEFAULT);//在Activity中也要配置,否则不能启动Activity // intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); //如果通知是在没有Activity栈的情况下发送的,就要配置这个Flags PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0); mBuilder.setContentTitle("测试标题")//设置通知栏标题 .setContentText("测试内容")//设置通知栏显示内容 .setContentIntent(pendingIntent)//设置通知栏点击意图 //.setNumber(number); .setTicker("测试通知来啦")//通知栏首次出现在通知栏,带上动画效果 .setWhen(System.currentTimeMillis())//通知栏时间,一般是直接用系统的 .setPriority(Notification.DEFAULT_ALL)//设置通知栏优先级 // .setAutoCancel(true)//用户单击面板后消失 .setOngoing(false)//true,设置他为一个正在进行的通知。他们通常是用来表示一个后台任务,用户积极参与(如播放音乐)或以某种方式正在等待,因此 //占用设备(如一个文件下载,同步操作,主动网络连接) .setDefaults(Notification.DEFAULT_VIBRATE)//向通知添加声音、闪灯和振动效果的最简单、最一致的方式是使用当前的用户默认设置, //使用default属性,可以组合 //Notification.DEFAULT_ALL Notification.DEFAULT_SOUND 添加声音 // requires VIBRATE permission .setSmallIcon(R.mipmap.ic_launcher); //生成通知 Notification notification = mBuilder.build(); notification.flags = Notification.FLAG_ONGOING_EVENT; notification.flags = Notification.FLAG_NO_CLEAR;//点击清除的时候不清除 mNotificationManager.notify(0,notification);//第一个参数是notification的id,可以用于后来的清除
如何自定义通知
RemoteViews remoteView = new RemoteViews(getPackageName(), R.layout.remoteview); // remoteView.setOnClickPendingIntent(R.id.btn_two, pendingIntent);//为单个按钮设置点击事件 mBuilder.setContent(remoteView).setSmallIcon(R.mipmap.ic_launcher); mBuilder.setContentIntent(pendingIntent);
不知道为什么,自定义通知的时候一定要设置setSmallIcon(),虽然它并不显示,但是不设置就会报错。
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- Android IPC进程间通讯机制
- Android Manifest 用法
- [转载]Activity中ConfigChanges属性的用法
- Android之获取手机上的图片和视频缩略图thumbnails
- Android之使用Http协议实现文件上传功能
- Android学习笔记(二九):嵌入浏览器
- android string.xml文件中的整型和string型代替
- i-jetty环境搭配与编译
- android之定时器AlarmManager
- android wifi 无线调试
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- android 代码实现控件之间的间距
- android FragmentPagerAdapter的“标准”配置
- Android"解决"onTouch和onClick的冲突问题
- android:installLocation简析
- android searchView的关闭事件
- SourceProvider.getJniDirectories