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

这篇文章主要给大家介绍了关于Android如何给通知channel静音的相关资料,文中通过实例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

前言

目前各个市场都要求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);

总结

到此这篇关于Android给通知channel静音的文章就介绍到这了,更多相关Android给通知channel静音内容请搜索编程学习网以前的文章希望大家以后多多支持编程学习网!

本文标题为:Android给通知channel静音的方法实例

基础教程推荐