Android 通知栏弹出通知 (兼容高版本Android)

简单过程

有一点相对可能比较重要的 高版本的Android的通知,必须要NotificationChannelId

低版本

NotificationCompat.Builder builder;
NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
...
int notificationId = new Random().nextInt(); //通知栏id    
builder = new NotificationCompat.Builder(context);
builder.setContentTitle(title)                         
       .setWhen(System.currentTimeMillis()) //设置通知时间戳
       .setSmallIcon(R.mipmap.app_icon) 
       .setContentText(text) 
       .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)  //设置将从系统默认值继承哪些通知属性 基本就是用来设置是否通知音效或者震动
       .setAutoCancel(true)
       .setContentIntent(PendingIntent.getActivity(context, 0, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT))   //点击通知后的跳转   
       .setTicker(text) //收到通知后从顶部弹出精简版通知
       .setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400}) //自定义震动的频率
       .setPriority(Notification.PRIORITY_HIGH); //设置通知的优先等级
manager.notify(notificationId, builder.build());

高版本

NotificationCompat.Builder builder;
NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
...
int notificationId = new Random().nextInt(); //通知栏id     
String channelId = String.valueOf(new Random().nextInt()); //自己生成的用于通知栏的channelId,高版本必备
NotificationChannel mChannel = new NotificationChannel(channelId, "name", NotificationManager.IMPORTANCE_HIGH);  
mChannel.enableVibration(true);
mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
manager.createNotificationChannel(mChannel);
builder = new NotificationCompat.Builder(context, channelId);
builder.setContentTitle(title)                         
       .setWhen(System.currentTimeMillis()) //设置通知时间戳
       .setSmallIcon(R.mipmap.app_icon) 
       .setContentText(text) 
       .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)  //设置将从系统默认值继承哪些通知属性 基本就是用来设置是否通知音效或者震动
       .setAutoCancel(true)
       .setContentIntent(PendingIntent.getActivity(context, 0, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT))   //点击通知后的跳转   
       .setTicker(text) //收到通知后从顶部弹出精简版通知
       .setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400}) //自定义震动的频率
manager.notify(notificationId, builder.build());    

不管高低版本,如果要覆盖类似极光推送的通知,则需要将上面的notificationId替换成极光推送生成,否则会出现两条通知

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容