Android how to runOnUiThread in other class? Android how to runOnUiThread in other class? android android

Android how to runOnUiThread in other class?


See the article Communicating with the UI Thread.

With Context in hand, you can create a Handler in any class. Otherwise, you can call Looper.getMainLooper(), either way, you get the Main UI thread.

For example:

class CheckData{    private final Handler handler;    public Checkdata(Context context){       handler = new Handler(context.getMainLooper());    }     public void someMethod() {       // Do work       runOnUiThread(new Runnable() {           @Override           public void run() {               // Code to run on UI thread           }       });    }    private void runOnUiThread(Runnable r) {       handler.post(r);    }  }


Here's a solution if you don't want to pass the context:

new Handler(Looper.getMainLooper()).post(new Runnable() {    public void run() {        // code goes here    }});


Activity is a class that extends Context. So there is no need to pass both context and activity. You may pass activity as context and then you can use the context to run on UI thread as follows:

((Activity) context).runOnUiThread(new Runnable() {        public void run() {            //Code goes here        }    });

Word of Caution: Only use this when you're sure that context is an activity context, and it's not a good practice to assume that.