首页 > 解决方案 > 在 AlarmManager 中调用平台特定方法

问题描述

我有以下情况。我有一个每天触发一次的 AlarmManager。在此警报中,我比较两个值,如果这些值相同,我会发送通知。所以我创建了我的平台特定代码(仅限 Android)来发送通知。

问题:我只能在 AlarmManager 之外调用方法。这意味着如果我在没有 AlarmManager 的情况下将方法称为“正常”,一切都会按预期工作。否则会抛出如下错误:

22:25:30.545 16 info flutter.tools E/flutter ( 5255): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: MissingPluginException(No implementation found for method test on channel reminder_channel)

带有警报管理器的代码:

主要.dart

final int dailyAlarmID = 0;
await AndroidAlarmManager.initialize();

runApp(...);

await AndroidAlarmManager.oneShot(
    Duration(seconds: 15), dailyAlarmID, testMethod);
}

测试方法:

void testMethod() async {
  SharedPreferences preferences = await SharedPreferences.getInstance();
  bool testBool = preferences.getBool("darkTheme");
  print("testBool: $testBool");

  final MethodChannel platform = const MethodChannel("reminder_channel");
  final testInt = await platform.invokeMethod("test");
  print("testInt: $testInt");
}

顺便说一句,我的方法返回一个 Int,即 5。这只是为了测试。并且 testBool 变量从 Shared Preferences 中读取并在两个变体中正确显示。

输出:

22:25:30.535 15 info flutter.tools I/flutter ( 5255): testBool: true
22:25:30.545 16 info flutter.tools E/flutter ( 5255): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: MissingPluginException(No implementation found for method test on channel reminder_channel)

没有警报管理器:

主要飞镖:

testMethod();

我只是在主方法的末尾调用方法。没什么特别的。

输出:

22:41:58.054 10 info flutter.tools I/flutter ( 5564): testBool: true
22:41:58.633 12 info flutter.tools I/flutter ( 5564): testInt: 5

感谢您的帮助。

标签: flutterdart

解决方案


到目前为止,这是飞镖的一个已知问题。参考https://github.com/flutter/flutter/issues/56186https://github.com/flutter/flutter/issues/13937


推荐阅读