发送消息
//自定义显示的通知内容的布局
RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.custom_notification);
remoteViews.setImageViewResource(R.id.iv_image, R.mipmap.ic_launcher);
remoteViews.setTextViewText(R.id.tv_title, "自定义通知标题");
remoteViews.setTextViewText(R.id.tv_text, "自定义通知内容");
//点击通知栏时跳转的Activity页面
Intent intent = new Intent(MainActivity.this, HomeActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 0, intent, 0);
//从这开始
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this);
Notification notification = builder
.setContentTitle("这是通知标题")
.setContentText("这是通知的内容")
.setWhen(System.currentTimeMillis())//设置通知发布时间
//设置默认提示的声音,有四种设置,分别有下Notification.DEFAULT_SOUND、Notification.DEFAULT_LIGHTS、Notification.DEFAULT_ALL、Notification.DEFAULT_VIBRATE
.setDefaults(Notification.DEFAULT_SOUND)
.setSmallIcon(R.mipmap.ic_launcher)//通知栏提示的小图片
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))//打开通知栏提示的大图片
.setColor(Color.parseColor("#EAA935"))//有时通知栏大图片的右下角会有一个小图,给他设置颜色
.setAutoCancel(true)//设置打开通知时,该通知取消
.setTicker("有新消息")//设置通知提示信息
.setContentIntent(pendingIntent)//开始跳转
.setContent(remoteViews)//加添自定义通知的布局内容
.build();
manager.notify(1, notification);//第一个参数为消息标识,第二个为消息对象
取消消息:
manager.cancel(1);//参数为消息标识