颤振背景任务

时间:2020-04-29 12:12:04

标签: android flutter kotlin dart flutter-engine

我正在尝试在backgroung中运行任务(不响应现有的插件), 但是在第一次运行时,我收到此错误“ -32601从应用程序接收:找不到方法”

一步一步

我有一种方法,可以通过MethodChannel向本机发送一个句柄

class Backgroundtask {
  static const MethodChannel _channel = const MethodChannel('backgroundtask');

  static Future<bool> periodic({@required Function callback}) async {
    assert(callback != null, 'task cannot be null');

    CallbackHandle handle = PluginUtilities.getCallbackHandle(callback);
    if (handle == null) {
      return false;
    }

    final bool result = await _channel.invokeMethod(
      'periodic',
      <dynamic>[
        handle.toRawHandle(),
      ],
    );
    return result ?? false;
  }
}

另一方面,我启动一个WorkerManager,将handle作为Data传递。

    override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
           [...]
            val data = Data.Builder()
            data.putLong("handle", handle)

            val constrains = Constraints.Builder()
                    .setRequiredNetworkType(NetworkType.CONNECTED)
                    .build()

            val pWorkRequest = PeriodicWorkRequest
                    .Builder(CustomWorker::class.java, 15, TimeUnit.MINUTES)
                    .setInputData(data.build())
                    .setConstraints(constrains)
                    .build()

            WorkManager.getInstance(context).enqueue(pWorkRequest)
            [...]
    }

我的androidx.work.Worker.doWork()

        [...]
        Handler(Looper.getMainLooper()).post {
            Log.d("periodic", "background service start")

            val handle = inputData.getLong("handle", 0)
            val flutterEngine = FlutterEngine(context)
            val flutterCallback = FlutterCallbackInformation.lookupCallbackInformation(handle)
            if (flutterCallback.callbackName == null) {
                Log.e("periodic", "callback not found")
                return
            }

            val assets = context.assets
            val bundle = FlutterMain.findAppBundlePath()
            val executor = flutterEngine.dartExecutor
            val dartCallback = DartExecutor.DartCallback(assets, bundle, flutterCallback)

            executor.executeDartCallback(dartCallback)
            Log.d("periodic", "background service end")
        }
        [...]

执行回调后,无论执行什么操作,都会发生我的错误。 我认为这一定是我没有看到的愚蠢的东西,但是我的头坏了。

非常感谢您。

error image

0 个答案:

没有答案