Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do some Android UI stuff in non-UI thread

Is there a way to do UI changes in a non-UI thread? Short question.

like image 617
Knobik Avatar asked Jun 03 '11 05:06

Knobik


People also ask

Are UI thread and main thread same in Android?

As such, the main thread is also sometimes called the UI thread. However, under special circumstances, an app's main thread might not be its UI thread; for more information, see Thread annotations. The system does not create a separate thread for each instance of a component.

Does Android service run on main thread?

Service runs in the main thread of its hosting process; the service does not create its own thread and does not run in a separate process unless you specify otherwise.

Why should you avoid to run non UI code on the main thread?

If you put long running work on the UI thread, you can get ANR errors. If you have multiple threads and put long running work on the non-UI threads, those non-UI threads can't inform the user of what is happening.

What is difference between UI thread and main thread?

UI Thread and Main Thread are same only in Android. The Main thread, that is responsible for handling the UI events like Draw, Listen and receive the UI events. Ans also it is responsible for interact with running components of the UI toolkit for the corresponding application that belongs to.


2 Answers

Either use Handler or use below code

    runOnUiThread(new Runnable()
    {           
        @Override
        public void run()
        {
            // Ui Stuff here                
        }
    });
like image 164
ingsaurabh Avatar answered Oct 22 '22 09:10

ingsaurabh


There are many way to do this, use AsyncTask or Threads. Short answer.

Hint: the UI stuff can be done in the pre-postExecute/runOnUiThread/Handler class

like image 33
Reno Avatar answered Oct 22 '22 09:10

Reno