Running code in main thread from another thread

前端 未结 16 2074
一个人的身影
一个人的身影 2020-11-22 13:50

In an android service I have created thread(s) for doing some background task.

I have a situation where a thread needs to post certain task on main thread\'s message

16条回答
  •  遥遥无期
    2020-11-22 14:31

    Follow this method. Using this way you can simply update the UI from a background thread. runOnUiThread work on the main(UI) thread . I think this code snippet is less complex and easy, especially for beginners.

    AsyncTask.execute(new Runnable() {
                @Override
                public void run() {
    
                //code you want to run on the background
                someCode();
    
               //the code you want to run on main thread
     MainActivity.this.runOnUiThread(new Runnable() {
    
                        public void run() {
    
    /*the code you want to run after the background operation otherwise they will executed earlier and give you an error*/
                            executeAfterOperation();
    
                       }
                    });
                }
            });
    

    in the case of a service

    create a handler in the oncreate

     handler = new Handler();
    

    then use it like this

     private void runOnUiThread(Runnable runnable) {
            handler.post(runnable);
        }
    

提交回复
热议问题