【问题标题】:Execute a Dart function in background when the flutter app Autostart's on BOOT_COMPLETED?当颤振应用程序自动启动在 BOOT_COMPLETED 时,在后台执行 Dart 函数?
【发布时间】:2019-08-28 22:53:46
【问题描述】:

在我的 Flutter 应用程序中,我希望在应用程序收到 Autostart on BOOT_COMPLETED 消息后立即在后台执行一个小的 Dart 函数,而不是在屏幕上加载整个应用程序。

当用户从启动器启动应用程序时,应用程序应该正常加载,但是当应用程序收到 Autostart on BOOT_COMPLETED 消息时,它应该只是在后台运行一个小的 dart 函数,而不会将应用程序实际加载到屏幕上。

到目前为止,我已经使用了以下git中的代码>>https://github.com/oatpano/flutter_boot_startup

但是,此代码将在屏幕上运行整个应用程序。

我不是 Android 开发人员,所以我无法确定清单文件中到底发生了什么。

所以在下面的示例中,我想仅在应用收到 Autostart on BOOT_COMPLETED 消息时执行 backgroundfunction()

import 'package:flutter/material.dart';

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

void backgroundfunction(){
    print("Hello world");
}

【问题讨论】:

  • 据我了解,存储库的唯一目的是在启动时启动活动。所以你所看到的几乎是预期的。为什么要在启动后执行代码?如果你想每隔几分钟运行一次代码,也许 background_fetch 插件会很有用:github.com/transistorsoft/flutter_background_fetch 它有一个类似的功能,允许无头模式:github.com/transistorsoft/flutter_background_fetch/blob/master/…
  • @herbert 感谢您抽出宝贵时间。我可以使用 flutter_background_fetch 在后台定期运行代码。这个包很棒,即使应用程序被用户终止并且不再在内存中,它也会执行该功能。但是,如果用户重新启动设备,则定期后台执行将停止。如果即使在启动后也要执行该功能,我也可以使用 flutter_background_fetch。
  • 确实如此,看我的回答。

标签: java android kotlin dart flutter


【解决方案1】:

您可以使用background_fetch plugin 并确保:

  1. 你关注headless mode documentation
  2. 通过during configuration of the service 启用startOnBoot: true,这将在Android use a BOOT_COMPLETED receiver,或者在Android >= 21 上为persisted JobService

【讨论】:

    猜你喜欢
    • 2020-05-11
    • 1970-01-01
    • 1970-01-01
    • 2021-06-27
    • 2021-08-23
    • 2021-11-12
    • 2019-09-01
    • 2021-02-25
    • 1970-01-01
    相关资源
    最近更新 更多