关于Android O不能正常推送通知问题

本文介绍了在Android O系统上实现通知推送的具体方法,包括如何创建NotificationChannel,并设置了灯光、震动等特性。同时分享了解决通知无法显示的问题及具体代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

        在看第一行代码自学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

震动和图片什么的都正常,不知道为什么我的呼吸灯不亮。如果有可以亮的,麻烦告诉下解决办法。我实在是太菜了!!!


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值