Флаттер Звук локального уведомления не работает

#android #flutter #flutter-local-notification

Вопрос:

Звук уведомления с использованием локального уведомления Flutter для Android вообще не работает вот код

 const NotificationDetails(
          android: AndroidNotificationDetails(
            'daily notification channel id',
            'daily notification channel name',
            'daily notification description',
            playSound: true,
            sound: RawResourceAndroidNotificationSound('pop'),
            importance: Importance.max,
            priority: Priority.high,
          ),
        ),
 

И у меня есть pop.mp3 по этому пути: androidappsrcmainresrawpop.mp3

Как я могу воспроизвести звук?

Ответ №1:

У меня уже была такая проблема, как у вас, но она решается с помощью приведенного ниже кода

 class AddTaskScreen extends StatefulWidget {
  static String id = 'AddTaskScreen';

  @override
  _AddTaskScreenState createState() => _AddTaskScreenState();
}

class _AddTaskScreenState extends State<AddTaskScreen> {
  final taskController = TextEditingController();
  final deskController = TextEditingController();

  String currTask = '';
  String deskTask = '';
  bool remindMe = false;
  DateTime reminderDate;
  TimeOfDay reminderTime;
  int id;

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Container(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[
            Text(
              Kunci.add_task.tr(),
              textAlign: TextAlign.center,
              style: TextStyle(
                fontWeight: FontWeight.w500,
              ),
            ),
            SizedBox(height: 15),
            TextFormField(
              controller: taskController,
              autofocus: false,
              textCapitalization: TextCapitalization.sentences,
              onChanged: (newVal) {
                currTask = newVal;
              },
              decoration: InputDecoration(
                focusedBorder: OutlineInputBorder(
                  borderSide: BorderSide(width: 0.5),
                ),
                hintText: Kunci.title_here.tr(),
                contentPadding: EdgeInsets.all(10),
                border: OutlineInputBorder(
                  borderSide: BorderSide(width: 0.5),
                ),
              ),
            ),
            SizedBox(height: 5),
            TextField(
              maxLines: 3,
              controller: deskController,
              autofocus: false,
              textCapitalization: TextCapitalization.sentences,
              onChanged: (newVal) {
                deskTask = newVal;
              },
              decoration: InputDecoration(
                focusedBorder: OutlineInputBorder(
                  borderSide: BorderSide(width: 0.5),
                ),
                hintText: Kunci.desc_here.tr(),
                contentPadding: EdgeInsets.all(10),
                border: OutlineInputBorder(
                  borderSide: BorderSide(width: 0.5),
                ),
              ),
            ),
            SizedBox(height: 10.0),
            SwitchListTile(
              contentPadding: EdgeInsets.all(0),
              value: remindMe,
              title: Text(Kunci.reminder.tr()),
              onChanged: (newValue) async {
                if (newValue) {
                  reminderDate = await showDatePicker(
                    context: context,
                    initialDate: DateTime.now(),
                    firstDate: DateTime.now(),
                    lastDate: DateTime(DateTime.now().year   2),
                  );

                  if (reminderDate == null) {
                    return;
                  }

                  reminderTime = await showTimePicker(
                      context: context, initialTime: TimeOfDay.now());

                  if (reminderDate != null amp;amp; reminderTime != null) {
                    remindMe = newValue;
                  }
                } else {
                  reminderDate = null;
                  reminderTime = null;
                  remindMe = newValue;
                }

                print(reminderTime);
                print(reminderDate);

                setState(() {});
              },
            ),
            Container(
                child: remindMe
                    ? Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Icon(FlutterIcons.calendar_ant, size: 20),
                          SizedBox(width: 5),
                          Text(
                            DateTime(
                              reminderDate.year,
                              reminderDate.month,
                              reminderDate.day,
                              reminderTime.hour,
                              reminderTime.minute,
                            ).toString().substring(0, 10),
                            style: TextStyle(fontSize: 15),
                          ),
                          SizedBox(width: 15),
                          Icon(FlutterIcons.calendar_ant, size: 20),
                          SizedBox(width: 5),
                          Text(
                            DateTime(
                              reminderDate.year,
                              reminderDate.month,
                              reminderDate.day,
                              reminderTime.hour,
                              reminderTime.minute,
                            ).toString().substring(11, 16),
                            style: TextStyle(fontSize: 15),
                          ),
                        ],
                      )
                    : null),
            SizedBox(
              height: remindMe ? 10.0 : 0.0,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Expanded(
                  child: FlatButton(
                    child: Text(
                      Kunci.cancel.tr(),
                      style: TextStyle(color: Colors.white, letterSpacing: 1.5),
                    ),
                    onPressed: () {
                      Navigator.pop(context);
                    },
                    color: Colors.grey,
                  ),
                ),
                SizedBox(width: 10),
                Expanded(
                  child: FlatButton(
                    child: Text(
                      Kunci.save.tr(),
                      style: TextStyle(color: Colors.white, letterSpacing: 1.5),
                    ),
                    onPressed: () async {
                      if (remindMe) {
                        **var scheduledNotificationDateTime = reminderDate
                            .add(Duration(
                                hours: reminderTime.hour,
                                minutes: reminderTime.minute))
                            .subtract(Duration(seconds: 5));
                        var androidPlatformChannelSpecifics =
                            AndroidNotificationDetails(
                          currTask,
                          'To Do Notification',
                          'Do the task',
                          sound: RawResourceAndroidNotificationSound('pop'),
                          priority: Priority.high,
                          importance: Importance.high,
                          playSound: true,**
                        );
                        var iOSPlatformChannelSpecifics =
                            IOSNotificationDetails();
                        NotificationDetails platformChannelSpecifics =
                            NotificationDetails(
                                android: androidPlatformChannelSpecifics,
                                iOS: iOSPlatformChannelSpecifics);
                        id = Provider.of<TaskData>(context, listen: false)
                            .tasks
                            .length;
                        print(id);
                        await flutterLocalNotificationsPlugin.schedule(
                            id,
                            Kunci.task_reminder.tr(),
                            currTask,
                            scheduledNotificationDateTime,
                            platformChannelSpecifics);
                      }

                      Provider.of<TaskData>(
                        context,
                        listen: false,
                      ).addTask(Task(
                        title: currTask,
                        deskripsi: deskTask,
                        isChecked: false,
                        reminderDate: reminderDate == null
                            ? null
                            : reminderDate.add(Duration(
                                hours: reminderTime.hour,
                                minutes: reminderTime.minute,
                              )),
                        reminderId: reminderDate != null ? id : null,
                      ));
                      Navigator.pop(context);
                    },
                    color: Theme.of(context).accentColor,
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
 

пожалуйста, отрегулируйте его с помощью вашего кода

Ответ №2:

Моя проблема заключалась в том, что я тестировал приложение на Xiaomi и понял, что у Xiaomi есть некоторые проблемы, и по умолчанию он не разрешает звук уведомлений. Почему-то это не сработало и на эмуляторе, но, протестировав его на других физических устройствах, оно сработало.

Комментарии:

1. Я получаю комментарии в магазине Play, в которых говорится, что звуки уведомлений не работают на некоторых устройствах, я думаю, что это могут быть устройства Xiaomi, вы нашли исправление?

Ответ №3:

добавьте этот код в Manifest.xml

 <receiver android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationReceiver" />
....
</application>
 

Комментарии:

1. Пожалуйста, добавьте дополнительные сведения, чтобы расширить свой ответ, например, ссылки на рабочий код или документацию.