关于Android(安卓)O不能正常推送通知问题
16lz
2021-01-26
在看第一行代码自学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
震动和图片什么的都正常,不知道为什么我的呼吸灯不亮。如果有可以亮的,麻烦告诉下解决办法。我实在是太菜了!!!
更多相关文章
- 《Android(安卓)开发艺术探索》笔记6--理解RemoteViews
- Android中的消息通知(NotificationManager和Notification)
- android service 通过broadcast通知Myreceiver 启动activity
- Badge分析&如何逼死处女座
- Android(安卓)为点击事件添加震动效果
- Android客户端消息推送原理简介
- BroadcastReceiver、EventBus的优缺点
- Android通知栏-Notification(通知消息)
- Android(安卓)推送