本篇博客只是对Android通知进行了比较浅显的研究,适合通知栏初学者借鉴。废话不多说开始撸代码。

Android开发环境

(1)AndroidStudio 3.1.2
(2)Android设备Honor 8 Lite

一、撸代码和效果图

1.1 Demo功能展示

关于Android8.0以上系统通知栏的使用介绍,详细使用可以查看 Android通知栏微技巧,8.0系统中通知栏的适配

@Overrideprotected void onCreate(Bundle savedInstanceState) {....if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {String channelId = "chat";String channelName = "聊天消息";int importance = NotificationManager.IMPORTANCE_HIGH;createNotificationChannel(channelId, channelName, importance);channelId = "subscribe";channelName = "订阅消息";importance = NotificationManager.IMPORTANCE_DEFAULT;createNotificationChannel(channelId, channelName, importance);channelId = "music";channelName = "酷狗音乐";importance = NotificationManager.IMPORTANCE_DEFAULT;createNotificationChannel(channelId, channelName, importance);channelId = "progress";channelName = "notify自带进度条";importance = NotificationManager.IMPORTANCE_DEFAULT;createNotificationChannel(channelId, channelName, importance);channelId = "uc_progress";channelName = "UC下载进度条";importance = NotificationManager.IMPORTANCE_DEFAULT;createNotificationChannel(channelId, channelName, importance);}.....}@TargetApi(Build.VERSION_CODES.O)private void createNotificationChannel(String channelId, String channelName, int importance) {NotificationChannel channel = new NotificationChannel(channelId, channelName, importance);/*** Android8.0启动震动,记得添加震动权限*/channel.enableVibration(true);/*** 先等2秒,再震动2秒,然后就不震动了,所以这个long数组的元素要是偶数个因为奇数个最后一个没用*/channel.setVibrationPattern(new long[]{2000, 2000, 2000});/*** 设置通知到来时手机关屏时指示灯的提示颜色*/channel.enableLights(true);channel.setLightColor(Color.YELLOW);NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);notificationManager.createNotificationChannel(channel);}

1.2 通知栏API的使用

代码分析

/*** 第一个样式通知栏:*/private void firstNotification() {//创建Builder的时候传入“chat”NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "chat");Intent intent = new Intent(this, AActivity.class);PendingIntent pendingIntent = PendingIntent.getActivity(this, 100, intent, PendingIntent.FLAG_CANCEL_CURRENT);Notification notify = builder.//Android8.0上面LargeIcon没有效果setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_directions_railway)).setSmallIcon(R.drawable.ic_local_car).setTicker("通知来了Ticker").  //话说这个有上升动画setContentInfo("ContentInfo--通知文本").//这个在通知中显示不出来setContentText("ContentText--通知文本").setContentTitle("ContentTitle--通知文本").setContentIntent(pendingIntent).setColor(Color.YELLOW).//setVibrate(new long[]{2000, 2000, 2000, 2000}).//Android8.0不起作用//setLights(Color.parseColor("#0000FF"), 5, 5).//Android8.0不起作用build();notify.flags = Notification.FLAG_NO_CLEAR;//此标记为该同志将不会清楚notificationManager.notify(1, notify);}

1.3 模仿酷狗通知

代码分析

  /*** 酷狗通知栏---自定义通知栏*/private void kuGouNotification() {if (kuGouNotify == null) {NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "music");kuGouContentView = new RemoteViews(getPackageName(), R.layout.notify_kugou_layout);Intent preIntent = new Intent();preIntent.setAction("com.kugou.action.pre");PendingIntent prePendingIntent = PendingIntent.getBroadcast(this, 100, preIntent, PendingIntent.FLAG_UPDATE_CURRENT);kuGouContentView.setOnClickPendingIntent(R.id.iv_previous, prePendingIntent);Intent nextIntent = new Intent();nextIntent.setAction("com.kugou.action.next");PendingIntent nextPendingIntent = PendingIntent.getBroadcast(this, 200, nextIntent, PendingIntent.FLAG_UPDATE_CURRENT);kuGouContentView.setOnClickPendingIntent(R.id.iv_next, nextPendingIntent);Intent closeIntent = new Intent();closeIntent.setAction("com.kugou.action.close");PendingIntent closePendingIntent = PendingIntent.getBroadcast(this, 300, closeIntent, PendingIntent.FLAG_UPDATE_CURRENT);kuGouContentView.setOnClickPendingIntent(R.id.iv_close, closePendingIntent);Intent intent = new Intent(this, BActivity.class);PendingIntent pendingIntent = PendingIntent.getActivity(this, 100, intent, PendingIntent.FLAG_CANCEL_CURRENT);kuGouNotify = builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_music)).setSmallIcon(R.drawable.ic_music).setOngoing(true).//设置当前通知栏是否不间断的运行,添加这个之后生成的自定义布局的通知才生效setOnlyAlertOnce(true).setCustomContentView(kuGouContentView).setCustomBigContentView(kuGouContentView). //设置折叠的通知栏setContentIntent(pendingIntent).//悬挂式通知栏,适配乐视上面的折叠通知栏显示不出来setFullScreenIntent(null, true).build();}if (simpleTarget == null) {simpleTarget = new SimpleTarget<Bitmap>() {@Overridepublic void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {kuGouContentView.setImageViewBitmap(R.id.iv_music, resource);notificationManager.notify(2, kuGouNotify);  //放到此处进行发出通知,使得图片加载成功之后弹出通知}};}Glide.with(this).asBitmap().load(Uri.parse(musicPictures[currentIndex])).into(simpleTarget);
