How to use Flutter Method Channel in background (app minimised/closed)

老子叫甜甜 提交于 2020-08-10 19:32:37

问题


I am working on a native Android widget in a Flutter App. In which there is refresh button, on click of that I have to call a method in the Flutter code. I am using Flutter Method Channel for the communication and it is working fine when app is in foreground. But it does not work when app is minimised or closed. I get error PlatformException(NO_ACTIVITY, null, null). Below is my code.

Android (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()
        }
})

Flutter

/// 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');
      }
    });
}

来源:https://stackoverflow.com/questions/63228013/how-to-use-flutter-method-channel-in-background-app-minimised-closed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!