在日常工作中,经常会需要使用到自定义布局的Notification来执行一些操作,这里就来总结一下基本的使用与一些有可能遇到的坑吧。
大家都知道 Notification 的自定义布局是通过 RemoteViews 来实现的,其实挺简单的,直接来看代码吧:
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setSmallIcon(R.mipmap.ic_icon);//使用RemoteViews时,设置的是状态栏中的小图标,必须要设置
builder.setAutoCancel(true);//设置是否点击通知后会自动消失
Notification notification = builder.build();
//通过xml创建RemoteViews,并且动态改变布局中的内容
RemoteViews views = new RemoteViews(getPackageName(), R.layout.notification);
views.setImageViewResource(R.id.iv_icon, R.mipmap.ic_icon);
views.setImageViewResource(R.id.iv_banner, R.mipmap.ic_banner);
views.setTextViewText(R.id.tv_title, "今日头条新闻标题");
views.setTextViewText(R.id.tv_content, "今日头条新闻内容摘要");
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
String time = sdf.format(date);
views.setTextViewText(R.id.tv_time, time);
//这里需要注意,如果不设置 notification.bigContentView ,则由于通知的高度是固定的,如果remoteview的布局超过了其通知的高度,
//就会有一部分显示不出来了
notification.bigContentView = views;
notification.contentView = views;
//给整个通知设置一个拉起今日头条首页的PendingIntent
Intent intentNotification = new Intent();
intentNotification.setData(Uri.parse("snssdk143://home/news?growth_from=click_schema_aguya7"));
intentNotification.setPackage("com.ss.android.article.news");
intentNotification.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pi = PendingIntent.getActivity(context, 123, intentNotification, PendingIntent.FLAG_CANCEL_CURRENT);
notification.contentIntent = pi;
//单独给RemoteView中的控件设置PengdingIntent
// Intent intentNotification2 = new Intent();
// intentNotification2.setComponent(new ComponentName("com.netease.newsreader.activity","com.netease.nr.biz.ad.AdActivity"));
// intentNotification.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// PendingIntent pi2 = PendingIntent.getActivity(context, 123, intentNotification2, PendingIntent.FLAG_CANCEL_CURRENT);
// views.setOnClickPendingIntent(R.id.iv_banner,pi2);
manager.notify(9999, notification);
可以看到和发送普通的通知其实没什么差别:
- 创建Builder对象,设置一些属性,build出notification;
- 通过布局文件创建出 RemoteViews,根据需求设置其内容;
- 将notification 的view指向创建出的 RemoteViews,为其或其中的某个控制指定相应的PengdingIntent;
- 通过 NotificationManager.notify() 发送通知。
RemoteViews 的布局xml文件很简单,这里就不贴出来了,需要注意到的一些点代码中也加了注释,来看一下展示效果吧:
这时点击通知,就会跳转到PendingIntent中所设置的今日头条相关页面中了。
很简单的一个使用RemoteViews 创建自定义布局的Notification 的Demo,当然,Notification 中还有很多个性化设置这里就不一一介绍了,大家看一下官网文档描述的很详细哦~