//        notify.bigContentView = contentView;   //该方法在API28已经过时}private class KuGouBroadCastReceiver extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {String intentAction = intent.getAction();Log.e("intentAction", intentAction);if ("com.kugou.action.pre".equals(intentAction)) {currentIndex = currentIndex == 0 ? 4 : currentIndex - 1;} else if ("com.kugou.action.next".equals(intentAction)) {currentIndex = currentIndex == 4 ? 0 : currentIndex + 1;} else if ("com.kugou.action.close".equals(intentAction)) {notificationManager.cancel(2);return;}kuGouNotification();}}

1.4 通知栏自定义进度条

代码分析

    private int currentProgress = 1;private NotificationCompat.Builder notifyBuilder = null;  //Builderprivate Notification notifyDefine = null;/*** 通知栏自带进度条*/private void notifyDefineProgress() {if (notifyBuilder == null) {notifyBuilder = new NotificationCompat.Builder(this, "progress");Intent intent = new Intent(this, CActivity.class);PendingIntent pendingIntent = PendingIntent.getActivity(this, 100, intent, PendingIntent.FLAG_CANCEL_CURRENT);notifyDefine = notifyBuilder.setSmallIcon(R.drawable.ic_file_download).setTicker("通知来了Ticker").  //话说这个有上升动画setContentText("ContentText--通知文本").setContentTitle("ContentTitle--通知文本").setContentIntent(pendingIntent).//第三个参数为true时代表是间断的进度条,为false的时候就是正常进度条setProgress(100, currentProgress, false).build();notifyDefine.flags = Notification.FLAG_NO_CLEAR;}notifyDefine = notifyBuilder.setProgress(100, currentProgress, false).build();notificationManager.notify(3, notifyDefine);handler.sendEmptyMessageDelayed(1, 1000);}

1.5 模仿UC通知栏下载进度条

代码分析

