Bolts框架:onSuccess在UI / Main线程上进行更改

时间:2019-04-12 09:09:56

标签: android android-asynctask bolts-framework

一旦Task callInBackground执行完成,是否可以在UI线程上显示消息或进行更改?

类似以下内容:

Task.callInBackground(new Callable<String>() {
            @Override
            public String call() {


                for(int i=0; i<3; i++){
                    Log.i("I=", String.valueOf(i));

                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                String obj = "";
                return null;
            }
        }).onSuccess(new Continuation<String, Object>() {
            @Override
            public Object then(Task<String> task) throws Exception {
                Log.i("I=", "Counter complete");

                Toast.makeText(MainLoanMemberActivity.this, "Finished", Toast.LENGTH_SHORT).show();
                btnAgriLoan.setText("LOL");
                return null;
            }
        });

目前,没有显示Toast消息,也没有崩溃。

在Bolts Framework中寻找AsyncTask的onPostExecute的等效项,可以在其中向UI添加更改。

1 个答案:

答案 0 :(得分:0)

没有意识到您可以在每个帮助器函数中提及诸如EXECUTOR的类型,例如:(Task.UI_THREAD_EXECUTOR)

Task.callInBackground(new Callable<String>() {
            @Override
            public String call() {
                for(int i=0; i<3; i++){
                    Log.i("I=", String.valueOf(i));
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                String obj = "";
                return null;
            }
        }).onSuccess(new Continuation<String, Void>() {
            public Void then(Task<String> object) throws Exception {
                Toast.makeText(MainLoanMemberActivity.this, "Finished", Toast.LENGTH_SHORT).show();
                btnAgriLoan.setText("LOL");
                return null;
            }
        }, Task.UI_THREAD_EXECUTOR);

文档帮助了!