以下方法显示带有自定义声音和频道的通知。问题是振动不起作用。我曾尝试研究并尝试过,但没有成功。
private void showNotification(){
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, 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());
}
答案 0 :(得分:1)
这与自定义声音无关。您实际上没有设置任何模式。振动模式中的第一个值定义了在打开振动器之前要等待的毫秒数。下一个值指示在关闭振动器之前将其保持打开状态的毫秒数,随后的值在这两个值之间交替变化。因此,实际上图案序列表示OFF, ON, OFF, ON...
,因此要产生任何振动,您至少需要两个值。我认为您最有可能是这样的:
notificationChannel.setVibrationPattern(new long[]{ 0, 100 });
此外,调用notificationChannel.enableVibration(true);
是多余的,因为设置有效模式会自动启用它(请参见source)。