可调用和未来延迟android主线程

问题描述 投票:0回答:1

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

@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被frizzed直到所有任务都关闭,然后交易失败。这不是我第一次遇到这个问题。每次我使用callable和executor服务时我都不知道为什么用户界面会被frizzed !!!!

这是探查器:

enter image description here

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

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

android future callable
1个回答
1
投票

这是因为你在execute()方法返回的未来上调用了get()。根据文件,

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

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

为了避免用户界面,你应该使用回调。

© www.soinside.com 2019 - 2024. All rights reserved.