Android在子线程更新UI主线程的6种方法

效果描述:

点击按钮后,按钮切换为不可点击状态,6个任务依次执行(线程池实现),待6个任务全部执行完成之后,按钮状态切换可用,可在此执行前述操作。

 

public class UpgradeUI implements Runnable {    // 调用任务进度    protected void onProgress(int value){    }    // 任务结束调用    protected void onFinish(Object ... args){    }    @Override    public void run() {        int i=0;        while(i<100){            i++;            try {                // 模拟任务耗时                Thread.sleep(20);            } catch (InterruptedException e) {                e.printStackTrace();            }            // 通知任务进度            onProgress(i);        }        // 通知任务结束        onFinish();    }}
public class TestSubThreadActivity extends AppCompatActivity {    private static final String TAG = "TestSubThreadActivity";    private EditText editText;    private ProgressBar progressBar;    private LinearLayout lp;    int index = 0;    static CountDownLatch countDownLatch = new CountDownLatch(6);    // 使用handler更新UI    Handler handler = new Handler() {        @Override        public void handleMessage(@NonNull Message msg) {            progressBar.setProgress(msg.arg1);        }    };    // handler message    UpgradeUI upgradeUI = new UpgradeUI() {        @Override        protected void onFinish(Object... args) {            countDownLatch.countDown();        }        @Override        protected void onProgress(int value) {            Message message = new Message();            message.arg1 = value;            handler.sendMessage(message);        }    };    // 使用runOnUiThread    UpgradeUI upgradeUI1 = new UpgradeUI() {        @Override        protected void onFinish(Object... args) {            countDownLatch.countDown();        }        @Override        protected void onProgress(int value) {            runOnUiThread(new Runnable() {                @Override                public void run() {                    progressBar.setProgress(value);                    editText.setText("使用runOnUiThread");                }            });        }    };    // 使用rhandler.post    UpgradeUI upgradeUI2 = new UpgradeUI() {        @Override        protected void onProgress(int value) {            handler.post(new Runnable() {                @Override                public void run() {                    progressBar.setProgress(value);                    editText.setText("使用rhandler.post");                }            });        }        @Override        protected void onFinish(Object... args) {            countDownLatch.countDown();        }    };    // 使用handler postDelay延时1s更新    UpgradeUI upgradeUI3 = new UpgradeUI() {        @Override        protected void onFinish(Object... args) {            countDownLatch.countDown();        }        @Override        protected void onProgress(int value) {            handler.postDelayed(new Runnable() {                @Override                public void run() {                    progressBar.setProgress(value);                    editText.setText("使用handler postDelay延时1s更新");                }            }, 1000);        }    };    // 通过view.post    UpgradeUI upgradeUI4 = new UpgradeUI() {        @Override        protected void onFinish(Object... args) {            countDownLatch.countDown();        }        @Override        protected void onProgress(int value) {            progressBar.post(new Runnable() {                @Override                public void run() {                    progressBar.setProgress(value);                    editText.setText("通过view.post");                }            });        }    };    // by syncTask    UpgradeUI upgradeUI5 = new UpgradeUI() {        @Override        protected void onFinish(Object... args) {            countDownLatch.countDown();        }        @Override        protected void onProgress(int value) {            AsyncTask asyncTask = new AsyncTask() {                @Override                protected Object doInBackground(Object[] objects) {                    return null;                }                @Override                protected void onPostExecute(Object o) {                    progressBar.setProgress(value);                    editText.setText("by syncTask");                    super.onPostExecute(o);                }            }.executeOnExecutor(executor);        }    };    // 线程池,每次执行一个线程,可设置    Executor executor = Executors.newSingleThreadExecutor();    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_test_sub_thread);        Toolbar toolbar = findViewById(R.id.toolbar);        setSupportActionBar(toolbar);        editText = findViewById(R.id.editText);        progressBar = findViewById(R.id.progressBar);        lp = findViewById(R.id.lp);//        progressBar.animate().start();        FloatingActionButton fab = findViewById(R.id.fab);        fab.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)                        .setAction("Action", null).show();            }        });    }    public void confirm(View view) {        // 设置按钮不可点击        view.setClickable(false);        editText.setText("handle message!");        executor.execute(upgradeUI);        executor.execute(upgradeUI1);        executor.execute(upgradeUI2);        executor.execute(upgradeUI3);        executor.execute(upgradeUI4);        executor.execute(upgradeUI5);        // 所有的更新UI线程执行结束,按钮恢复点击        new AsyncTask(){            @Override            protected Object doInBackground(Object... objects) {                try {                    countDownLatch.await();                } catch (InterruptedException e) {                    e.printStackTrace();                }                return null;            }            @Override            protected void onPostExecute(Object o) {                super.onPostExecute(o);                view.setClickable(true);            }        }.execute();    }}