振动不适用于自定义声音的通知

问题描述

以下方法显示带有自定义声音和频道的通知。问题是振动不起作用。我曾尝试研究并尝试过,但没有成功。

private void showNotification(){
        Intent intent = new Intent(this,MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,intent,PendingIntent.FLAG_ONE_SHOT);

        Uri soundUri = Uri.parse("android.resource://" + getApplicationContext().getPackageName() + "/" + R.raw.messenger);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this,ChannelId)
                .setSmallIcon(R.drawable.ic_stat_facebookmessengernotificationicon)
                .setContentTitle("John Doe")
                .setContentText("hey,What's Up!")
                .setAutoCancel(true)
                .setSound(soundUri)
                .setContentIntent(pendingIntent);

        notificationmanager mnotificationmanager = (notificationmanager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            if(soundUri != null){
                notificationBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
                AudioAttributes audioAttributes = new AudioAttributes.Builder()
                        .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                        .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                        .setLegacyStreamType(AudioManager.STREAM_NOTIFICATION)
                        .build();
                NotificationChannel notificationChannel = new NotificationChannel(ChannelId,"Messenger",notificationmanager.IMPORTANCE_DEFAULT);
                notificationChannel.setSound(soundUri,audioAttributes);
                notificationChannel.enableVibration(true);
                notificationChannel.setVibrationPattern(new long[]{ 100 });
                mnotificationmanager.createNotificationChannel(notificationChannel);
            }
        }
        mnotificationmanager.notify(0,notificationBuilder.build());
    }

解决方法

这与自定义声音无关。您实际上没有设置任何模式。振动模式中的第一个值定义了在打开振动器之前要等待的毫秒数。下一个值指示在关闭振动器之前将其保持打开状态的毫秒数,随后的值在这两个值之间交替变化。因此,实际上图案序列表示OFF,ON,OFF,ON...,因此要产生任何振动,您至少需要两个值。我认为您最有可能是这样的:

notificationChannel.setVibrationPattern(new long[]{ 0,100 });

此外,调用notificationChannel.enableVibration(true);是多余的,因为设置有效模式会自动启用它(请参见source)。