Flutter后台触发闹钟插件flutter_alarm_background_trigger的使用

发布于 1周前 作者 phonegap100 来自 Flutter

Flutter后台触发闹钟插件flutter_alarm_background_trigger的使用

安装

flutter_alarm_background_trigger: ^1.0.0
# 或者
flutter pub add flutter_alarm_background_trigger

初始化

void main() {
  // 非常重要,必须在初始化之前调用,以确保绑定可用且准备就绪
  WidgetsFlutterBinding.ensureInitialized();

  // 初始化 Required 用于将闹钟事件与 Flutter 方法通道绑定
  FlutterAlarmBackgroundTrigger.initialize();

  runApp(const MyApp());
}

创建实例

var alarmPlugin = FlutterAlarmBackgroundTrigger();

设置闹钟

alarmPlugin.addAlarm(
  // 必需
  DateTime.now().add(Duration(seconds: 10)),

  // 可选
  uid: "YOUR_APP_ID_TO_IDENTIFY",
  payload: {"YOUR_EXTRA_DATA":"FOR_ALARM"},

  // screenWakeDuration: 闹钟触发时屏幕唤醒的时间长度
  screenWakeDuration: Duration(minutes: 1)
);

接收闹钟触发事件

alarmPlugin.requestPermission().then((isGranted){
  if(isGranted){
    alarmPlugin.onForegroundAlarmEventHandler((alarm){
      // 在前台或后台执行你的操作
      print(alarm.id)
    })
  }
})

其他方法

  • 请求权限
    Future<bool> requestPermission()
    
  • 添加闹钟
    Future<AlarmItem> addAlarm(
      DateTime time, 
      {
        String? uid, 
        Map<String, dynamic>? payload, 
        Duration screenWakeDuration
      }
    )
    
  • 按 UID 获取闹钟
    Future<List<AlarmItem>> getAlarmByUid(String uid)
    
  • 获取所有计划中的闹钟
    Future<List<AlarmItem>> getAllAlarms()
    
  • 按 ID 获取单个闹钟
    Future<AlarmItem> getAlarm(int id)
    
  • 按 Payload 获取闹钟
    Future<List<AlarmItem>> getAlarmByPayload(Map<String, dynamic> payload)
    
  • 按时间获取闹钟
    Future<List<AlarmItem>> getAlarmByTime(DateTime time)
    
  • 闹钟触发事件处理
    void onForegroundAlarmEventHandler(OnForegroundAlarmEvent alarmEvent)
    
  • 删除单个闹钟
    Future<void> deleteAlarm(int id)
    
  • 按 Payload 删除闹钟
    Future<void> deleteAlarmsByPayload(Map<String, dynamic> payload)
    
  • 按时间删除闹钟
    Future<void> deleteAlarmsByTime(DateTime dateTime)
    
  • 按 UID 删除闹钟
    Future<void> deleteAlarmsByUid(String uid)
    
  • 删除所有计划中的闹钟
    Future<void> deleteAllAlarms()
    

示例代码

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

import 'package:flutter_alarm_background_trigger/flutter_alarm_background_trigger.dart';
import 'package:date_time_picker/date_time_picker.dart';
import 'package:flutter_alarm_background_trigger_example/alarm_service.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();

  // 初始化 Required 用于将闹钟事件与 Flutter 方法通道绑定
  FlutterAlarmBackgroundTrigger.initialize();

  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  AlarmItem? _alarmItem;
  DateTime? time;
  List<AlarmItem> alarms = [];

  [@override](/user/override)
  void initState() {
    super.initState();
    reloadAlarms();
    AlarmService.instance.onForegroundAlarmEventHandler((alarmItem) {
      reloadAlarms();
    });
  }

  reloadAlarms() {
    AlarmService.instance.getAllAlarms().then((alarmsList) => setState(() {
          alarms = alarmsList;
        }));
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Builder(builder: (context) {
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Card(
                  margin: const EdgeInsets.all(10),
                  child: Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Row(
                      children: [
                        Expanded(
                            child: DateTimePicker(
                          type: DateTimePickerType.dateTime,
                          initialValue: '',
                          firstDate: DateTime.now(),
                          lastDate:
                              DateTime.now().add(const Duration(days: 365)),
                          dateLabelText: 'Alarm date time',
                          onChanged: (val) => setState(() {
                            time = DateTime.parse(val);
                          }),
                        )),
                        ElevatedButton(
                            onPressed: createAlarm,
                            child: const Text("Set Alarm"))
                      ],
                    ),
                  ),
                ),
                Expanded(
                  child: ListView.builder(
                    itemCount: alarms.length,
                    itemBuilder: (ctx, idx) => ((AlarmItem alarm) => ListTile(
                          title: Row(
                            children: [
                              Text(alarm.time!.toString()),
                              const SizedBox(width: 5),
                              Chip(
                                padding: EdgeInsets.zero,
                                label: Text(describeEnum(alarm.status),
                                    style: TextStyle(
                                        color: alarm.status == AlarmStatus.DONE
                                            ? Colors.black
                                            : Colors.white,
                                        fontSize: 10)),
                                backgroundColor:
                                    alarm.status == AlarmStatus.DONE
                                        ? Colors.greenAccent
                                        : Colors.redAccent,
                              )
                            ],
                          ),
                          subtitle: Text(
                              "ID: ${alarm.id}, UID: ${alarm.uid}, Payload: ${alarm.payload.toString()}"),
                          trailing: IconButton(
                              onPressed: () async {
                                await AlarmService.instance
                                    .deleteAlarm(alarm.id!);
                                reloadAlarms();
                              },
                              icon:
                                  const Icon(Icons.delete, color: Colors.red)),
                        ))(alarms[idx]),
                  ),
                )
              ],
            ),
          );
        }),
      ),
    );
  }

  void createAlarm() async {
    await AlarmService.instance
        .addAlarm(time!, uid: "TEST UID", payload: {"holy": "Moly"});
    reloadAlarms();
  }
}

