如何将参数传递给Android Alarm Manager的回调函数Flutter?

7

Android闹钟管理器一旦到达设置的时间就会触发,同时也会触发回调函数来处理一些任务。但是,在向回调函数发送消息或参数以执行某些任务时,如何在闹钟管理器中设置特定值来设置特定闹钟并触发回调函数还不清晰。

        await AndroidAlarmManager.oneShot(
          const Duration(seconds: 5),
          // Ensure we have a unique alarm ID.
          Random().nextInt(pow(2, 31)),
          callback,
          exact: true,
          wakeup: true,
        );

那个调用函数在这里。但它无法获取来自其父函数的变量。
  // The callback for our alarm
  static Future<void> callback() async {
    print('Alarm fired!');

    // Get the previous cached count and increment it.
    final prefs = await SharedPreferences.getInstance();
    int currentCount = prefs.getInt(countKey);
    await prefs.setInt(countKey, currentCount + 1);

    // This will be null if we're running in the background.
    uiSendPort ??= IsolateNameServer.lookupPortByName(isolateName);
    uiSendPort?.send(null);
  }

我的主要目的是将Android Alarm Manager用作提醒应用程序。


1
我使用sqflite解决了这个问题,通过保存索引和其他数据,如时间戳、消息、ID和其他内容。然后,在闹钟触发后,您将拥有一个索引,可以使用该索引从SQFLITE数据库中获取数据。 - zemunkh
1个回答

0

首先,您可以仅使用形式参数而不是实际参数在回调函数中使用alarmId,并使用该变量获取特定数据。

// The callback for our alarm
static Future<void> callback(int alarmId) async {
print('Alarm fired! : ' + alarmId);

// Get the previous cached count and increment it.
final prefs = await SharedPreferences.getInstance();
int currentCount = prefs.getInt(countKey);
await prefs.setInt(countKey, currentCount + 1);

// This will be null if we're running in the background.
uiSendPort ??= IsolateNameServer.lookupPortByName(isolateName);
uiSendPort?.send(null);
}

此外,您应该使用 sqflite 数据库,它是一个关系型本地数据库,可以将您的提醒信息存储在移动设备的本地磁盘中,并且在未来,您可以通过使用此唯一的 alarmId(如果将其插入到表中)来获取它。

https://pub.dev/packages/sqflite

这份文档将帮助您使用sqflite执行基本的CRUD操作。

希望它能对您有所帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接