Android自定义Notification通知,效果图:
Activity中的代码:
//通过点击事件触发自定义的通知 @Override public void onClick(View v) { NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); SimpleDateFormat formatter = new SimpleDateFormat("HH:mm"); Date curDate = new Date(System.currentTimeMillis());//获取当前时间 String str = formatter.format(curDate); switch (v.getId()) { case R.id.start: Notification notification = new Notification(R.mipmap.ic_launcher,"title",System.currentTimeMillis()); // FLAG_AUTO_CANCEL 该通知能被状态栏的清除按钮给清除掉 // FLAG_NO_CLEAR 该通知不能被状态栏的清除按钮给清除掉 // FLAG_ONGOING_EVENT 通知放置在正在运行 notification.flags = Notification.FLAG_ONGOING_EVENT;// 点击通知之后自动消失 RemoteViews remoteView = new RemoteViews(this.getPackageName(), R.layout.layout_notification); remoteView.setImageViewResource(R.id.image, R.mipmap.ic_launcher_round); remoteView.setTextViewText(R.id.title, "标题:Notification "+str); remoteView.setTextViewText(R.id.content, "前面我们说过,NotificationManager是所有Notification的大管家,它的主要职责是加入/移除Notification。"); // remoteView.setTextViewText(R.id.nowTime,str ); notification.contentView = remoteView; // 3、为Notification的contentIntent字段定义一个Intent(注意,使用自定义View不需要setLatestEventInfo()方法) //这儿点击后简答启动Settings模块 PendingIntent contentIntent = PendingIntent.getActivity(MainActivity.this, 0, new Intent("android.settings.SETTINGS"), 0); notification.contentIntent = contentIntent; // 发送一个标识为100的通知 notificationManager.notify(100,notification); // 发送一个标识为zjh和100的通知 // notificationManager.notify("zjh",100,notification); break; case R.id.stop: //清除掉所有标识为100的通知 notificationManager.cancel(100); //清除掉所有的通知 // notificationManager.cancelAll(); //清除掉所有标识为zjh和100的通知 // notificationManager.cancel("zjh",100); break; default: break; } }
layou_noticfication的布局文件