如何在后台使用 Flutter Method Channel(应用最小化/关闭)

Sha*_*hmi 5 android dart flutter flutter-plugin flutter-method-channel

我正在 Flutter 应用程序中开发本机 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()
        }
})
Run Code Online (Sandbox Code Playgroud)

/// 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');
      }
    });
}
Run Code Online (Sandbox Code Playgroud)

Jup*_*han 0

您可以通过注册 Dart 回调函数在后台启动 Flutter 引擎,该回调函数仅在 Flutter 中启动后台作业时才会被调用。

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