Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Access Main ui from background thread in android

    • 0
    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 512
    Comment on it

    We know that in android only main thread can touch the UI but there are some severals methods that can touch the UI from background thread that are following as :

    1. Handler

    2. PostDelayed

    3. RunOnUIThread

    4. AsyncTask

    1. Handler is basically used to access main ui from background thread, with handler we obtain a message from background thread and we handle this message in main ui thread where we can access or touch main ui easily.

    Example :

    Thread thread = new Thread() {
        @Override
        public void run(){
            // some background work here in this thread.
            if(succeed){
                h.sendEmptyMessage(0);
            }else{
                h.sendEmptyMessage(1);
            }
        }
    };
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg){
            if(msg.what == 0){
                updateUI();
            }else{
                // show some dialog or toast
            }
        }
    };

     

    2. Post Delayed method add the runnable into message queue that is to be run after specified period of time. Runnable will be run on the thread to which this handler is attached.

    boolean postDelayed(Runnable r, long time)

    -> This method return true if runnable successfully added into the message queue.

    -> This method return false if message queue is exiting.

    -> If user exit the app by pressing back button then looper will also exit and so postDelayed will also exit and will return false.

    Example :

    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
    @Override
    public void run() {
            btn1.setBackgroundColor(Color.BLACK);
            }
            }, 2000);

    3. runOnUiThread to run something on ui main thread.

    Example :

    runOnUiThread(new Runnable() {
    
        @Override
        public void run() {
            btn.setText(run on ui thread);
        }
    });

    4. AsyncTask used to perform action on ui thread by using onPre , onPost execute method and work in background using doInBackground method of this class.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: