Android在appcompat-v7库中提供了一个NotificationCompat类来处理新老版本的兼容问题,我们在编写通知功能时都使用NotificationCompat这个类来实现,appcompat-v7库就会自动帮我们做好所有系统版本的兼容性处理了。一段基本的触发通知代码如下所示:
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
Notification notification = builder
.setContentTitle(“通知标题”)
.setContentText(“通知内容”)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(
getResources(), R.mipmap.ic_launcher))
.build();
manager.notify(1, notification);
- 先来介绍一下setContentTitle(),setContentText()的设置:
在这里我是从本地的用户列表数据库中查找得到的setContentTitle为用户名称,setContentText为最新的消息内容,具体怎么做是操作数据库,这里就不说了。
- 在看看setSmallIcon为项目logo:
Android从5.0系统开始,对于通知栏图标的设计进行了修改。现在Google要求,所有应用程序的通知栏图标,应该只使用alpha图层来进行绘制,而不应该包括RGB图层。
说的好像很玄乎,什么叫作只使用alpha图层来进行绘制呢?其实通俗点来讲,就是让我们的通知栏图标不要带颜色(基本上一个白色就好了)就可以了。
不带颜色图标由UI设计师来设置(我这里先谁便用了一个)
- setLargeIcon的设置这是重点,这个方法是用来显示图片的,我的源码如下:
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(appContext)
.setSmallIcon(appContext.getApplicationInfo().icon)
.setSmallIcon(R.mipmap.icon_app_small)
.setWhen(System.currentTimeMillis())
.setColor(Color.parseColor("#4e60c4"))
.setAutoCancel(true);
if (friendListBean != null && !StringUtil.isBland(friendListBean.getHeadUrl())) {
mBuilder.setLargeIcon(GetImageInputStream(friendListBean.getHeadUrl()) == null ? BitmapFactory.decodeResource(
UIUtils.getContext().getResources(), R.mipmap.icon_logo) : GetImageInputStream(friendListBean.getHeadUrl()));
} else {
mBuilder.setLargeIcon(BitmapFactory.decodeResource(
UIUtils.getContext().getResources(), R.mipmap.icon_logo));
}
Intent msgIntent = appContext.getPackageManager().getLaunchIntentForPackage(packageName);
if (notificationInfoProvider != null) {
msgIntent = notificationInfoProvider.getLaunchIntent(message);
}
PendingIntent pendingIntent = PendingIntent.getActivity(appContext, notifyID, msgIntent, PendingIntent.FLAG_UPDATE_CURRENT);
/**
-
获取网络图片
-
@param imageurl 图片网络地址
-
@return Bitmap 返回位图
*/
public Bitmap GetImageInputStream(String imageurl) {
URL url;
HttpURLConnection connection = null;
Bitmap bitmap = null;
try {
url = new URL(imageurl);
connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(6000); //超时设置
connection.setDoInput(true);
connec
《Android学习笔记总结+最新移动架构视频+大厂安卓面试真题+项目实战源码讲义》
【docs.qq.com/doc/DSkNLaERkbnFoS0ZF】 完整内容开源分享
tion.setUseCaches(false); //设置不使用缓存
InputStream inputStream = connection.getInputStream();
bitmap = BitmapFactory.decodeStream(inputStream);