原因:
在Android.o版本以后,已经不再支持这个实例化通知的方法了,而是多加了一个channelid参数:
Notification notification = new NotificationCompat.Builder(this,"one");
那么这个参数如何获取呢?
调用如下方法,参数分别为chanelid, channelname, 以及通知优先级。
createNotificationChanneler("one","notiChannelName",3);
//建立通知部分格式 NotificationChannel, 参数Channelid, Channel名, 优先级
public void createNotificationChanneler(String c_channelid,String c_channelname,int c_importance){
//检测 Channel是否已经被创建了,避免重复创建
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//检测Android版本
if (getNotificationManager().getNotificationChannel(c_channelid)!=null){
return; }//要是没被创建那么
NotificationChannel notificationChannel = new NotificationChannel(c_channelid,c_channelname,c_importance);
notificationChannel.enableLights(true);//开启提示灯
notificationChannel.enableVibration(true);//开启震动
notificationChannel.setSound(Uri.fromFile(new File("/system/media/audio/ringtones/Luna.ogg")),null);
notificationChannel.setBypassDnd(true);//可绕过免打扰模式
notificationChannel.setImportance(c_importance);//设置优先级
notificationChannel.setLightColor(Color.RED);//设置提示灯颜色
notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);//设置锁屏界面图标可见
notificationChannel.setShowBadge(true);//有图标
notificationChannel.setVibrationPattern(new long[]{
0,1000,1000,1000});
getNotificationManager().createNotificationChannel(notificationChannel);
}else {
return;
}
}
//获取通知管理、
private NotificationManager getNotificationManager(){
return (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
}
在创建通知前调用了createNotificationChanneler(,,)
然后就可以创建通知了
Intent intent = new Intent(this, ServerActivity.class);
PendingIntent pi = PendingIntent.getActivity(this,0, intent,0);
//由于Android7.0以后,通知的builder创建时,要多加一个参数,channelid,String类型
//以下函数可以获得这个channelid,需要三个参数,id,name,和优先级。
createNotificationChanneler("one","notiChannelName",3);
Notification notification = new NotificationCompat.Builder(this,"one")
.setContentTitle("通知标题")
.setContentText("通知内容,通知内容")
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher_round))
.setContentIntent(pi)
.build();
getNotificationManager.notify(1,notification);
关于优先级参数:
public static final int IMPORTANCE_DEFAULT = 3;
public static final int IMPORTANCE_HIGH = 4;
public static final int IMPORTANCE_LOW = 2;
public static final int IMPORTANCE_MAX = 5;
public static final int IMPORTANCE_MIN = 1;
public static final int IMPORTANCE_NONE = 0;
public static final int IMPORTANCE_UNSPECIFIED = -1000;