使用Android Oreo在后台运行应用时,Firebase通知声音/振动

时间:2018-10-16 12:34:06

标签: android firebase firebase-cloud-messaging android-8.0-oreo

使用Android Oreo在后台运行应用程序时,我听不到声音或振动。在前景中使用应用程序时,声音和振动效果很好。

在使用早期版本的android且没有Nofication Channel的情况下,一切正常,但现在我找不到解决方法。

这是我的代码:

private void showNotification(String title, String body) {

    NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    String NOTIFICATION_CHANNEL_ID = "com.example.name.notification.test";

    Uri sound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getPackageName() + "/" + R.raw.my_sound);

    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "Notification", NotificationManager.IMPORTANCE_MAX);

        AudioAttributes audioAttributes = new AudioAttributes.Builder()
                .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                .setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
                .build();

        notificationChannel.setDescription("EDMT Channel");
        notificationChannel.enableLights(true);
        notificationChannel.setLightColor(Color.BLUE);
        notificationChannel.enableVibration(true);
        notificationChannel.setVibrationPattern(new long[]{0,1000,500,1000});           
        notificationChannel.setSound(sound, audioAttributes); // This is IMPORTANT            
        notificationManager.createNotificationChannel(notificationChannel);

    }

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder( this,NOTIFICATION_CHANNEL_ID);

    notificationBuilder.setAutoCancel(true)
            .setDefaults(Notification.DEFAULT_ALL)
            .setWhen(System.currentTimeMillis())
            .setSmallIcon(R.drawable.ic_notification)
            .setContentTitle(title)
            .setContentText(body)
            .setContentInfo("Info");

    notificationManager.notify(new Random().nextInt(),notificationBuilder.build());

}

1 个答案:

答案 0 :(得分:0)

我在文档中找到了这个。可能会对您有帮助:

  •   

    在Android 8.0(API级别26)及更高版本上,通知的重要性   由通知所针对的频道的重要性决定   发布到。用户可以更改通知渠道的重要性   在系统设置中(图12)。在Android 7.1(API级别25)和   下面,每个通知的重要性由   通知的优先级。

  •   

    Android O引入了通知渠道以提供统一的系统   帮助用户管理通知。以Android O为目标时,   必须实现一个或多个通知渠道才能显示   通知您的用户。如果您不定位Android O,则您的应用   在Android O上运行时,其行为与在Android 7.0上相同   设备。

  

1 。现在必须将各个通知放在特定的频道中。

     

2 。用户现在可以关闭每个频道的通知,而不必关闭       关闭来自应用程序的所有通知。

     

3 。具有有效通知的应用在顶部显示通知“徽章”       他们的应用图标在主屏幕/启动器屏幕上的位置。

     

4 。用户现在可以暂停抽屉中的通知。您可以设置       通知自动超时。

     

5 。一些与通知行为有关的API已从       通知到NotificationChannel。例如使用       NotificationChannel.setImportance()代替       适用于Android 8.0及更高版本的NotificationCompat.Builder.setPriority()。