5

我正在开发 Flutter App 中的原生 Android 小部件。其中有刷新按钮,单击该按钮我必须调用 Flutter 代码中的方法。我正在使用 Flutter Method Channel 进行通信,当应用程序处于前台时它工作正常。但是当应用程序最小化或关闭时它不起作用。我收到错误PlatformException(NO_ACTIVITY, null, null)。下面是我的代码。

安卓 (AppWidgetProvider)

if (methodChannel == null && context != null) {
        FlutterMain.startInitialization(context)
        FlutterMain.ensureInitializationComplete(context, arrayOf())

        // Instantiate a FlutterEngine.
        val engine = FlutterEngine(context.applicationContext)

        // Define a DartEntrypoint
        val entrypoint: DartEntrypoint = DartEntrypoint.createDefault()

        // Execute the DartEntrypoint within the FlutterEngine.
        engine.dartExecutor.executeDartEntrypoint(entrypoint)

        // Register Plugins when in background. When there
        // is already an engine running, this will be ignored (although there will be some
        // warnings in the log).
        //GeneratedPluginRegistrant.registerWith(engine)

        methodChannel = MethodChannel(engine.dartExecutor.binaryMessenger, MainActivity.CHANNEL)
}

methodChannel!!.invokeMethod("fetchNewData", "", object : MethodChannel.Result {
        override fun notImplemented() {
            Toast.makeText(context, "method not implemented", Toast.LENGTH_SHORT).show()
        }

        override fun error(errorCode: String?, errorMessage: String?, errorDetails: Any?) {
            Toast.makeText(context, errorMessage, Toast.LENGTH_SHORT).show()
        }

        override fun success(result: Any?) {
            Toast.makeText(context, "success", Toast.LENGTH_SHORT).show()
        }
})

/// calling in main
static Future<void> attachListeners() async {
    WidgetsFlutterBinding.ensureInitialized();
    var bloc = new AqiCnDashboardBloc();
    _channel.setMethodCallHandler((call) {
      switch (call.method) {
        case 'fetchNewData':
          bloc.getAqiCn(false);
          return null;
        default:
          throw MissingPluginException('notImplemented');
      }
    });
}
4

2 回答 2

1

我正在收集信息/讨论,将我们重定向到在后台运行颤振引擎。

void callbackDispatcher() {
WidgetsFlutterBinding.ensureInitialized();
print("Our background job ran!");

}

void main() {

 static const MethodChannel _channel = const MethodChannel("channel-name");

 Future<void> initialize(final Function callbackDispatcher) async {

  final callback = PluginUtilities.getCallbackHandle(callbackDispatcher);

 await _channel.invokeMethod('initialize', callback.toRawHandle());
 }
}

如此处所述如何在后台运行 Flutter?

当本机启动后台作业时,Flutter 引擎处于不活动状态。所以我们无法运行 Dart。Android/iOS可以在后台启动Flutter引擎吗?是的!我们首先需要注册一个 Dart 回调函数,该回调函数只会在本机代码启动后台作业时调用。此回调函数称为 callbackDispatcher。

另请查看这些 stackoverflow 讨论。

Flutter:将应用程序作为后台服务运行

如何在 Flutter 中创建服务以使应用始终在后台运行?

如何创建在应用程序关闭时也能正常工作的 Flutter 后台服务

使用 Flutter 插件和地理围栏在后台执行 Dart

于 2020-08-20T05:53:04.380 回答
0

你可以通过注册一个 Dart 回调函数在后台启动 Flutter 引擎,该回调函数只会在 Flutter 中启动后台作业时调用。

尝试这个。 https://medium.com/vrt-digital-studio/flutter-workmanager-81e0cfbd6f6e

于 2020-08-13T09:28:58.277 回答