如何在后台运行自定义平台特定的代码?

时间:2020-02-06 00:01:35

标签: java flutter

当我执行繁重的代码执行时。整个Flutter界面都会冻结。如何使该过程异步?

@Override
public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
    GeneratedPluginRegistrant.registerWith(flutterEngine);

    MethodChannel methodChannel = new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL);
    methodChannel.setMethodCallHandler(
            (call, result) -> {
                try {
                    //Emulate HardWork
                    TimeUnit.SECONDS.sleep(5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                result.success("HardWork Result");
            }
    );
}

我尝试创建一个线程,但是结果在它结束之前被破坏了,应用程序崩溃了

public class MainActivity extends FlutterActivity {
    private static final String CHANNEL = "test/channel";

    @Override
    public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
        GeneratedPluginRegistrant.registerWith(flutterEngine);

        MethodChannel methodChannel = new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL);
        methodChannel.setMethodCallHandler(
                (call, result) -> new Thread(new MyRunnable(result)).start()
        );
    }
}

class MyRunnable implements Runnable {
    private MethodChannel.Result result;

    MyRunnable(MethodChannel.Result result) {
        this.result = result;
    }

    public void run() {
        try {
            //Emulate HardWork
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        result.success("HardWork Result");
    }
}

invoke的实现,在Flutter端等待结果

class _MyHomePageState extends State<MyHomePage> {
  static const platform = const MethodChannel(CHANNEL);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CircularProgressIndicator(),
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          String response = await platform.invokeMethod("hardWork");
          print(response);
        },
      ),
    );
  }
}

1 个答案:

答案 0 :(得分:1)

您必须在UI线程上回复,请参见:https://flutter.dev/docs/development/platform-integration/platform-channels#jumping-to-the-ui-thread-in-android

new Handler(Looper.getMainLooper()).post(new Runnable() {
  @Override
  public void run() {
    result.success("HardWork Result");
  }
});