Уведомление о тревоге, не воспроизводившись на заказ или правильноAndroid

Форум для тех, кто программирует под Android
Ответить
Anonymous
 Уведомление о тревоге, не воспроизводившись на заказ или правильно

Сообщение 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);
}
}


Подробнее здесь: https://stackoverflow.com/questions/796 ... on-correct
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Android»