Showing posts with label Thread. Show all posts
Showing posts with label Thread. Show all posts

Processes and Threads in Android

Start

What is runOnUiThread in android? when we used this?

When you explicitly spawn a new thread to do work in the background, this code is not is not run on the UIThread. So what happens if the this background thread needs to do something that changes the UI? 
This is what the runOnUiThread is for. it provides these background threads the ability to execute code that can modify the UI.

what is UIthread in android?

The UIThread is the main thread of execution for your application. This is where most of your application code is run. All of your application components(Activities, Services, ContentProviders, BroadcastReceivers) are created in this thread, and any system calls to As for example in a  single Activity class. Then all of the life cycle methods and most of your event handling code is run in this UIThread. These are methods like OnCreate, OnPause, OnDestroy,OnClick, etc. Additionally, this is where all of the updates to the UI are made. Anything that causes the UI to be updated or changed has to happen on the UI thread.

What is AsyncTask in android?

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

In order to use the AsyncTask class, you must extendit and override at least the doInBackground()method. 

AsyncTask have 4 methods 

1)  onPreExecute() 
2) doInBackground(Params…)
3) onProgressUpdate()
4) onPostExecute(Result) 

 1. onPreExecute() – called on the UI thread before the thread starts running. This method is usually used to setup the task, for example by displaying a progress bar.

   2. doInBackground(Params…) – this is the method that runs on the background thread. In this method you should put all the code you want the application to perform in background. The doInBackground() is called immediately after onPreExecute(). When it finishes, it sends the result to the onPostExecute().

   3. onProgressUpdate() - called when you invoke publishProgress() in the doInBackground().

   4. onPostExecute(Result) – called on the UI thread after the background thread finishes. It takes as parameter the result received from doInBackground().

AsyncTask is a generic class, it uses 3 types:AsyncTask<Params, Progress, Result>.

Params – the input. what you pass to the AsyncTask
Progress – if you have any updates, passed to onProgressUpdate()
Result – the output. what returns doInBackground()