Android - howto pass data to the Runnable in runOnUiThread?

前端 未结 6 2341
慢半拍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:43

    The problem you found is that

    Inner classes in Java capture ("close over") the lexical scope in which they are defined. But they only capture variables that are declared "final".

    If this is clear as mud, there's a good discussion of the details here: Cannot refer to a non-final variable inside an inner class defined in a different method

    But your solution looks fine. In addition, provided that data is final, you could simplify the code to this:

    public void OnNewSensorData(final Data data) {
        runOnUiThread(new Runnable() {
            public void run() {
                // use data here
                data.doSomething();
            }
        });
    }
    

提交回复
热议问题