Android Notification自定义通知样式你要知道的事(android 8.0之前)

本文将根据个人经验对Notification做个总结,以供参考!

什么是通知(Notification)

通知是一个可以在应用程序正常的用户界面之外显示给用户的消息。
通知发出时,它首先出现在状态栏的通知区域中,用户打开通知抽屉可查看通知详情。通知区域和通知抽屉都是用户可以随时查看的系统控制区域。

作为安卓用户界面的重要组成部分,通知有自己的设计指南。在Android 5.0(API level 21)中引入的 Material Design 的变化是特别重要的,更多信息请阅读 通知设计指南

如何创建通知

随着Android系统不断升级,Notification的创建方式也随之变化,主要变化如下:

Android 3.0之前

Android 3.0 (API level 11)之前,使用new Notification()方式创建通知:


   
   
  1. NotificationManager mNotifyMgr =
  2. (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
  3. PendingIntent contentIntent = PendingIntent.getActivity(
  4. this, 0, new Intent(this, ResultActivity.class), 0);
  5. Notification notification = new Notification(icon, tickerText, when);
  6. notification.setLatestEventInfo(this, title, content, contentIntent);
  7. mNotifyMgr.notify(NOTIFICATIONS_ID, notification);
Android 3.0 (API level 11)及更高版本

Android 3.0开始弃用new Notification()方式,改用Notification.Builder()来创建通知:


   
   
  1. NotificationManager mNotifyMgr =
  2. (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
  3. PendingIntent contentIntent = PendingIntent.getActivity(
  4. this, 0, new Intent(this, ResultActivity.class), 0);
  5. Notification notification = new Notification.Builder(this)
  6. .setSmallIcon(R.drawable.notification_icon)
  7. .setContentTitle("My notification")
  8. .setContentText("Hello World!")
  9. .setContentIntent(contentIntent)
  10. .build();// getNotification()
  11. mNotifyMgr.notify(NOTIFICATIONS_ID, notification);

这里需要注意: “build()” 是Androdi 4.1(API level 16)加入的,用以替代
“getNotification()”。API level 16开始弃用”getNotification()”

兼容Android 3.0之前的版本

为了兼容API level 11之前的版本,v4 Support Library中提供了
NotificationCompat.Builder()这个替代方法。它与Notification.Builder()类似,二者没有太大区别。


   
   
  1. NotificationManager mNotifyMgr =
  2. (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
  3. PendingIntent contentIntent = PendingIntent.getActivity(
  4. this, 0, new Intent(this, ResultActivity.class), 0);
  5. NotificationCompat.Builder mBuilder =
  6. new NotificationCompat.Builder(this)
  7. .setSmallIcon(R.drawable.notification_icon)
  8. .setContentTitle("My notification")
  9. .setContentText("Hello World!")
  10. .setContentIntent(contentIntent);
  11. mNotifyMgr.notify(NOTIFICATIONS_ID, mBuilder.build());

注:除特别说明外,本文将根据 NotificationCompat.Builder() 展开解析,
Notification.Builder()类似。

通知基本用法

通知的必要属性

一个通知必须包含以下三项属性:

  • 小图标,对应 setSmallIcon()
  • 通知标题,对应 setContentTitle()
  • 详细信息,对应 setContentText()

其他属性均为可选项,更多属性方法请参考NotificationCompat.Builder

尽管其他都是可选的,但一般都会为通知添加至少一个动作(Action),这个动作可以是跳转到Activity、启动一个Service或发送一个Broadcas等。 通过以下方式为通知添加动作:

  • 使用PendingIntent
  • 通过大视图通知的 Action Button //仅支持Android 4.1 (API level 16)及更高版本,稍后会介绍
创建通知

1、实例化一个NotificationCompat.Builder对象


   
   
  1. NotificationCompat. Builder mBuilder =
  2. new NotificationCompat. Builder( this)
  3. .setSmallIcon( R.drawable.notification_icon)
  4. .setContentTitle( "My notification")
  5. .setContentText( "Hello World!");

NotificationCompat.Builder自动设置的默认值:

  • priority: PRIORITY_DEFAULT
  • when: System.currentTimeMillis()
  • audio stream: STREAM_DEFAULT

2、定义并设置一个通知动作(Action)


   
   
  1. Intent resultIntent = new Intent(this, ResultActivity.class);
  2. PendingIntent resultPendingIntent = PendingIntent.getActivity(
  3. this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
  4. mBuilder.setContentIntent(resultPendingIntent);

3、生成Notification对象

Notificatioin notification = mBuilder.build();
   
   

4、使用NotificationManager发送通知


   
   
  1. // Sets an ID for the notification
  2. int mNotificationId = 001;
  3. // Gets an instance of the NotificationManager service
  4. NotificationManager mNotifyMgr =
  5. (NotificationManager) getSystemService(NOTIFI CATION_SERVICE);
  6. // Builds the notification and issues it.
  7. mNotifyMgr .notify(mNotificationId, notification);
更新通知

更新通知很简单,只需再次发送相同ID的通知即可,如果之前的通知依然存在则会更新通知属性,如果之前通知不存在则重新创建。
示例代码:


   
   
  1. NotificationManager mNotifyMgr =
  2. (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
  3. // Sets an ID for the notification, so it can be updated
  4. int notifyID = 1;
  5. NotificationCompat.Builder mNotifyBuilder =
  6. new NotificationCompat.Builder(this)
  7. .setContentTitle("New Message")
  8. .setContentText("You've received new messages.")
  9. .setSmallIcon(R.drawable.ic_notify_status);
  10. int numMessages = 0;
  11. ...
  12. mNotifyBuilder.setContentText("new content text")
  13. .setNumber(++numMessages);
  14. mNotifyMgr.notify(notifyID, mNotifyBuilder.build());
  15. ...
取消通知

取消通知有如下4种方式:

  • 点击通知栏的清除按钮,会清除所有可清除的通知
  • 设置了 setAutoCancel() 或 FLAG_AUTO_CANCEL的通知,点击该通知时会清除它
  • 通过 NotificationManager 调用 cancel() 方法清除指定ID的通知
  • 通过 NotificationManager 调用 cancelAll() 方法清除所有该应用之前发送的通知

通知类型

大视图通知

通知有两种视图:普通视图和大视图。
普通视图:



大视图:


默认情况下为普通视图,可通过NotificationCompat.Builder.setStyle()设置大视图。

注: 大视图(Big Views)由Android 4.1(API level 16)开始引入,且仅支持Android 4.1及更高版本。

构建大视图通知

以上图为例:
1、构建Action Button的PendingIntent


   
   
  1. Intent dismissIntent = new Intent(this, PingService.class);
  2. dismissIntent.setAction(CommonConstants.ACTION_DISMISS);
  3. PendingIntent piDismiss = PendingIntent.getService(
  4. this, 0, dismissIntent, 0);
  5. Intent snoozeIntent = new Intent(this, PingService.class);
  6. snoozeIntent.setAction(CommonConstants.ACTION_SNOOZE);
  7. PendingIntent piSnooze =
  8. PendingIntent.getService(this, 0, snoozeIntent, 0);

2、构建NotificatonCompat.Builder对象


   
   
  1. NotificationCompat.Builder builder =
  2. new NotificationCompat.Builder( this)
  3. .setSmallIcon(R.drawable.ic_stat_notification)
  4. .setContentTitle(getString(R. string.notification))
  5. .setContentText(getString(R. string.ping))
  6. .setDefaults(Notification.DEFAULT_ALL)
  7. // 该方法在Android 4.1之前会被忽略
  8. .setStyle( new NotificationCompat.BigTextStyle()
  9. .bigText(msg))
  10. //添加Action Button
  11. .addAction (R.drawable.ic_stat_dismiss,
  12. getString(R. string.dismiss), piDismiss)
  13. .addAction (R.drawable.ic_stat_snooze,
  14. getString(R. string.snooze), piSnooze);

3、其他步骤与普通视图相同

进度条通知

明确进度的进度条
使用setProgress(max, progress, false)来更新进度。
max: 最大进度值
progress: 当前进度
false: 是否是不明确的进度条

模拟下载过程,示例如下:


   
   
  1. int id = 1;
  2. ...
  3. mNotifyManager = (NotificationManager)
  4. getSystemService(Context.NOTIFICATION_SERVICE);
  5. mBuilder = new NotificationCompat.Builder(this);
  6. mBuilder.setContentTitle("Picture Download")
  7. .setContentText("Download in progress")
  8. .setSmallIcon(R.drawable.ic_notification);
  9. // Start a lengthy operation in a background thread
  10. new Thread(
  11. new Runnable() {
  12. @Override
  13. public void run() {
  14. int incr;
  15. for (incr = 0; incr <= 100; incr+=5) {
  16. mBuilder.setProgress(100, incr, false);
  17. mNotifyManager.notify(id, mBuilder.build());
  18. try {
  19. // Sleep for 5 seconds
  20. Thread.sleep(5*1000);
  21. } catch (InterruptedException e) {
  22. Log.d(TAG, "sleep failure");
  23. }
  24. }
  25. mBuilder.setContentText("Download complete")//下载完成
  26. .setProgress(0,0,false); //移除进度条
  27. mNotifyManager.notify(id, mBuilder.build());
  28. }
  29. }
  30. ).start();


上图,分别为下载过程中进度条通知 和 下载完成移除进度条后的通知。

  • 不确定进度的进度条
    使用setProgress(0, 0, true)来表示进度不明确的进度条

    mBuilder.setProgress(0, 0, true); mNotifyManager.notify(id, mBuilder.build());


    浮动通知(Heads-up Notifications)

    Android 5.0(API level 21)开始,当屏幕未上锁且亮屏时,通知可以以小窗口形式显示。用户可以在不离开当前应用前提下操作该通知。
    如图:


    
       
       
    1. NotificationCompat. Builder mNotifyBuilder =
    2. new NotificationCompat. Builder( this)
    3. .setContentTitle( "New Message")
    4. .setContentText( "You've received new messages.")
    5. .setSmallIcon( R.drawable.ic_notify_status)
    6. .setFullScreenIntent(pendingIntent, false);

    以下两种情况会显示浮动通知:

    • setFullScreenIntent(),如上述示例。
    • 通知拥有高优先级且使用了铃声和振动
    锁屏通知

    Android 5.0(API level 21)开始,通知可以显示在锁屏上。用户可以通过设置选择是否允许敏感的通知内容显示在安全的锁屏上。
    你的应用可以通过setVisibility()控制通知的显示等级:

    • VISIBILITY_PRIVATE : 显示基本信息,如通知的图标,但隐藏通知的全部内容
    • VISIBILITY_PUBLIC : 显示通知的全部内容
    • VISIBILITY_SECRET : 不显示任何内容,包括图标
    自定义通知

    Android系统允许使用RemoteViews来自定义通知。
    自定义普通视图通知高度限制为64dp,大视图通知高度限制为256dp。同时,建议自定义通知尽量简单,以提高兼容性。

    自定义通知需要做如下操作:
    1、创建自定义通知布局
    2、使用RemoteViews定义通知组件,如图标、文字等
    3、调用setContent()将RemoteViews对象绑定到NotificationCompat.Builder
    4、同正常发送通知流程

    注意: 避免为通知设置背景,因为兼容性原因,有些文字可能看不清。

    定义通知文本样式

    通知的背景颜色在不同的设备和版本中有所不同,Android2.3开始,系统定义了一套标准通知文本样式,建议自定义通知使用标准样式,这样有助于通知文本可见。
    通知文本样式:

    
       
       
    1. Android 5.0之前可用:
    2. android:style/TextAppearance.StatusBar.EventContent.Title // 通知标题样式
    3. android:style/TextAppearance.StatusBar.EventContent // 通知内容样式
    4. Android 5.0及更高版本:
    5. android:style/TextAppearance.Material.Notification.Title // 通知标题样式
    6. android:style/TextAppearance.Material.Notification // 通知内容样式

    更多通知的标准样式和布局,可参考源码frameworks/base/core/res/res/layout路径下的通知模版如:

    
       
       
    1. Android 5.0之前:
    2. notification_template_base.xml
    3. notification_template_big_base.xml
    4. notification_template_big_picture.xml
    5. notification_template_big_text.xml
    6. Android 5.0 及更高版本:
    7. notification_template_material_base.xml
    8. notification_template_material_big_base.xml
    9. notification_template_material_big_picture.xml
    10. notification_template_part_chronometer.xml
    11. notification_template_progressbar.xml
    12. 等等。

    保留Activity返回栈

    常规Activity

    默认情况下,从通知启动一个Activity,按返回键会回到主屏幕。但某些时候有按返回键仍然留在当前应用的需求,这就要用到TaskStackBuilder了。

    1、在manifest中定义Activity的关系

    
       
       
    1. Android 4.0.3 及更早版本
    2. <activity
    3. android:name = ".ResultActivity" >
    4. <meta-data
    5. android:name = "android.support.PARENT_ACTIVITY"
    6. android:value = ".MainActivity" />
    7. </activity>
    8. Android 4.1 及更高版本
    9. <activity
    10. android:name = ".ResultActivity"
    11. android:parentActivityName = ".MainActivity" >
    12. </activity>

    2、创建返回栈PendingIntent

    
       
       
    1. Intent resultIntent = new Intent(this, ResultActivity.class);
    2. TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    3. // 添加返回栈
    4. stackBuilder.addParentStack(ResultActivity.class);
    5. // 添加Intent到栈顶
    6. stackBuilder.addNextIntent(resultIntent);
    7. // 创建包含返回栈的pendingIntent
    8. PendingIntent resultPendingIntent =
    9. stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    10. NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    11. builder.setContentIntent(resultPendingIntent);
    12. NotificationManager mNotificationManager =
    13. (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    14. mNotificationManager.notify(id, builder.build());

    上述操作后,从通知启动ResultActivity,按返回键会回到MainActivity,而不是主屏幕。

    特殊Activity

    默认情况下,从通知启动的Activity会在近期任务列表里出现。如果不需要在近期任务里显示,则需要做以下操作:

    1、在manifest中定义Activity

    
       
       
    1. <activity
    2. android:name = ".ResultActivity"
    3. android:launchMode = "singleTask"
    4. android:taskAffinity = ""
    5. android:excludeFromRecents = "true" >
    6. </activity>

    2、构建PendingIntent

    
       
       
    1. NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    2. Intent notifyIntent = new Intent(this, ResultActivity.class);
    3. // Sets the Activity to start in a new, empty task
    4. notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
    5. | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    6. PendingIntent notifyPendingIntent =
    7. PendingIntent.getActivity(this, 0, notifyIntent,
    8. PendingIntent.FLAG_UPDATE_CURRENT);
    9. builder.setContentIntent(notifyPendingIntent);
    10. NotificationManager mNotificationManager =
    11. (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    12. mNotificationManager.notify(id, builder.build());

    上述操作后,从通知启动ResultActivity,此Activity不会出现在近期任务列表中。

    通知常见属性和常量

    通知的提醒方式

    1、声音提醒

    • 默认声音
      notification.defaults |= Notification.DEFAULT_SOUND;
    • 自定义声音
      notification.sound = Uri.parse(“file:///sdcard0/notification.ogg”);

    2、震动提醒


    • 默认振动
      notification.defaults |= Notification.DEFAULT_VIBRATE;
    • 自定义振动
      long[] vibrate = {100, 200, 300, 400}; //震动效果
      // 表示在100、200、300、400这些时间点交替启动和关闭震动 notification.vibrate = vibrate;

    3、闪烁提醒


    • 默认闪烁
      notification.defaults |= Notification.DEFAULT_LIGHTS;
    • 自定义闪烁
      notification.ledARGB = 0xff00ff00; // LED灯的颜色,绿灯
      notification.ledOnMS = 300; // LED灯显示的毫秒数,300毫秒
      notification.ledOffMS = 1000; // LED灯关闭的毫秒数,1000毫秒
      notification.flags |= Notification.FLAG_SHOW_LIGHTS; // 必须加上这个标志
    常见的Flags

    • FLAG_AUTO_CANCEL
      当通知被用户点击之后会自动被清除(cancel)
    • FLAG_INSISTENT
      在用户响应之前会一直重复提醒音
    • FLAG_ONGOING_EVENT
      表示正在运行的事件
    • FLAG_NO_CLEAR
      通知栏点击“清除”按钮时,该通知将不会被清除
    • FLAG_FOREGROUND_SERVICE
      表示当前服务是前台服务
      更多Notification属性详见Notification

    来一些基础知识:

    基本属性
    publicBuilder setTicker(CharSequence tickerText)
    设置状态栏开始动画的文字
     
    publicBuilder setContentTitle(CharSequence title)
    设置内容区的标题,必须设置
     
    publicBuilder setContentText(CharSequence text)
    设置内容区的内容,必须设置
     
    publicBuilder setContentIntent(PendingIntent intent)
    设置点击通知后操作(可以跳转Activity,打开Service,或者发送广播)
     
    publicBuilder setColor(@ColorIntint argb)
    这个可以设置smallIcon的背景色
     
    publicBuilder setSmallIcon(@DrawableResint icon)
    设置小图标,必须设置
     
    publicBuilder setLargeIcon(Bitmap b)
    设置打开通知栏后的大图标
     
    publicBuilder setWhen(long when)
    设置显示通知的时间,不设置默认获取系统时间,这个值会在Notification上面显示出来
     
    publicBuilder setAutoCancel(boolean autoCancel)
    设置为true,点击该条通知会自动删除,false时只能通过滑动来删除
     
    publicBuilder setPriority(int pri)
    设置优先级,级别高的排在前面
     
    publicBuilder setDefaults(int defaults)
    设置上述铃声,振动,闪烁用|分隔,常量在Notification
     
    publicBuilder setOngoing(boolean ongoing)
    设置是否为一个正在进行中的通知,这一类型的通知将无法删除
     
    通知的提醒方式
    声音提醒
    默认声音
    notification.defaults|=Notification.DEFAULT_SOUND;
    自定义声音
    notification.sound=Uri.parse("file:///sdcard0/notification.ogg");
    震动提醒
    默认振动
    notification.defaults|=Notification.DEFAULT_VIBRATE;
    自定义振动
    long[] vibrate ={100,200,300,400};//震动效果,表示在100、200、300、400这些时间点交替启动和关闭震动
    notification.vibrate= vibrate;
    闪烁提醒
    默认闪烁
    notification.defaults|=Notification.DEFAULT_LIGHTS;
    自定义闪烁
    notification.ledARGB=0xff00ff00;// LED灯的颜色,绿灯
    notification.ledOnMS=300;// LED灯显示的毫秒数,300毫秒
    notification.ledOffMS=1000;// LED灯关闭的毫秒数,1000毫秒
    notification.flags|=Notification.FLAG_SHOW_LIGHTS;// 必须加上这个标志
    PendingIntent
    PendingIntent pendingIntent=PendingIntent.getActivity(MainActivity.this,(int)SystemClock.uptimeMillis(),newIntent(MainActivity.this,OpenActivity.class),PendingIntent.FLAG_UPDATE_CURRENT);
    flags有四种不同的值:
    FLAG_CANCEL_CURRENT:如果构建的PendingIntent已经存在,则取消前一个,重新构建一个。
    FLAG_NO_CREATE:如果前一个PendingIntent已经不存在了,将不再构建它。
    FLAG_ONE_SHOT:表明这里构建的PendingIntent只能使用一次。
    FLAG_UPDATE_CURRENT:如果构建的PendingIntent已经存在,那么系统将不会重复创建,只是把之前不同的传值替换掉。通常做法就是在构建PendingIntent的时候传入不一样的requestCode来更新PendingIntent
     
    最简单的通知
    将之前提到的那些基础点串起来,就可以发送一条一行文本的通知了

    ————————————————————————————————————————————————————————————–

    现在来进行实际操作

    Android通知有两种,默认通知与自定义通知。默认通知简单调用系统接口就能实现,如下:


    发送默认通知

    默认通知效果

    自定义通知就稍微麻烦一些,需要定义一个layout文件,使用RemoteViews加载它并设置一些点击事件,再设置到builder,如下:


    自定义通知代码

    自定义通知效果

    这个通知很简单,就是两行文本加上一个按钮,按钮具有单独的点击事件,点击后跳转到AnotherActivity。

    注意:smallIcon对于自定义通知和默认通知都是必须的,否则通知显示不出来。道理很简单,smallIcon需要在状态栏上显示,不设置怎么行。在5.0及以上,smallIcon必须符合Material Design风格,即白色内容,透明背景。不然系统会使用默认的图片替换。具体可参考Android通知栏微技巧,那些你所没关注过的小细节 标签: android通知通知栏微技巧。后面我会有一篇更详细的文章来介绍这个。contentIntent对于2.3及以下的系统是必须的,否则发送通知时会抛异常。道理也很简单,Android 2.3及以下系统不支持给自定义通知上的元素绑定单独的点击事件,因此必须设置整个通知的点击事件。

    为什么要进行样式适配?


    默认通知不存在样式适配的问题,因为默认通知的布局、颜色、背景什么的都是系统的,系统总会正确的显示默认通知。但自定义通知就不一样了,自定义通知的布局完全由我们自己掌控,我们可以为元素设置任何背景、颜色。那么,问题来了。Android通知栏的背景各种各样,不同的ROM有不同的背景,白色、黑色、透明等。不同的Android版本通知栏背景也不一样,一旦我们为自定义通知上的元素设置了特定背景或颜色,就肯定会带来兼容性问题(主要是文本啦)。这样的应用一大把,贴个图大家就明白了:


    未适配的自定义通知

    怎么适配?


    适配的方式大概有两种,一种简单粗暴:为自定义通知设置固定的背景(上图中的360卫士就这么干的),比如黑色。那么内容自然就是白色或近似白色。这样,在所有的手机上都能正常显示,不会出现在黑色背景通知栏上显示良好,到了白色背景通知栏上就几乎啥也看不见。使用这种方案的应用太多了。我个人很不推崇这种方式,这样会使得自定义通知在将近一半的手机上显示得很突兀,和系统的通知栏不够沉浸,影响整体美观。另一种方案就稍微合理一些:通过读取系统的通知栏样式文件,获取到title和content的颜色,进而将这个颜色设置到自定义通知上。读取通知栏样式文件本身有兼容性问题,不同Android版本的样式文件有变,具体可参考这篇博客通知栏设置系统字体颜色
    ,这种方式也不是在所有手机上生效,实际测试发现,还是有小部分机型没法读取或是读取到的是错误的。拿到title和content的颜色后,还可以通过算法(后面细说)判断这个颜色是近似白色还是近似黑色,进而能判断出通知栏的背景是近似黑色还是近似白色,这样就能根据不同的通知栏背景加载不同的自定义通知布局。进而做到良好的适配。

    更好的适配


    现在切入主题,谈谈如何来更好的适配自定义通知。有过锁屏开发经验的人应该知道,如果你的应用有读取系统通知栏的权限,那么每当应用程序发出一个通知,你的应用都会收到对应的notification对象,这个时候,我们一般会执行以下操作:


    获取并展示app通知

    调用addView之后,应用程序的通知就会显示在我们的应用里。显然,上面的代码并没有对apply返回的notificationItemLayout做任何其他操作,但确实这个View显示出来时就是样式良好的,可见,notificationItemLayout本身就是带有样式的,即便是默认通知。那么方案来了!我们先构造一个默认通知:


    获取通知栏title的颜色

    通知并不发送出去,只是用来获取通知栏title的颜色,如果你还想获取content的颜色,抱歉,不能通过查找android.R.id.text来获取,这个字段是访问不到的。可通过反射获取,更好的办法是先预先设置一个content,然后遍历viewGoup根据content内容找到对应的TextView再获取颜色。

    拿到颜色后,可根据算法判断这个颜色是近似白色还是近似黑色,我们使用黑色作为基准色,使用方差来计算这个颜色是否近似黑色:


    比较两个颜色是否近似

    baseColor传入Color.BLACK,color传入刚刚获取到的title的颜色,根据我实测,阈值为180.0较为合理。上述方法返回true,即表示title的颜色近似黑色,也就是说通知栏背景近似白色。

    额,经验丰富的同学应该已经洞察到第二段代码存在的兼容性问题了:根据android.R.id.title去找到title对应的TextView是不靠谱的,因为有些ROM厂商会把id改掉,导致找到的title为空。

    同时还有另外一个问题:使用上述方法,Activity不能继承自AppCompatActivity(实测5.0以下机型可以,5.0及以上机型不行),大致的原因是默认通知布局文件中的ImageView(largeIcon和smallIcon)被替换成了AppCompatImageView,而在5.0及以上系统中,AppCompatImageView的setBackgroundResource(int)未被标记为RemotableViewMethod,导致apply时抛异常。

    为了解决这两个问题,我们改进getNotificationColor方法:


    改进后的方法

    在getNotificationColorInternal中,设置一个默认的title文本,如果根据id找不到title,则遍历notificationRoot根据设置的title文本找到title:


    兼容厂商改id

    在getNotificationColorCompat中,我们先构造一个默认通知,获取到默认通知的布局文件id,并将布局加载到notificationRoot,此时,如果根据id找不到title,显然设置默认title的办法已经失效了。如何从notificationRoot中找到title是个问题。我的解决办法是:反正都已经拿到notificationRoot了,不如就遍历它,先找到其中的所有TextView,取字体最大的TextView作为title(这是合理的,因为默认通知中最多也就4个TextView,分别是title、content、info、when,title肯定是字体最大,最显眼的),并返回其颜色:


    兼容AppCompatActivity

    实际测试


    拿到了通知栏背景的颜色后,我们就可以加载不同样式的布局,达到适配的目的。代码如下:


    适配代码

    效果:


    Android 4.4黑色背景的通知栏





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值