Update the UI outside the main thread

后端 未结 5 1155
梦谈多话
梦谈多话 2021-01-17 01:21

I am totaly new to android and just want to know if it is any working and possible way to update the UI outside the main thread. Just from my code I have listed below I know

相关标签:
5条回答
  • 2021-01-17 01:44

    Use activity.runOnUiThread

    Acivity.runOnUiThread(new Runnable() {
        public void run() {
            //something here
        }
    });
    
    0 讨论(0)
  • 2021-01-17 01:48

    You can't update UI directly from non-UI thread, but You could communicate with UI thread using Handler object or AsyncTask object. The most convinient way to use AsyncTask:

    1. .doInBackground() method of AsyncTask runs in non-ui thread
    2. .onProgressUpdate() runs in UI thread so could change views
    3. You could use publishProgress() method inside doInBackground() to pass data to .onProgressUpdate.

    Sorry if some mistakes in method names. Read http://developer.android.com/guide/components/processes-and-threads.html for details.

    0 讨论(0)
  • 2021-01-17 01:50

    you have to use an Handler instance and use the post method do add a Runnable inside the queue of the UI Thread. If you are inside an Activity you can use runOnUiThread that is a "shortcut" to do the same thing

    0 讨论(0)
  • 2021-01-17 01:53

    Only main thread can update UI. If your thread want to update UI, use activity.runOnUiThread()

    However your action is just queued to run in UI thread(if you are running it not from UI thread), which mean it can update UI a little bit later.

    http://developer.android.com/reference/android/app/Activity.html#runOnUiThread(java.lang.Runnable)

    0 讨论(0)
  • 2021-01-17 02:07

    A worker thread never can update main thread because only main thread can render the UI elements (TextView, EditText etc.) and if we try to update for sure we are going to an exception.

    myAcitity.runOnUiThread(new Runnable() {
        public void run() {
            //here you can update your UI elements because this code is going to executed by main thread
        }
    });
    

    Otherwise you can use post method of View class

    myView.post(new Runnable() {
            public void run() {
                //here you can update your UI elements because this code is going to executed by main thread
            }
        });
    
    0 讨论(0)
提交回复
热议问题