Попытка сделать:
Я строю приложение Flutter, где я планирую сигнал тревоги, используя Flutter_local_notifications и хочу воспроизводить пользовательский звук тревоги, когда уведомление запускается. Я также добавил кнопку «Остановить тревогу», чтобы остановить звук. < /P>
The notification shows at the correct time.
Given Sounds Are not playing like an alarm play on Android.
< /code>
Звук не воспроизводится на iOS.import 'dart:async';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:timezone/data/latest_all.dart' as tz;
import 'package:timezone/timezone.dart' as tz;
import 'package:audioplayers/audioplayers.dart';
class NotificationService {
static final FlutterLocalNotificationsPlugin _notificationsPlugin =
FlutterLocalNotificationsPlugin();
static final AudioPlayer _audioPlayer = AudioPlayer();
static bool _isAlarmPlaying = false;
static Future init() async {
const androidSettings =
AndroidInitializationSettings('@mipmap/ic_launcher');
const iosSettings = DarwinInitializationSettings();
const initSettings = InitializationSettings(
android: androidSettings,
iOS: iosSettings,
);
await _notificationsPlugin.initialize(
initSettings,
onDidReceiveNotificationResponse: (details) {
if (details.payload == 'alarm_trigger') {
playAlarmSound();
}
if (details.actionId == 'stop_alarm_action') {
stopAlarmSound();
}
},
);
// iOS Permissions
await _notificationsPlugin
.resolvePlatformSpecificImplementation<
IOSFlutterLocalNotificationsPlugin>()
?.requestPermissions(alert: true, sound: true, badge: true);
tz.initializeTimeZones();
}
static Future scheduleAlarm({
required int id,
required String title,
required String body,
required DateTime scheduledTime,
}) async {
final tzScheduledTime = tz.TZDateTime.from(scheduledTime, tz.local);
const androidDetails = AndroidNotificationDetails(
'alarm_channel',
'Alarm Notifications',
channelDescription: 'Used for daily alarms',
importance: Importance.max,
priority: Priority.high,
playSound: true,
fullScreenIntent: true,
sound: RawResourceAndroidNotificationSound('alarm_sound'),
actions: [
AndroidNotificationAction(
'stop_alarm_action',
'Stop Alarm',
showsUserInterface: true,
cancelNotification: true,
),
],
);
const iosDetails = DarwinNotificationDetails(
sound: 'alarm_sound.mp3',
presentSound: true,
);
const notificationDetails = NotificationDetails(
android: androidDetails,
iOS: iosDetails,
);
await _notificationsPlugin.zonedSchedule(
id,
title,
body,
tzScheduledTime,
notificationDetails,
androidScheduleMode: AndroidScheduleMode.exactAllowWhileIdle,
payload: 'alarm_trigger',
);
}
static Future cancelAlarm(int id) async {
await _notificationsPlugin.cancel(id);
}
static Future playAlarmSound() async {
if (!_isAlarmPlaying) {
_isAlarmPlaying = true;
try {
await _audioPlayer.play(AssetSource('sounds/alarm_sound.mp3'));
} catch (e) {
print('Error playing alarm sound: $e');
}
}
}
static Future stopAlarmSound() async {
if (_isAlarmPlaying) {
await _audioPlayer.stop();
_isAlarmPlaying = false;
}
}
static Future scheduleDailyReflectionReminder({
required int hour,
required int minute,
}) async {
final now = DateTime.now();
final scheduledTime = DateTime(
now.year,
now.month,
now.day,
hour,
minute,
);
final finalScheduledTime = scheduledTime.isBefore(now)
? scheduledTime.add(Duration(days: 1))
: scheduledTime;
await scheduleAlarm(
id: 1001,
title: 'Time for Reflection',
body: 'Take a moment to reflect, pray, or review your day.',
scheduledTime: finalScheduledTime,
);
}
static Future cancelDailyReflectionReminder() async {
await cancelAlarm(1001);
}
}
Подробнее здесь: https://stackoverflow.com/questions/796 ... on-correct
Уведомление о тревоге, не воспроизводившись на заказ или правильно ⇐ Android
Форум для тех, кто программирует под Android
-
Anonymous
1746209940
Anonymous
Попытка сделать:
Я строю приложение Flutter, где я планирую сигнал тревоги, используя Flutter_local_notifications и хочу воспроизводить пользовательский звук тревоги, когда уведомление запускается. Я также добавил кнопку «Остановить тревогу», чтобы остановить звук. < /P>
The notification shows at the correct time.
Given Sounds Are not playing like an alarm play on Android.
< /code>
Звук не воспроизводится на iOS.import 'dart:async';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:timezone/data/latest_all.dart' as tz;
import 'package:timezone/timezone.dart' as tz;
import 'package:audioplayers/audioplayers.dart';
class NotificationService {
static final FlutterLocalNotificationsPlugin _notificationsPlugin =
FlutterLocalNotificationsPlugin();
static final AudioPlayer _audioPlayer = AudioPlayer();
static bool _isAlarmPlaying = false;
static Future init() async {
const androidSettings =
AndroidInitializationSettings('@mipmap/ic_launcher');
const iosSettings = DarwinInitializationSettings();
const initSettings = InitializationSettings(
android: androidSettings,
iOS: iosSettings,
);
await _notificationsPlugin.initialize(
initSettings,
onDidReceiveNotificationResponse: (details) {
if (details.payload == 'alarm_trigger') {
playAlarmSound();
}
if (details.actionId == 'stop_alarm_action') {
stopAlarmSound();
}
},
);
// iOS Permissions
await _notificationsPlugin
.resolvePlatformSpecificImplementation<
IOSFlutterLocalNotificationsPlugin>()
?.requestPermissions(alert: true, sound: true, badge: true);
tz.initializeTimeZones();
}
static Future scheduleAlarm({
required int id,
required String title,
required String body,
required DateTime scheduledTime,
}) async {
final tzScheduledTime = tz.TZDateTime.from(scheduledTime, tz.local);
const androidDetails = AndroidNotificationDetails(
'alarm_channel',
'Alarm Notifications',
channelDescription: 'Used for daily alarms',
importance: Importance.max,
priority: Priority.high,
playSound: true,
fullScreenIntent: true,
sound: RawResourceAndroidNotificationSound('alarm_sound'),
actions: [
AndroidNotificationAction(
'stop_alarm_action',
'Stop Alarm',
showsUserInterface: true,
cancelNotification: true,
),
],
);
const iosDetails = DarwinNotificationDetails(
sound: 'alarm_sound.mp3',
presentSound: true,
);
const notificationDetails = NotificationDetails(
android: androidDetails,
iOS: iosDetails,
);
await _notificationsPlugin.zonedSchedule(
id,
title,
body,
tzScheduledTime,
notificationDetails,
androidScheduleMode: AndroidScheduleMode.exactAllowWhileIdle,
payload: 'alarm_trigger',
);
}
static Future cancelAlarm(int id) async {
await _notificationsPlugin.cancel(id);
}
static Future playAlarmSound() async {
if (!_isAlarmPlaying) {
_isAlarmPlaying = true;
try {
await _audioPlayer.play(AssetSource('sounds/alarm_sound.mp3'));
} catch (e) {
print('Error playing alarm sound: $e');
}
}
}
static Future stopAlarmSound() async {
if (_isAlarmPlaying) {
await _audioPlayer.stop();
_isAlarmPlaying = false;
}
}
static Future scheduleDailyReflectionReminder({
required int hour,
required int minute,
}) async {
final now = DateTime.now();
final scheduledTime = DateTime(
now.year,
now.month,
now.day,
hour,
minute,
);
final finalScheduledTime = scheduledTime.isBefore(now)
? scheduledTime.add(Duration(days: 1))
: scheduledTime;
await scheduleAlarm(
id: 1001,
title: 'Time for Reflection',
body: 'Take a moment to reflect, pray, or review your day.',
scheduledTime: finalScheduledTime,
);
}
static Future cancelDailyReflectionReminder() async {
await cancelAlarm(1001);
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79603926/flutter-alarm-notification-not-playing-custom-sound-or-triggering-action-correct[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия