public void Click(View view) {
switch (view.getId()) {
case R.id.text1://只显示一条通知
count++;
notification = new Notification.Builder(this).
setContentTitle("通知").
setContentText("点我。。。").
setTicker("新消息").//第一次提示消息的时候显示在通知栏上
setSmallIcon(R.mipmap.ic_launcher).
setAutoCancel(true).//点击后自动消失
setNumber(count).
build();
//通知消息与intent关联
intent = new Intent(MainActivity.this,MainActivity.class);
intent.putExtra(DATA,"text1,只显示单条消息+"+count);
PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this,10,intent,PendingIntent.FLAG_CANCEL_CURRENT);
//设置通知意图
notification.contentIntent = pendingIntent;
notificationManager.notify(0,notification);
break;
case R.id.text2://显示多条通知,都跳转同一个活动
count++;
notification = new Notification.Builder(this).
setContentTitle("通知").
setContentText("点我。。。").
setTicker("新消息").//第一次提示消息的时候显示在通知栏上
setSmallIcon(R.mipmap.ic_launcher).
setAutoCancel(true).//点击后自动消失
setNumber(count).
build();
//通知消息与intent关联
intent = new Intent(MainActivity.this,MainActivity.class);
intent.putExtra(DATA,"text1,只显示单条消息+"+count);
PendingIntent p = PendingIntent.getActivity(MainActivity.this,10,intent,PendingIntent.FLAG_CANCEL_CURRENT);
//设置通知意图
notification.contentIntent = p;
notificationManager.notify(count,notification);//不同的id会显示不同的通知
break;
case R.id.text4://显示自定义通知
RemoteViews remoteViews = new RemoteViews(MainActivity.this.getPackageName(),R.layout.notifity_view);
remoteViews.setImageViewResource(R.id.app_iv,R.mipmap.ic_launcher);
intent = new Intent(MainActivity.this,MainActivity.class);
intent.putExtra(DATA,"text4,自定义通知!");
//包装意图
PendingIntent i = PendingIntent.getActivity(MainActivity.this,100,intent,PendingIntent.FLAG_CANCEL_CURRENT);
notification = new Notification.Builder(MainActivity.this).setSmallIcon(R.mipmap.ic_launcher).setContentTitle("通知")
.setAutoCancel(true).setTicker("自定义通知").setContentIntent(i).build();
notification.bigContentView = remoteViews;
notificationManager.notify(0,notification);
break;
}
}
实现通知的一般步骤:
1、创建通知管理器
2、构建通知
3、包装意图
4、调用notify方法发送通知