1.步骤
①获取通知管理器getSystemService
②兼容O版以上系统
③获取通知对象(构建者模式):必要属性有三项
④用通知管理器发送通知
⑤延时意图:intent、pendingIntent、setContentIntent
⑥通知提示:声音、震动、呼吸灯、全部
private void send() {
String channdleId="1";
// String channleName="sb";
//创建通知管理器
NotificationManager systemService = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// 设置通知的显示参数
// if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
// NotificationChannel channel = new NotificationChannel(channleId, channleName, NotificationManager.IMPORTANCE_DEFAULT);
// channel.enableLights(true);//开启指示灯,如果设备有的话
// channel.setLightColor(Color.RED);//设置指示灯颜色
// channel.setShowBadge(true);//检测是否显示角标
// service.createNotificationChannel(channel);
// }
//获取activity延时意图
Intent intent = new Intent(this, PendingIntentActivity.class);
PendingIntent activity = PendingIntent.getActivity(this, 100, intent, PendingIntent.FLAG_CANCEL_CURRENT);
//获取通知对象
Notification build = new NotificationCompat.Builder(this,channdleId)
.setSmallIcon(R.mipmap.ic_launcher)//图标
.setContentTitle("通知")//标题
.setContentText("内容")//内容
.setContentIntent(activity)//设置延时意图
.build();
//发送通知
systemService.notify(100,build);
}
2.PendingIntent (延时意图)
PendingIntent 是一种特殊的 Intent ,字面意思可以解释为延迟的 Intent ,主要的区别在于Intent的执行立刻的,而pendingIntent的执行不是立刻的,用于在某个事件结束后执行特定的 Action 。从上面带 Action 的通知也能验证这一点,当用户点击通知时,才会执行。如果创建该PendingIntent对象的进程被杀死了,这个PendingItent对象在其他进程中还是可用的。
PendingIntent 可以通过以下三种方式获取:
getActivity(Context, int, Intent, int)------->跳转到一个activity组件
getBroadcast(Context, int, Intent, int)------>打开一个广播组件
getService(Context, int, Intent, int)-------->打开一个服务组件
Intent和PendingIntent的区别
①Intent是立即使用的,而PendingIntent可以等到事件发生后触发,PendingIntent可以cancel
②Intent在程序结束后即终止,而PendingIntent在程序结束后依然有效
③PendingIntent自带Context,而Intent需要在某个Context内运行
④Intent在原task中运行,PendingIntent在新的task中运行
网友评论