如何在Flutter应用程序的后台运行代码?

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

我正在开发一款Flutter应用。我一天中有很多次,我想在任何时候显示警报通知,如果正在运行,还要更改应用程序的用户界面。

所以我寻找了可以选择的选项,因此发现了以下内容

  • 诸如flutter-workmanagerbackground_fetch的插件
  • 使用渠道实施本机代码

我的问题是:

  1. 哪个选项最适合我的用例?
  2. 是否更好地实现按时间延迟或使用警报管理器的时间计数器。
  3. 如何在后台任务和应用之间传递数据(当前时间),以便可以更新UI?

PS:目前,我们对至少适用于Android的解决方案感兴趣。

flutter timer scheduled-tasks alarmmanager background-task
1个回答
0
投票

我认为您仅需要后台任务即可显示通知。使用flutter_local_notifications应该足以完成您的任务。您可以使用此插件安排特定日期时间的通知。在应用程序内部,您可以使用Timer在特定日期时间触发。我给你看一个简单的例子:

demo

class _HomePageState extends State<HomePage> {
  FlutterLocalNotificationsPlugin notifPlugin;

  @override
  void initState() {
    super.initState();
    notifPlugin = FlutterLocalNotificationsPlugin();
  }

  Future<void> scheduleNotification(DateTime dateTime, String title) async {
    final now = DateTime.now();
    if (dateTime.isBefore(now)) {
      // dateTime is past
      return;
    }

    final difference = dateTime.difference(now);

    Timer(difference, () {
      showDialog(
        context: this.context,
        builder: (context) {
          return AlertDialog(
            content: Text(title),
          );
        }
      );
    });

    await notifPlugin.schedule(title.hashCode, title, title, dateTime, platformChannelSpecifics, payload: 'test');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: SafeArea(
        child: Container()
      ),
      floatingActionButton: Builder(
        builder: (context) {
          return FloatingActionButton(
            onPressed: () {
              final snackbar = SnackBar(content: Text('planned notification'), duration: Duration(seconds: 3));
              Scaffold.of(context).showSnackBar(snackbar);
              scheduleNotification(DateTime.now().add(Duration(seconds: 2)), 'Hello');
            },
          );
        }
      ),
    );
  }
}

但是如果您需要进行一些计算或数据提取,那么background_fetch是您所需要的。唯一的问题是在大多数情况下,Apple不允许后台任务。

© www.soinside.com 2019 - 2024. All rights reserved.