【问题标题】:flutter - Notification not displayed颤动 - 未显示通知
【发布时间】:2022-11-13 03:18:57
【问题描述】:

我正在尝试显示本地通知。我不明白我错过了什么,但没有显示通知。我已尝试激活该应用程序。但是当应用程序在后台时它会起作用。

我已经检查了配置并且允许通知。如果你能帮上忙就太好了。谢谢你。

import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:rxdart/rxdart.dart';
import 'package:timezone/data/latest.dart' as tz;
import 'package:timezone/timezone.dart' as tz;
import 'package:flutter_native_timezone/flutter_native_timezone.dart';

class NotificationApi {
  static final _notifications = FlutterLocalNotificationsPlugin();
  static final onNotifications = BehaviorSubject<String?>();

  static Future _notificationDetails() async {
    /*final largeIconPath = await Utils.downloadFile(
      'https://images.unsplash.com/photo-1597223557154-721c1cecc4b0?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=80',
      'largeIcon',
    );*/
    /*final bigPicturePath = await Utils.downloadFile(
      'https://images.unsplash.com/photo-1589010588553-46e8e7c21788?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=400&q=80',
      'bigPicture',
    );*/

   // final styleInformation = BigPictureStyleInformation(
    //  FilePathAndroidBitmap(bigPicturePath),
    //  largeIcon: FilePathAndroidBitmap(largeIconPath),
   // );

    /// Download: https://samplefocus.com/samples/chime-notification-alert
    const sound = 'notification_sound.wav';
    return NotificationDetails(
      android: AndroidNotificationDetails(
        'channel id 8',
        'channel name',
        channelDescription: 'channel description',
        importance: Importance.max,
        //playSound: false,
        sound: RawResourceAndroidNotificationSound(sound.split('.').first),
        enableVibration: false,
      //  styleInformation: styleInformation,
      ),
      iOS: const IOSNotificationDetails(
        presentSound: false,
        sound: sound,
      ),
    );
  }

  static Future init({bool initScheduled = false}) async {
    const android = AndroidInitializationSettings('@mipmap/ic_launcher');
    const iOS = IOSInitializationSettings();
    const settings = InitializationSettings(android: android, iOS: iOS);

    /// Handle payload when app is closed
    final details = await _notifications.getNotificationAppLaunchDetails();
    if (details != null && details.didNotificationLaunchApp) {
      onNotifications.add(details.payload);
    }

    await _notifications.initialize(
      settings,
      onSelectNotification: (payload) async {
        onNotifications.add(payload);
      },
    );

    if (initScheduled) {
      tz.initializeTimeZones();
      final locationName = await FlutterNativeTimezone.getLocalTimezone();
      tz.setLocalLocation(tz.getLocation(locationName));
    }
  }

  /// Direct Notification
  static Future showNotification({
    int id = 0,
    String? title,
    String? body,
    String? payload,
  }) async =>
      _notifications.show(
        id,
        title,
        body,
        await _notificationDetails(),
        payload: payload,
      );

  /// Notification for specific DateTime
  static void showScheduledNotification({
    int id = 0,
    String? title,
    String? body,
    String? payload,
    required DateTime scheduledDate,
  }) async =>
      _notifications.zonedSchedule(
        id,
        title,
        body,
        tz.TZDateTime.from(scheduledDate, tz.local),
        await _notificationDetails(),
        payload: payload,
        androidAllowWhileIdle: true,
        uiLocalNotificationDateInterpretation:
        UILocalNotificationDateInterpretation.absoluteTime,
      );

  static tz.TZDateTime _scheduleDaily(Time time) {
    final now = tz.TZDateTime.now(tz.local);
    final scheduledDate = tz.TZDateTime(tz.local, now.year, now.month, now.day,
        time.hour, time.minute, time.second);

    return scheduledDate.isBefore(now)
        ? scheduledDate.add(const Duration(days: 1))
        : scheduledDate;
  }

  static List<tz.TZDateTime> _scheduleWeekly(Time time,
      {required List<int> days}) {
    return days.map((day) {
      tz.TZDateTime scheduledDate = _scheduleDaily(time);

      while (day != scheduledDate.weekday) {
        scheduledDate = scheduledDate.add(const Duration(days: 1));
      }
      return scheduledDate;
    }).toList();
  }

  static void cancel(int id) => _notifications.cancel(id);

  static void cancelAll() => _notifications.cancelAll();
}

@override
  void initState() {
    super.initState();
    _contextSelected = _context;

    NotificationApi.init();
    listenNotifications();
  }

  void onClickedNotification(String? payload) {
    // Navigator.of(context).push(MaterialPageRoute(
    //   builder: (context) => SecondPage(payload: payload),
    // ));
  } //TODO a modifier pour que envoie sur bonne page view detail task


  void listenNotifications() =>
      NotificationApi.onNotifications.stream.listen(onClickedNotification);

然后,我有一个按钮,在点击时,我希望执行下面的代码


NotificationApi.showScheduledNotification(
      title: 'Test notification',
      body: 'Today at 6 PM',
      payload: 'test_notification_6pm',
      scheduledDate: DateTime.now().add(const Duration(seconds: 4)),
    );


【问题讨论】:

  • 你能解决这个问题吗?如果是这样,你是如何克服它的
  • 是的。我已经用 <string>local_notifications</string> <key>CFBundleExecutable</key> 编辑了 info.plist

标签: flutter notifications


【解决方案1】:

尝试添加这个

static Future<void> _configureLocalTimeZone() async {
tz.initializeTimeZones();
final String timeZone = await FlutterNativeTimezone.getLocalTimezone();
tz.setLocalLocation(tz.getLocation(timeZone));

}

方法并在 NotificationAPI 类的 init() 方法的顶部调用它。

【讨论】:

    猜你喜欢
    • 2022-12-25
    • 2022-06-28
    • 2020-07-31
    • 2022-08-22
    • 2022-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多