普通Notification
tv_normal = findViewById(R.id.tv_normal);
tv_normal.setOnClickListener(this);
notificationManager =(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
首先在onCreate中为TextView tv_normal绑定点击事件,然后通过getSystemService
(NOTIFICATION_SERVICE)得到notificationMangeer这个系统服务。
public void onClick(View view) {
switch (view.getId()){
case R.id.tv_normal:
sendNomalNotification();
break;
default:
break;
}
}
在View.onCickListener重写的onClick方法中启动Notification。
private void sendNomalNotification() {
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.setAutoCancel(true);
builder.setContentTitle("普通通知");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
PendingIntent.notify(0,builder.build());
}
}
首先新建一个Notification.Builder和PendingIntent,表示将网页显示到当前活动中。builder可以设置一系列参数,比如传入PendingIntent,设置小图标,大图标,自动消失等,然后使用PendingIntent的notify方法显示通知。
折叠式通知
折叠式通知需要两个View,一个是普通的View,一个是展开状态下的view,两者不在一个进程中,需要使用RemoteView。其他的配置和普通Notification相同。
RemoteViews remoteViews = new RemoteViews(getPackageName(),R.layout.view_fold);
Notification notification = builder.build();
notification.bigContentView = remoteViews;
notificationManager.notify(1,notification);
Notification的bigContentView就是展开后的界面。
悬挂式通知
不需要下拉通知栏直接显示
Intent hangIntent = new Intent();
hangIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
hangIntent.setClass(this,MyNotificationActivity.class);
PendingIntent hangPi = PendingIntent.getActivity(this,0,
hangIntent,PendingIntent.FLAG_CANCEL_CURRENT);
builder.setFullScreenIntent(hangPi,true);
notificationManager.notify(2,builder.build());