Android - howto pass data to the Runnable in runOnUiThread?

前端 未结 6 2356
慢半拍i
慢半拍i 2020-12-08 10:30

I need to update some UI and do it inside of the UI thread by using runOnUiThread
Now the data for the UI comes from the other Thread, represented by

6条回答
  •  孤城傲影
    2020-12-08 10:39

    Here is a typical case where service callback is called to update a UI status string (TextView textStatus). The service may be threaded.

    The sample combines checking if thread redirection is needed and the actual redirection:

       // service callbacks
        public void service_StatusTextChanged(final String s) {
            if( isOnUiThread() ) {
                textStatus.setText(s);
            } else {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        textStatus.setText(s);
                    }
                });
            }
        }
    
        static public boolean isOnUiThread() {
           return Thread.currentThread() == Looper.getMainLooper().getThread();
        }
    

    See also How to check if running on UI thread in Android?

提交回复
热议问题