在 Android Oreo 中,为保护用户隐私和减少恼人的通知声和振动,Google 强制规定了一些限制,包括不能从应用程序代码中更改通知声和振动。但是,可以通过以下方法在应用程序中更改通知声和振动:
1.首先,在 AndroidManifest.xml 文件中声明一个频道 ID,这将帮助您创建该频道的通知。例如:
...
...
2.然后,在应用程序中创建一个频道以及可选的振动和声音。例如:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel notificationChannel = new NotificationChannel(channelId, "Name", importance);
notificationChannel.setVibrationPattern(new long[] { 100, 200, 300, 400, 500, 400, 300, 200, 400 });
AudioAttributes audioAttributes = new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_NOTIFICATION).build();
notificationChannel.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION), audioAttributes);
notificationManager.createNotificationChannel(notificationChannel);
}
3.最后,在发送通知之前设置通知的频道 ID。例如:
Notification.Builder builder = new Notification.Builder(this)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("Title")
.setContentText("Message")
.setChannelId(channelId);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(notificationId, builder.build());
以上是在 Android Oreo+上为通知设置自定义声音和振动的解决方法。