android 8.0 新特性:通知渠道

  由于Google的限制,要求在2018年10月之前 targetSdkVersion 必须在26以上,更改过之后发现在androd 8手机上不再推送通知,查看android 8.0官方文档发现,添加了通知渠道新特性,并要求targetSdkVersion 26以上的android 8手机必须实现通知渠道

  通知渠道可以用户自定义,并在用户手机系统设置里面修改,通知渠道的引入可以让用户对通知的优先级有了更好的体验,开发者定义两个渠道  product_01, product_02,

   其中product_01 重要性为高,每次推送通知发出声音

   product_02 重要性为紧急,每次推送通知发出声音和弹出窗口

   假设一个场景:针对微信用户,好友消息采用product_01通知渠道,群消息采用product_02通知渠道,这样一来,如果好友发来消息,就会发出声音,但不弹出窗口;如果是群消息,不但发出消息还会弹出窗口;然后过一段时间你觉得好友消息比较重要,群消息相对不太重要,想改一下通知的优先级,于是,在系统设置里面找到通知,把微信的product_01改为重要性紧急,把product_02改为重要性高,如此操作以后,如果好友发来消息,不但发出声音而且弹出窗口;如果是群消息,只能发出声音但没有弹窗

具体实现

    private void sendNotification() {

        NotificationCompat.Builder builder =
                new NotificationCompat.Builder(this, "id_product_01")
                        .setContentText("Hello World")
                        .setSmallIcon(R.drawable.ic_launcher_foreground)
                        .setContentTitle("id")
                        .setChannelId("id_product_01");

        //添加返回栈,使按返回键后,不会退出,而是跳转到主界面
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(NotificationJumpActivity.class);
        Intent intentActivity = new Intent(this, NotificationJumpActivity.class);
        stackBuilder.addNextIntent(intentActivity);
        PendingIntent pendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(pendingIntent);

        NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            String id = "id_product_01";
            CharSequence name = "Product_01";
            String description = "Notifications regarding our products";
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel mChannel = new NotificationChannel(id, name, importance);
            mChannel.setDescription(description);
            mChannel.enableLights(true);
            mChannel.setLightColor(Color.RED);
            mChannel.enableVibration(true);
            notificationManager.createNotificationChannel(mChannel);
        }
        notificationManager.notify(1, builder.build());
        
    }

注意,channelId为唯一标识符,和渠道是一对一的关系,一旦创建过 channelId为 id_product_01 的渠道就不会再进行创建

删除渠道通过 

            notificationManager.deleteNotificationChannel("id_product_01"); 其中参数为 channelId


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值