Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • What is main and background thread and how to touch ui from background thread ?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 337
    Comment on it

    Multithreading is  a meachanism where a one user can access more than one process or you can say that an operating system can perform more than one operations simultaneously.

    In Android we have two types of thread that are Main thread and background thread.

    Main thread is one that modifies the UI and handles input events from one single thread but background thread is one that can't touch the main UI directly.

    Android collects all the input events in a Queue and process them as an instance of looper class.

    Here is an example of Main thread operations :

    someButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
    
            someButton.setText("Main thread");
    
        }
    });

     

    But how can we touch this button from a background thread ?

    To touch main ui from background thread we have many ways to do that are :

    1. postDelayed() method

    2. Handler

    3. runOnUIThread() method

    4. AsyncTask

    Example of AsyncTask to touch main ui :

    private class MyAsyncTask extends AsyncTask<url, Integer, Long> {
        protected Long doInBackground(url... urls) {
        // Runs in background thread
        }
    
        protected void onProgressUpdate(Integer... progress) {
            setProgressPercent(progress[0]);
        // Runs in Main thread
        }
    
        protected void onPostExecute(Long result) {
         someButton.setText("Main thread from asyncTask");
        // Runs in Main thread so you can touch ui here
        }
    }

     

 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: