学无先后,达者为师

网站首页 编程语言 正文

Android给通知channel静音的方法实例_Android

作者:BennuCTec   更新时间: 2022-04-16 编程语言

前言

目前各个市场都要求targetsdkversion要不低于26,也就是android 8.0。 相应的影响很多功能,比如通知。

当targetsdkversion >= 26,需要为通知添加channel,如

manager = (NotificationManager) BaseApp.getAppContext()
        .getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    NotificationChannel channel = new NotificationChannel("update", "update", NotificationManager.IMPORTANCE_DEFAULT);
    manager.createNotificationChannel(channel);
}
builder = new NotificationCompat.Builder(BaseApp.getAppContext(), "update");

首先要新建一个NotificationChannel,并调用NotificationManager的createNotificationChannel启用该通道。

然后在创建buidler的时候设置同样的channelid即可。

静音

那么如果想让通知静音怎么处理?

  • 可以在channel上设置,setSound(null, null)。注意如果已经安装且这个channel已经存在,再覆盖安装不能生效,需要卸载重装。
  • 也可以对builder进行设置,setOnlyAlertOnce(true)。注意这个并不是完全静音,而是让这个通知只响一次,比如显示下载进度时,就不会一直响。
manager = (NotificationManager) BaseApp.getAppContext()
        .getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    NotificationChannel channel = new NotificationChannel("update", "update", NotificationManager.IMPORTANCE_DEFAULT);
    channel.setSound(null, null);
    manager.createNotificationChannel(channel);
}
builder = new NotificationCompat.Builder(BaseApp.getAppContext(), "update");
...
builder.setOnlyAlertOnce(true);

总结

原文链接:https://juejin.cn/post/7062616850005229582

栏目分类
最近更新