在看第一行代码自学Android时(虽然三天打鱼两天晒网,进度慢的吓人)看到NotificationCompat.Builder()方法被划了横线,刚开始时看了一下Android Studio给的警告,没有找到替代的方法,但是可以正常推送,就没有在意。后来因为手机问题,换了小米6,刚好升级到8.0,发现无法推送通知。百度后发现,Android O做很多修改,如悬浮窗、通知、广播、WiFi、蓝牙等。Android O推送通知需要设置Notification Channel。代码如下:
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
String id = "my_channel_01";
NotificationChannel mChannel = null;//创建Notification Channel对象
//如果版本号为8.0以上,定义Notification Channel
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
mChannel = new NotificationChannel(id,"my_channel", NotificationManager.IMPORTANCE_DEFAULT);//设置唯一的渠道通知Id
mChannel.enableLights(true);//开启灯光
mChannel.setLightColor(Color.RED);
mChannel.enableVibration(true);//开启震动
mChannel.setVibrationPattern(new long[]{0,1000,0,1000});//8.0以下版本的效果一样,都是震动
manager.createNotificationChannel(mChannel);//在NotificationManager中注册渠道通知对象
}
//定义通知,都可适配
NotificationCompat.Builder notification=new NotificationCompat.Builder(this,"1");
notification.setContentTitle("你有一条新的联系人信息")
.setContentText("快来更新联系人信息!!!!!!!")
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setStyle(new NotificationCompat.BigPictureStyle().bigPicture(BitmapFactory.decodeResource(getResources(),R.drawable.notification1)))
.setSound(Uri.fromFile(new File("/system/media/audio/ringtones/Luna.ogg")))
//.setVibrate(new long[]{0,1000,0,1000})
//.setLights(Color.RED,1000,1000)//震动和灯光一样都需要Notification Channel开启灯光和震动,才能有效果
.setPriority(NotificationCompat.PRIORITY_MAX)//悬浮通知
.setContentIntent(pi)
.setChannelId(id)//设置通知Id
.setAutoCancel(true);
manager.notify(1,notification.build());
百度时看的如下链接:https://www.cnblogs.com/qyun/p/6715195.html
震动和图片什么的都正常,不知道为什么我的呼吸灯不亮。如果有可以亮的,麻烦告诉下解决办法。我实在是太菜了!!!