先来一段代码
mNotificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE); Intent intent = new Intent(context, MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent pi = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); rv = new RemoteViews(context.getPackageName(), R.layout.down_notification); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context); mBuilder.setPriority(Notification.FLAG_HIGH_PRIORITY); Notification notification = mBuilder.build(); notification.icon = R.drawable.ic_launcher; notification.tickerText = "通知内容"; notification.contentIntent = pi; notification.contentView = rv; notification.flags |= Notification.FLAG_ONGOING_EVENT; mNotificationManager.notify(NOTIFICATION_ID, notification);咱们分段代码分析
mNotificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);获取noficationmanger,通知管理器,她可以显示通知或者取消显示。
Intent intent = new Intent(context, MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent pi = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);设置点击通知栏跳转的activity,特别注意的是
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);如果栈内已经存在该activity,则不需要再次重新创建该activity,并且清除该activity前面所有的activity显示到最上层。
通知的视图
rv = new RemoteViews(context.getPackageName(), R.layout.down_notification);所有的对视图内的控件的操作都可以 用 rv....来实现。
通知栏的优先级:有时候可以看到QQ音乐了,360安全管理了,为什么他们的通知都是显示到嘴上面呢?其实我们的也可以哦
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context); mBuilder.setPriority(Notification.FLAG_HIGH_PRIORITY);这里可以设置优先级,简单不
下面的都是一些基本的配置了
Notification notification = mBuilder.build(); notification.icon = R.drawable.ic_launcher; notification.tickerText = "通知内容"; notification.contentIntent = pi; notification.contentView = rv; notification.flags |= Notification.FLAG_ONGOING_EVENT;通知显示图标
notification.icon = R.drawable.ic_launcher;通知显示的内容
notification.tickerText = "通知内容";点击通知跳转的内容
notification.contentIntent = pi;通知的视图
notification.contentView = rv;使自己的Notification像Android QQ一样能出现在 “正在运行的”栏目下面
notification.flags |= Notification.FLAG_ONGOING_EVENT;设置
notification.flags为 Notification.FLAG_AUTO_CANCEL ,该标志表示当用户点击 Clear 之后,能够清除该通知。