首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

为什么我得不到通知声音(NotificationCompat.Builder) SDK26+

在Android开发中,通知声音是通过NotificationCompat.Builder类来实现的。在SDK26及以上的版本中,通知声音的获取方式有所改变。

在SDK26之前,我们可以通过设置NotificationCompat.Builder的setSound()方法来设置通知的声音。该方法接受一个Uri参数,可以是本地文件的Uri或者是资源文件的Uri。例如:

代码语言:txt
复制
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
        .setSound(Uri.parse("android.resource://" + context.getPackageName() + "/" + R.raw.notification_sound))
        .setContentTitle("Notification Title")
        .setContentText("Notification Content");

在SDK26及以上的版本中,通知声音的获取方式有所改变。现在,我们需要使用NotificationChannel来设置通知的声音。首先,我们需要创建一个NotificationChannel对象,并设置其重要性级别和声音。然后,将该NotificationChannel对象传递给NotificationCompat.Builder的setChannelId()方法。例如:

代码语言:txt
复制
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    String channelId = "channel_id";
    CharSequence channelName = "Channel Name";
    int importance = NotificationManager.IMPORTANCE_DEFAULT;
    AudioAttributes audioAttributes = new AudioAttributes.Builder()
            .setUsage(AudioAttributes.USAGE_NOTIFICATION)
            .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
            .build();
    NotificationChannel channel = new NotificationChannel(channelId, channelName, importance);
    channel.setSound(Uri.parse("android.resource://" + context.getPackageName() + "/" + R.raw.notification_sound), audioAttributes);
    
    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.createNotificationChannel(channel);
    
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context, channelId)
            .setContentTitle("Notification Title")
            .setContentText("Notification Content");
}

在上述代码中,我们创建了一个名为"channel_id"的NotificationChannel,并设置了其重要性级别为默认。然后,我们使用setSound()方法设置了通知的声音,并使用setContentType()方法设置了声音的内容类型为语音。最后,我们将该NotificationChannel对象传递给NotificationCompat.Builder的setChannelId()方法。

这样,我们就可以在SDK26及以上的版本中设置通知的声音了。需要注意的是,为了兼容SDK26以下的版本,我们可以在创建NotificationChannel之前添加以下代码:

代码语言:txt
复制
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    // 创建NotificationChannel
}
else {
    // 不需要创建NotificationChannel
}

推荐的腾讯云相关产品和产品介绍链接地址:

  • 云服务器(CVM):https://cloud.tencent.com/product/cvm
  • 云数据库 MySQL 版:https://cloud.tencent.com/product/cdb_mysql
  • 云原生容器服务(TKE):https://cloud.tencent.com/product/tke
  • 人工智能开发平台(AI Lab):https://cloud.tencent.com/product/ailab
  • 物联网开发平台(IoT Explorer):https://cloud.tencent.com/product/iothub
  • 移动推送服务(信鸽):https://cloud.tencent.com/product/tpns
  • 云存储(COS):https://cloud.tencent.com/product/cos
  • 腾讯区块链服务(TBaaS):https://cloud.tencent.com/product/tbaas
  • 腾讯云游戏引擎(GSE):https://cloud.tencent.com/product/gse
  • 腾讯云直播(CSS):https://cloud.tencent.com/product/css
页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的沙龙

领券