一.普通通知
二.自定义通知
进度条通知
1.普通通知并跳转页面
//创建构造者
Notification.Builder builder = new Notification.Builder(getActivity());
//注意:必须为通知设置一个任意图片
builder.setSmallIcon(R.mipmap.ic_launcher);
//为通知设置标题
builder.setContentTitle("通知");
//获取通知管理者 发送通知和取消通知
NotificationManager manager = (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
//设置跳转页面
Intent intent = new Intent(getActivity(),Fragment3.class);
//将intent转换为pendingintent 参数一:上下文 参数二:请求码 参数三:要转换的intent
PendingIntent pendingIntent = PendingIntent.getActivity(getActivity(), 100, intent, PendingIntent.FLAG_UPDATE_CURRENT);
//设置跳转
builder.setContentIntent(pendingIntent);
//管理者发送通知
manager.notify(1,builder.build());
2.自定义通知 可以为通知设置各种布局及功能
//创建通知管理者
NotificationManager manager = (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
//设置构造者
Notification.Builder builder = new Notification.Builder(getActivity());
//设置一个图片
builder.setSmallIcon(R.mipmap.ic_launcher);
//给通着设置视图 参数一:你的包名 参数二:布局
RemoteViews remoteViews = new RemoteViews(getActivity().getPackageName(),R.layout.notifiaction);
//给通知设置功能
Intent intent = new Intent();
//发送一个广播 在广播中完成要实现的功能
intent.setAction("com.day18.icon");
//将intent转换为pendingintent并获取广播
PendingIntent broadcast = PendingIntent.getBroadcast(getActivity(), 101, intent, PendingIntent.FLAG_UPDATE_CURRENT);
//给组件设置点击事件
remoteViews.setOnClickPendingIntent(R.id.image,broadcast);
//动态设置一个图片
remoteViews.setImageViewResource(R.id.image,R.mipmap.a3);
//给构造者设置remoteview
builder.setContent(remoteViews);
//刷新
Notification build = builder.build();
//发送通知
manager.notify(2,build);
3.进度条通知
//创建构造者
final Notification.Builder builder = new Notification.Builder(getActivity());
//创建通知管理者
final NotificationManager manager = (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
builder.setSmallIcon(R.mipmap.ic_launcher);
final Timer timer = new Timer();
timer.schedule(new TimerTask() {
int progress = 0;
@Override
public void run() {
builder.setContentText("正在下载,当前进度"+progress);
builder.setProgress(100,progress,false);
progress+=10;
manager.notify(3,builder.build());
if(progress >= 100){
builder.setContentText("正在安装");
//参数一 最大值 参数二 进度 参数三 是否为迷糊进度
builder.setProgress(0,0,true);
manager.notify(3,builder.build());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
manager.cancel(3);
timer.cancel();
}
}
},0,1000);