Android how to runOnUiThread in other class?

后端 未结 6 1950
再見小時候
再見小時候 2020-11-28 08:22

In my application, in MainActivity, there is a thread which works fine. But when I call another class to get data from the server I can\'t run on a thread. See code exampl

6条回答
  •  醉话见心
    2020-11-28 09:04

    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);
        }  
    }
    

提交回复
热议问题