在 flutter 中每 x 小时显示一条通知

问题描述 投票:0回答:1

我试图在 Android 通知中每 x 小时显示一条文本。我要求 ChatGpt 作为我编写它的唯一来源,但它似乎缺少一些我不太明白的东西。 这就是我到目前为止所做的:

main.dart:

final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
    FlutterLocalNotificationsPlugin();

Future<void> main() async {
  if (!kIsWeb && (Platform.isWindows || Platform.isLinux || Platform.isMacOS)) {
    sqfliteFfiInit();
    databaseFactory = databaseFactoryFfi;
  }
  WidgetsFlutterBinding.ensureInitialized();
  tz.initializeTimeZones();

  const AndroidInitializationSettings initializationSettingsAndroid =
      AndroidInitializationSettings('@mipmap/ic_launcher');

  const InitializationSettings initializationSettings =
      InitializationSettings(android: initializationSettingsAndroid);

  await flutterLocalNotificationsPlugin.initialize(initializationSettings);
  if (Platform.isAndroid || Platform.isIOS) {
    await NotificationService().scheduleRepeatingNotification();
  }
  runApp(const MyApp());
}

notification_service.dart

import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:timezone/timezone.dart' as tz;

class NotificationService {
  final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
      FlutterLocalNotificationsPlugin();

  Future<void> scheduleRepeatingNotification() async {
    const AndroidNotificationDetails androidDetails =
        AndroidNotificationDetails(
      'channel_id',
      'channel_name',
      channelDescription: 'description',
      importance: Importance.max,
      priority: Priority.high,
    );

    const NotificationDetails platformDetails = NotificationDetails(
      android: androidDetails,
    );

    final tz.TZDateTime now = tz.TZDateTime.now(tz.local);
    final tz.TZDateTime firstNotification =
        now.add(const Duration(hours: 3)); // Start in 3 hours

    await flutterLocalNotificationsPlugin.zonedSchedule(
      0, // ID of the notification
      'Scheduled Notification',
      'This notification repeats every 3 hours.',
      firstNotification,
      platformDetails,
      uiLocalNotificationDateInterpretation:
          UILocalNotificationDateInterpretation.absoluteTime,
      matchDateTimeComponents: DateTimeComponents.time, // To repeat at intervals
      androidScheduleMode: AndroidScheduleMode.exactAllowWhileIdle, // Add this
    );
  }
}

pubspec.yaml:

dependencies:
  flutter:
    sdk: flutter
  provider: ^6.0.1
  sqflite: ^2.0.3
  path: ^1.8.3
  sqflite_common_ffi: ^2.1.0
  flutter_local_notifications: ^18.0.1
  get: ^4.6.5
  cupertino_icons: ^1.0.8
  timezone: ^0.9.0

现在,当我将它安装到手机上时,它就死机了。应用程序的屏幕黑屏并且卡住。我做错了什么吗?

flutter dart flutter-local-notification
1个回答
0
投票

您是否添加了 POST_NOTIFICATIONS 权限?,因为在 Android 上发布通知。在最近的 Android 版本中(从 Android 13,API 级别 33 开始),您需要在 AndroidManifest.xml 中显式声明 POST_NOTIFICATIONS 权限,如下所示:

<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/> 
© www.soinside.com 2019 - 2024. All rights reserved.