Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android basics: running code in the UI thread

In the viewpoint of running code in the UI thread, is there any difference between:

MainActivity.this.runOnUiThread(new Runnable() {     public void run() {         Log.d("UI thread", "I am the UI thread");     } }); 

or

MainActivity.this.myView.post(new Runnable() {     public void run() {         Log.d("UI thread", "I am the UI thread");     } }); 

and

private class BackgroundTask extends AsyncTask<String, Void, Bitmap> {     protected void onPostExecute(Bitmap result) {         Log.d("UI thread", "I am the UI thread");     } } 
like image 437
Luky Avatar asked Oct 11 '12 23:10

Luky


People also ask

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

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.

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.


2 Answers

None of those are precisely the same, though they will all have the same net effect.

The difference between the first and the second is that if you happen to be on the main application thread when executing the code, the first one (runOnUiThread()) will execute the Runnable immediately. The second one (post()) always puts the Runnable at the end of the event queue, even if you are already on the main application thread.

The third one, assuming you create and execute an instance of BackgroundTask, will waste a lot of time grabbing a thread out of the thread pool, to execute a default no-op doInBackground(), before eventually doing what amounts to a post(). This is by far the least efficient of the three. Use AsyncTask if you actually have work to do in a background thread, not just for the use of onPostExecute().

like image 117
CommonsWare Avatar answered Sep 29 '22 21:09

CommonsWare


I like the one from HPP comment, it can be used anywhere without any parameter:

new Handler(Looper.getMainLooper()).post(new Runnable() {     @Override     public void run() {         Log.d("UI thread", "I am the UI thread");     } }); 
like image 22
pomber Avatar answered Sep 29 '22 22:09

pomber