更多关于Flutter后台触发闹钟插件flutter_alarm_background_trigger的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter后台触发闹钟插件flutter_alarm_background_trigger的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何使用 flutter_alarm_background_trigger 插件在 Flutter 应用中设置后台触发闹钟的示例代码。这个插件允许你在应用处于后台或终止状态时触发闹钟事件。

步骤 1: 添加依赖

首先,在你的 pubspec.yaml 文件中添加 flutter_alarm_background_trigger 依赖:

dependencies:
  flutter:
    sdk: flutter
  flutter_alarm_background_trigger: ^x.y.z  # 替换为最新版本号

然后运行 flutter pub get 来获取依赖。

步骤 2: 配置 Android 权限

android/app/src/main/AndroidManifest.xml 文件中添加必要的权限:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

步骤 3: 配置 iOS 权限

ios/Runner/Info.plist 文件中添加必要的权限(如果需要)。

步骤 4: 实现后台闹钟功能

在你的 Flutter 项目中,编写以下 Dart 代码来设置和使用后台闹钟:

import 'package:flutter/material.dart';
import 'package:flutter_alarm_background_trigger/flutter_alarm_background_trigger.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: AlarmScreen(),
    );
  }
}

class AlarmScreen extends StatefulWidget {
  @override
  _AlarmScreenState createState() => _AlarmScreenState();
}

class _AlarmScreenState extends State<AlarmScreen> {
  String _alarmStatus = "Alarm not set";

  @override
  void initState() {
    super.initState();

    // 设置后台闹钟
    _setupAlarm();

    // 监听后台闹钟事件
    FlutterAlarmBackgroundTrigger.eventStream.listen((event) {
      if (event.type == FlutterAlarmBackgroundTriggerEventType.alarm) {
        // 处理闹钟事件
        showDialog(
          context: context,
          builder: (context) => AlertDialog(
            title: Text("Alarm Triggered"),
            content: Text("The alarm has been triggered in the background."),
            actions: <Widget>[
              TextButton(
                onPressed: () => Navigator.of(context).pop(),
                child: Text("OK"),
              ),
            ],
          ),
        );
      }
    });
  }

  void _setupAlarm() async {
    // 设置一个10秒后触发的闹钟
    int delayInSeconds = 10;
    await FlutterAlarmBackgroundTrigger.setupAlarm(
      alarmId: "my_alarm_id",
      delayInSeconds: delayInSeconds,
      oneShot: true,  // 是否是一次性闹钟
    );

    setState(() {
      _alarmStatus = "Alarm set to trigger after ${delayInSeconds} seconds";
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Background Alarm Example"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(_alarmStatus),
          ],
        ),
      ),
    );
  }
}

注意事项

  1. 权限处理:确保在运行时请求并处理必要的权限,特别是在 Android 上。
  2. 电池优化:某些设备和操作系统可能会限制后台任务,包括闹钟。确保你的应用被允许在后台运行。
  3. 测试:在真实设备上测试你的应用,以确保后台闹钟功能按预期工作。

这个示例展示了如何使用 flutter_alarm_background_trigger 插件来设置和监听后台闹钟事件。根据你的具体需求,你可能需要调整代码和配置。

回到顶部