简体   繁体   中英

Handler or runOnUiThread solution for “Can't create handler inside thread that has not called Looper.prepare() ”

Recently, I show up a toast in user thread and got the above runtime error.

From Can't create handler inside thread that has not called Looper.prepare() , they proposed use Handler as solution. However, I saw the solution is quite lengthy and cumbersome.

My own solution is to use runOnUiThread

private void showTooDarkToastMessage()
{
    ((Activity) this.getContext()).runOnUiThread(new Runnable() {
        @Override
        public void run() {
            Toast toast = Toast.makeText(getContext(), getResources().getString(R.string.toast_toodark), Toast.LENGTH_LONG);
            toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
            toast.show();
        }
    });        
}

I was wondering, is there any shortcoming of using runOnUiThread , compared to Handler ?

Because you are showing a UI element (a Toast message) runOnUiThread is perfect.

A Handler will run its task on the specified thread. For instance,

     protected void onCreate( Bundle savedInstanceState )
     {
        Handler hander = new Handler();
        //Create thread, post to handler
     }

would create a new Handler that would run its posts on the UI thread. calling Activiy.runOnUiThread just posts the runnable specifically to the UI thread. By default, Handlers will run on whatever thread they were created in. The above code would work identical to using runOnUiThread because the onCreate method is run on the UI thread!

  • Handlers would be preferred if you needed to communicate between multiple background threads.

  • Because mobile devices have limited resources, work run on the UI thread should be kept relatively light. Intense work done on the UI thread can cause Application Not Responding (ANR) errors and can cause the OS to kill your process.

Actually runOnUiThread() using Handler inside. So, there is no downsides to use runOnUiThread() if you want to simple post some job to do in the UI Thread.

If you are interesting in difference between Handler and runOnUiThread() you can read about it in this answer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM