Android(安卓)标题栏添加常驻图标 Notification
16lz
2021-01-26
最近开发需求:可穿戴设备将其电量传给手机,让其电量信息显示在andorid 手机标题栏上,并且不消失,也不要向qq似得提示消息。
查看资料发现除了root修改系统应用,只能通过通过Notification让其显示在标题栏上。
具体代码如下:
private void showBetteryNotification(int powerLevel){NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(android.content.Context.NOTIFICATION_SERVICE); String currentBettery=mContext.getResources().getString(R.string.current_power)+":"+powerLevel;Notification.Builder builder= new Notification.Builder(mContext);CharSequence contentTitle = mContext.getResources().getString(R.string.current_power);CharSequence contentText = currentBettery;builder.setContentTitle(contentTitle);builder.setContentText(currsntbettery);//设置通知消息左侧大图标。builder.setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(),R.drawable.notification));//设置标题栏上小图标if (powerLevel >= 95) builder.setSmallIcon(R.drawable.battery_100);else if (powerLevel >= 85) builder.setSmallIcon(R.drawable.battery_90);else if (powerLevel >= 75) builder.setSmallIcon(R.drawable.battery_80);else if (powerLevel >= 65) builder.setSmallIcon(R.drawable.battery_70);else if (powerLevel >= 55) builder.setSmallIcon(R.drawable.battery_60);else if (powerLevel >= 45) builder.setSmallIcon(R.drawable.battery_50);else if (powerLevel >= 35) builder.setSmallIcon(R.drawable.battery_40);else if (powerLevel >= 25) builder.setSmallIcon(R.drawable.battery_30);else if (powerLevel >= 15) builder.setSmallIcon(R.drawable.battery_20);else if (powerLevel >= 7) builder.setSmallIcon(R.drawable.battery_10);else builder.setSmallIcon(R.drawable.battery_5);// 设置通知的事件消息 点击通知消息跳转 Intent notificationIntent =new Intent();notificationIntent.setAction("cn.vn.fen.WelcomeActivity");PendingIntent contentIntent = PendingIntent.getActivity(mContext, 0, notificationIntent,0);builder.setContentIntent(contentIntent);Notification notification = builder.getNotification();//builder.build() API16后支持使用这个。notification.flags |= Notification.FLAG_SHOW_LIGHTS; notification.flags |= Notification.FLAG_ONGOING_EVENT; // 表明在点击了通知栏中的"清除通知"后,此通知不清除, 经常与FLAG_ONGOING_EVENT一起使用 notification.flags |= Notification.FLAG_NO_CLEAR; notification.defaults = Notification.DEFAULT_LIGHTS; notification.ledARGB = 0xff0000ff;notification.ledOnMS =5000; //5 s notificationManager.notify(100, notification); }
通过Notification flag属性设置Notification.FLAG_NO_CLEAR,点击 左右滑动该通知消息不回将此通知清除,标题栏上的图标也不会清除。但是有的手机经过深度定制,虽然设置了它但是还是会被清除(比如华为的)。
通过不断的调用上面的方法,可以实时更新电量到标题栏上了。
当不需要显示时可以调用notificationManager.cancel(100),将通知消息清除。
还有就是当应用彻底退出后台时,该应用到通知消息会被清除。
更多相关文章
- Android系统自带更新DownloadManager用法
- android 消息传递流程
- android 常用控件
- Notification学习
- Notification详解
- Android(安卓)发送和接收即时消息
- Android(安卓)屏蔽系统通知的几种方法
- Android(安卓)JB 4.2 中InputManager 分发键盘消息给应用程序的
- 开发者的惊喜福利,Swift将支持Android?