private boolean isDownload = true;private Notification ucNotification = null;private RemoteViews ucContentView = null;private int ucCurrentProgress = 1;private int ucCurrentSecondProgress = 5;private void ucDownloadProgress() {if (ucNotification == null) {NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "music");ucContentView = new RemoteViews(getPackageName(), R.layout.notify_uc_layout);ucContentView.setImageViewResource(R.id.iv_pause_play, isDownload ? R.drawable.ic_pause_circle : R.drawable.ic_play_circle);//给ProgressBar设置进度ucContentView.setProgressBar(R.id.pb, 100, ucCurrentProgress, false);//更新ProgressBar第二层进度条ucContentView.setInt(R.id.pb, "setSecondaryProgress", ucCurrentSecondProgress);Intent preIntent = new Intent();preIntent.setAction("com.uc.action.pause.play");PendingIntent prePendingIntent = PendingIntent.getBroadcast(this, 100, preIntent, PendingIntent.FLAG_UPDATE_CURRENT);ucContentView.setOnClickPendingIntent(R.id.iv_pause_play, prePendingIntent);Intent intent = new Intent(this, BActivity.class);PendingIntent pendingIntent = PendingIntent.getActivity(this, 100, intent, PendingIntent.FLAG_CANCEL_CURRENT);ucNotification = builder.setSmallIcon(R.drawable.ic_toys_black).setOngoing(true).//设置当前通知栏是否不间断的运行,添加这个之后生成的自定义布局的通知才生效setCustomBigContentView(ucContentView). //设置折叠的通知栏setContentIntent(pendingIntent).build();}ucContentView.setImageViewResource(R.id.iv_pause_play, isDownload ? R.drawable.ic_pause_circle : R.drawable.ic_play_circle);ucContentView.setProgressBar(R.id.pb, 100, ucCurrentProgress, false);ucContentView.setInt(R.id.pb, "setSecondaryProgress", ucCurrentSecondProgress);if (isDownload) {ucContentView.setImageViewResource(R.id.iv_icon, R.drawable.uc_rotate);handler.sendEmptyMessageDelayed(2, 1000);} else { //false时给iv_icon设置不旋转,必须放在notify方法之前否则该图片设置将会不生效ucContentView.setImageViewResource(R.id.iv_icon, R.drawable.ic_toys_black);}notificationManager.notify(4, ucNotification);  //放到此处进行发出通知,使得图片加载成功之后弹出通知}private class UCBroadCastReceiver extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {String intentAction = intent.getAction();if ("com.uc.action.pause.play".equals(intentAction)) {isDownload = !isDownload;}if (ucCurrentProgress > 100) {ucCurrentProgress = 1;ucCurrentSecondProgress = 5;}if (!isDownload) {//false时给iv_icon设置不旋转ucContentView.setImageViewResource(R.id.iv_icon, R.drawable.ic_toys_black);handler.removeMessages(2);}ucDownloadProgress();}}

三、开发遇到的错误

3.1 Binary XML file line #54: Class not allowed to be inflated android.view.View

解决办法:
Remove the 'View' you are using as a shadow in your layout(or Replace View with TextView) and it works fine. XML used for Remoteview should make use of Views which has @android.widget.RemoteViews.RemoteView annotation. Since a plain View does not has this annotation, you cannot use that in your xml.
意思就是在自定义通知栏时,通知栏的自定义布局中不能使用控件TextView

四、推荐文章

设置Android通知栏Notification的字体/图标颜色随背景色变化而变化

源码地址

Android中Notification的使用(一)相关推荐

  1. android notification的使用方法,详解Android中Notification的使用方法

    在消息通知的时候,我们经常用到两个控件Notification和Toast.特别是重要的和需要长时间显示的信息,用Notification最合适不过了.他可以在顶部显示一个图标以标示有了新的通知,当我 ...

  2. android notification 的总结分析,Android中Notification用法实例总结

    本文实例总结了 Android中Notification用法.分享给大家供大家参考,具体如下: 我们在用手机的时候,如果来了短信,而我们没有点击查看的话,是不是在手机的最上边的状态栏里有一个短信的小图 ...

  3. android开发提示对话框,Android中Notification 提示对话框

    Notification,俗称通知,是一种具有全局效果的通知,它展示在屏幕的顶端,首先会表现为一个图标的形式,当用户向下滑动的时候,展示出通知具体的内容. 一.Notification用于状态栏显示通 ...

  4. Android中notification通知的Demo——震动,铃声,Led灯闪烁

    这里要注意几点: 1. notification的各种方法及参数的应用 2. 旧版本的SDK和新版本的SDK消息推送的写法是有些不一样的   1. notification的各种方法及参数的应用  ( ...

  5. Android中Notification设置setSmallIcon、setLargeIcon无效的问题,仍显示安卓自带的机器人图标(小米10手机)

    问题描述: 使用setSmallIcon.setLargeIcon这两个方法设置通知的图标,但是我的小米10就是显示不出我设置的图标,而是显示安卓系统自带的机器人图标.另一台手机荣耀9却没有这个问题. ...

  6. Android中的Notification

    原帖地址:http://www.cnblogs.com/newcj/archive/2011/03/14/1983782.html Notification 的使用需要导入 3 个类 1 2 3 im ...

  7. 【达内课程】Android中的Notification

    文章目录 什么是通知 一个发送通知的栗子: Android 8.0不能弹出通知 一个兼容8.0的栗子 让通知常驻通知栏 如何清除通知 如何更新通知界面内容 点击通知执行意图 如何实现进度条的通知 如何 ...

  8. Android中使用Notification在状态栏上显示通知

    场景 状态栏上显示通知效果 注: 博客: https://blog.csdn.net/badao_liumang_qizhi 关注公众号 霸道的程序猿 获取编程相关电子书.教程推送与免费下载. 实现 ...

  9. Android中Service深入学习

    概述 1.当用户在与当前应用程序不同的应用程序时,Service可以继续在后台运行. 2.Service可以让其他组件绑定,以便和它交互并进行进程间通信. 3.Service默认运行在创建它的应用程序 ...

最新文章

  1. LightBus新浪微博客户端开源下载
  2. Asp.net mvc 添加Jquery UI
  3. Qt Creator调试C ++示例应用程序
  4. 第三天【DOM4J Xpath】
  5. python中的__name__=='__main__'如何简单理解(一)
  6. python编程胡牌将是什么意思_OpenCV+Python识别车牌和字符分割的实现
  7. java国际化软件_JavaWeb开发——软件国际化(动态元素国际化)
  8. 使用代码控制小米智能插座
  9. 下列哪个网站还未推出微博服务器,新浪微博笔试题与答案
  10. sublime linux中文版,sublime text 3中文免费版
  11. Android 设置gif动态桌面
  12. 我的Android进阶之旅------报 error: Apostrophe not preceded by \ 的错误解决办法
  13. 饥饿游戏2:星火燎原[The Hunger Games:Catching Fire]
  14. 动态电压恢复器(DVR)模型 Matlab/simulink
  15. 万字HBase详解带你畅游大数据的海豚湾
  16. 【CSS】用CSS画太极图
  17. 最完整的Windows系统安装教程(Win7、Win10、Win11)
  18. Typora中(Markdown语法)在符号的上方添加符号或文字
  19. Streamlit学习使用(一)
  20. jQuery 选择器(checked)详解

热门文章

  1. 盛世昊通打造线上线下融合的百业联盟商业生态
  2. C# 让程序开机自动运行的方法
  3. 面试flink开发岗位,看这些就够啦
  4. uniapp开发中ios底部出现安全距离问题怎么解决?
  5. LeetCode(力扣) 刷题注意事项 持续更新 ~ ~
  6. 力扣刷题记录-回溯算法相关题目
  7. TP6-------对接腾讯云直播
  8. 通俗理解 set,dict 背后的哈希表
  9. Android项目从零到上线的全过程
  10. Python爬虫---爬取腾讯动漫全站漫画