Running a method on UI thread

2019-09-08 00:10发布

My question seems very simple but i can't seem to the logic right. Am trying to run methods from other classes using the UI thread. I could do this this simply by wrapping my methods like this

    runOnUiThread(new Runnable() {
    public void run() {
        Log.d("UI thread", "I am the UI thread");
           ui.myMethod("changetext");
    }
});

but my goal is to have a class that wraps methods to be run on the UI thread as having runOnUiThread() almost 5 times in a single class seems very untidy. Any pointers?

2条回答
爷、活的狠高调
2楼-- · 2019-09-08 00:44

If you really have to do this from multiple classes, you could create a public static method that will run a runnable on the main thread. Something like this:

public class Util {
    public static void runOnUI(Activity a, Runnable r){
        a.runOnUIThread(r);
    }
}

You call it by doing something like this:

Util.runOnUI(getActivity(), mRunnable);
查看更多
forever°为你锁心
3楼-- · 2019-09-08 00:48

If you're calling the same UI method repeatedly, you could streamline the client code by creating the Runnable in a method:

private void updateUi(final String message) {
   runOnUiThread(new Runnable() {
      public void run() {
         ui.myMethod(message);
      }
   });
}

Then your client code would simply call updateUi("changetext"). (This code assumes that ui is final. If not, you could pass in a final reference.)

If you're calling a different UI method every time, this doesn't gain you anything as you'd need a separate update method for each UI method. Your existing code is as elegant as it gets.

查看更多
登录 后发表回答