Android - howto pass data to the Runnable in runOnUiThread?

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

    If you want to avoid using an intermediate final variable (as described by Dan S), you can implement Runnable with an additional method to set Data:

    public class MyRunnable implements Runnable {
      private Data data;
      public void setData(Data _data) {
        this.data = _data;
      }
    
      public void run() {
        // do whatever you want with data
      }
    }
    

    You can then call the method like this:

    public void OnNewSensorData(Data data) {
      MyRunnable runnable = new MyRunnable();
      runnable.setData(data);
      runOnUiThread(runnable);
    }
    

    you could also make MyRunnable's constructor take in the Data instance as an argument:

    public class MyRunnable implements Runnable {
      private Data data;
      public MyRunnable(Data _data) {
        this.data = _data;
      }
    
      public void run() {
        ...
      }
    }
    

    and then just say runOnUiThread(new MyRunnable(data));

提交回复
热议问题