首页 > 解决方案 > 可调用和未来延迟android主线程

问题描述

我想通过可调用和未来从服务中获取一些数据。这是我的代码之一:

@Override
public void getCIFilesType(Consumer<String> consumer) {
    try {
        consumer.accept(serviceExecutor.submit(() ->
                service.getCi(EsupFactory.getConfigString(SETTING_ROOT_CI) + "GetCI",
                        translator.makeCiJsonObject("PCiName", "CI_FilesType")).execute())
                .get().body().string());
    } catch (ExecutionException | InterruptedException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

我有 10 种像上面一样执行的方法。我使用 Executor 服务运行callable

ExecutorService serviceExecutor = Executors.newSingleThreadExecutor();

我是我的活动,我有一个菜单,然后单击菜单中的一项,片段是活动中的事务。所有线程任务立即onViewCreated在片段中开始:

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    presenter.getCis();
}

但是,当我单击菜单项UI时,直到所有任务都停止,然后事务就停止了。这不是我第一次遇到这个问题。每次我使用 callable 和 executor 服务时,我都不知道为什么 UI 会卷曲!!!!

这是探查器:

在此处输入图像描述

有人给我一些指导!?请不要告诉我使用 asyncTask :-)

什么是读线??在ui线程中我只是做事务而不执行长时间运行的任务!!!

标签: androidfuturecallable

解决方案


发生这种情况是因为您在execute()方法返回的未来调用get() 。根据文档,

如果您想立即阻止等待任务,可以使用 result = exec.submit(aCallable).get(); 形式的结构。

因此,即使您使用后台线程,也可以通过调用get阻塞主线程,直到后台线程完成您的任务。

为避免 UI 垃圾,您应该使用回调。


推荐阅读