Notification 的创建主要涉及到 Notification.Builder 、 Notification 、 NotificationManager 。
- Notification.Builer : 使用建造者模式构建 Notification 对象。由于 Notification.Builder 仅支持 Android 4.1及之后的版本,为了解决兼容性问题, Google 在 Android Support v4 中加入了 NotificationCompat.Builder 类。对于某些在 Android 4.1 之后才特性,即使 NotificationCompat.Builder 支持该方法,在之前的版本中也不能运行。点我 查看更多关于 Notification 兼容性问题处理。文中使用的都是 NotificationCompat。
- Notification : 通知对应类,保存通知相关的数据。NotificationManager 向系统发送通知时会用到。
- NotificationManager : NotificationManager 是通知管理类,它是一个系统服务。调用 NotificationManager 的 notify() 方法可以向系统发送通知。
1.获取 NotificationManager 对象:
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
2.Builder
a.普通通知
Notification.Builder builder = new Notification.Builder(this); Intent mIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://blog.csdn.net/itachi85/")); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, mIntent, 0); builder.setContentIntent(pendingIntent); builder.setSmallIcon(R.drawable.lanucher); builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.lanucher)); builder.setAutoCancel(true); builder.setContentTitle("普通通知"); selectNotofovatiomLevel(builder); notificationManager.notify(0, builder.build());
b.折叠式通知
Notification.Builder builder = new Notification.Builder(this); Intent mIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://blog.csdn.net/itachi85/")); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, mIntent, 0); builder.setContentIntent(pendingIntent); builder.setSmallIcon(R.drawable.foldleft); builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.lanucher)); builder.setAutoCancel(true); builder.setContentTitle("折叠式通知"); selectNotofovatiomLevel(builder); //用RemoteViews来创建自定义Notification视图 RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.view_fold); Notification notification = builder.build(); //指定展开时的视图 notification.bigContentView = remoteViews; notificationManager.notify(1, notification);
c.悬挂式通知
Notification.Builder builder = new Notification.Builder(this); Intent mIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://blog.csdn.net/itachi85/")); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, mIntent, 0); builder.setContentIntent(pendingIntent); builder.setSmallIcon(R.drawable.foldleft); builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.lanucher)); builder.setAutoCancel(true); builder.setContentTitle("悬挂式通知"); selectNotofovatiomLevel(builder); //设置点击跳转 Intent hangIntent = new Intent(); hangIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); hangIntent.setClass(this, MyNotificationActivity.class); //如果描述的PendingIntent已经存在,则在产生新的Intent之前会先取消掉当前的 PendingIntent hangPendingIntent = PendingIntent.getActivity(this, 0, hangIntent, PendingIntent.FLAG_CANCEL_CURRENT); builder.setFullScreenIntent(hangPendingIntent, true); notificationManager.notify(2, builder.build());
3.效果