【发布时间】:2018-03-12 10:23:52
【问题描述】:
我有一个在前台运行的服务,其中包括秒表。当服务启动时,会出现通知,当它结束时,我会用声音和一些指示它完成的文本来更新它。问题是这在 api 25 之前运行良好,但对于 26 和 27,它可以更新通知,但没有声音。以下是相关代码:
在服务内创建通知:
mBuilder = new NotificationCompat.Builder(context, "Main")
.setSmallIcon(R.drawable.ic_notification_temp)
.setContentTitle(step.getDescription())
.setContentText(getString(R.string.notification_text))
.setVisibility(VISIBILITY_PUBLIC)
.setOngoing(true);
.setDeleteIntent(deletePendingIntent);
.setContentIntent(contentPendingIntent);
.addAction(R.drawable.ic_stop_red_24dp, getString(R.string.cancel),finnishPendingIntent);
mNotificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(mId, mBuilder.build());
“工作”完成后通知生成器的更新:
mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
mBuilder.setVibrate(new long[]{0, 300, 0, 400, 0, 500});
mBuilder.setOngoing(false);
mBuilder.setAutoCancel(true);
mBuilder.setContentText(getString(R.string.notification_finished_text));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
mBuilder.setChannelId("Sound");
mBuilder.setCategory(NotificationCompat.CATEGORY_ALARM);
}
mNotificationManager.notify(mId, mBuilder.build());
在应用启动时仅为 api 26 或更高版本创建的 2 个通道:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// Create the normal NotificationChannel
CharSequence name = getString(R.string.app_name);
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel channel = new NotificationChannel("Main", name, importance);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = (NotificationManager) getSystemService(
NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(channel);
// Create theNotificationChannel with sound
importance = NotificationManager.IMPORTANCE_HIGH;
name = getString(R.string.notification_channel_sound);
NotificationChannel sound = new NotificationChannel("Sound", name, importance);
sound.enableVibration(true);
sound.setVibrationPattern(new long[]{0, 300, 0, 400, 0, 500});
AudioAttributes aa = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setLegacyStreamType(AudioManager.STREAM_NOTIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION_EVENT)
.build();
sound.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION), aa);
notificationManager.createNotificationChannel(sound);
}
这就是我现在所处的位置。我尝试不使用 setsound() ,因为我已经读到通知应该只播放具有适当重要性的默认声音(当然我什至在尝试正确更新频道设置之间卸载了应用程序)但没有似乎适用于 api 26,我只是不知道我做错了什么。
【问题讨论】:
-
安装应用时,您在通知设置中看到了什么?显示通知时您的活动是否正在运行?
-
@ViktorYakunin 这两个通道已成功创建,但通知从服务运行,尽管我试图让调用服务的活动处于活动状态以防万一。通知显示和行为正确(首先只是抽屉中的徽章,没有视觉中断,然后更新的文本和通知按应有的方式显示,只是没有任何声音)。
-
@MohammadTabbara 是的,我试过这样来测试它是否只是模拟器的问题,不知何故没有默认通知声音,但听起来还不错。但这种解决方法也存在一些问题......
-
再次,您在设置->应用和通知->[您的应用]->应用通知中看到了什么?
标签: java android notifications