how to wait for Android runOnUiThread to be finished?

后端 未结 7 1945
予麋鹿
予麋鹿 2020-12-29 00:58

I have a worker thread that creates a runnable object and calls runOnUiThread on it, because it deals with Views and controls. I\'d like to use the result of the work of the

7条回答
  •  余生分开走
    2020-12-29 01:38

    A solution might be to leverage Java's FutureTask which has the benefit that someone else has already dealt with all the potential concurrency issues for you:

    public void sample(Activity activity) throws ExecutionException, InterruptedException {
        Callable callable = new Callable() {
            @Override
            public Void call() throws Exception {
                // Your task here
                return null;
            }
        };
    
        FutureTask task = new FutureTask<>(callable);
        activity.runOnUiThread(task);
        task.get(); // Blocks
    }
    

    You can even return a result from the main thread by replacing Void with something else.

提交回复
热议问题