Android ch-6
Android ch-6
Threads in Android
Thread is one of the important concepts in Android. Thread is a lightweight sub-process that
provides us a way to do background operations without interrupting the User Interface (UI).
When an app is launched, it creates a single thread in which all app components will run by
default. The thread which is created by the runtime system is known as the main thread. The
main thread’s primary role is to handle the UI in terms of event handling and interaction with
views in the UI. If there is a task that is time-consuming and that task is run on the main thread,
then it will stop other tasks until it gets completed, which in turn may result in displaying a
warning “Application is unresponsive” to the user by the operating system. So we need different
threads for such tasks and some other tasks.
The fragment or activity not attached threads: These types of threads can continue to run
beyond the lifetime of the activity or fragment from which they were spawned.
Threading Components: Service, Intent Service.
Types of threads
There are five types of thread used in Android mobile development.
Main Thread: When we launch our app on Android, it creates the first thread of execution
called the “Main Thread”. The communication between the components from the Android UI
toolkit and the dispatching of events to their appropriate UI widgets is handled by the main
thread. We should avoid network operations, database calls, and the loading of certain
components in the main thread. Because the main thread is called synchronously when executed,
that means the user interface will remain completely unresponsive until the performance
completes.
UI Thread: Every app in Android has its own thread which is responsible for running the UI
objects, like view objects. Such a thread is known as the UI thread. The UI thread is the main
thread of execution for our app as this is where most of the app code is run. The UI thread is
where all of our app components (like activities, services, content providers, and broadcast
receivers) are created. This thread allows our tasks to perform their background work and then
move the results to UI elements such as bitmaps. All objects running on our UI thread will be
able to access other objects which are also running on the same UI thread. The tasks that we run
on a thread from a thread pool do not run on our UI thread, so they will not have access to UI
objects. The data moves from a background thread to the UI thread, using a handler that runs on
the UI thread.
Worker Thread: The worker thread is a background thread. The worker threads are created
separately, other than threads like the UI thread. As we know from the rules, we cannot block a
UI thread so this is where the worker thread comes into play since we can use them to run the
child processes and tasks.
Any Thread:
In Any thread, the annotated method can be called from any thread. If the annotated element is a
class, then all methods in the class can be called from Any Thread.
Binder Thread: Binder thread represents a separate thread of service. The binder is a
mechanism that provides inter-process communication. The binder thread is used in service
binding with interprocess communication. This concept is mainly related to service calls with
interfaces defined by Android Interface Definition Language (AIDL).
Thread classes
AsyncTask: Helps get work on/off the UI thread.
HandlerThread: Thread for callback
ThreadPoolExecutor: Running lots of parallel work.
IntentService: Helps get intents off the UI thread.
1. New: In this stage thread is referred to as a born thread. A new thread starts its life cycle in
this stage. The thread remains in this thread until programs starts the thread.
2. Runnable: After a newly born thread is started , the thread comes in this stage which is
referred to as runnable. The thread comes into this stage after calling start() method, Thread
scheduler sets it to be runnable.
3. Running: Thread is in running stage only when Thread Scheduler has selected it. It executes
all the tasks assigned to it in this stage.
4. Non-Runnable (Blocked): In this stage, Thread is still alive but it is not eligible to run due to
some condition. In this stage thread is referred to be in waiting stage.
5. Terminated: Thread is terminated when its run() method exists. In this stage thread is referred
as Dead thread.
Handler Threads:
These are the threads that can receive messages from any other thread. Main/UI thread is also a
Handler thread. As explained above, such a thread must need a Message Queue(data structure in
which other threads can write to), and a mechanism to read this queue infinitely(until stopped).
Looper is a mechanism which loops through the message Queue infinitely until stopped.
Message Queue
Each HandlerThread has one Message Queue into which other threads write data to(via Handlers),
and it has a Looper which keeps on reading from it.
Looper:
A Looper is associated with every handler Thread and a Message Queue.
It keeps on reading the MessageQueue for any new Messages, and once it reads a message it will
delegate that to the corresponding Callback(Handler).
Handler:
The handler is the exposed API to work with Loopers/MessageQueues. It basically exposes
methods to interact with the Looper architecture, like writing messages to MQ, Setting callbacks
to handle the message once Looper reads it, etc, etc.
So Each handler will need a Looper (so that it knows in which MQ to write data to since Looper
has the reference to the MQ).
Message:
The Messages which can be sent to the HandlerThread. To avoid the number of Messages
initializes, there is a pool maintained. Every time the looper is stopped, or the message is read by
Looper, it is recycled(i.e. its fields are cleared off), and added to the pool. Next time we want to
create a new Message, we get it from the pool (Message.obtain() method does that). This way the
Android prevents us to initialize new Message instances every time.
Runnable
Runnable interface is the primary template for any object that is intended to be executed by a
thread. It defines a single method run(), which is meant to contain the code that is executed by
the thread.
Any class whose instance needs to be executed by a thread should implement
the Runnable interface. The Thread class itself implements Runnable with an empty
implementation of run() method.
AsyncTask
AsyncTask (asynchronous task) is an Android class that makes it easier to do operations on a
background thread and publish the result on the User Interface (UI)/ main thread without having
to manipulate threads and handlers ourselves.
In Android, updating a UI from a separate thread is a frequently encountered scenario. It’s so
frequent that Android provides ready to use API for such kinds of scenarios. AsyncTask is
basically an API.
The basic methods used in an android AsyncTask class are defined below :
>onPreExecute()- This part of the method gets executed on the main thread. Before doing a
background operation you should show something on-screen like a progress bar or an animation
to the user.
>doInBackground(Params)- This method is used to do background operations on the
background thread. Operations in doInBackground() method should not touch on any main
thread activities or fragments.
>onProgressUpdate(Progress…)- This method receives progress updates from the
doInBackground method and runs on the UI thread. This method is used to display progress bars
in the UI.
>onPostExecute(Result)- In this method you can update the UI of the background operation
result.
The three generic types used in an android AsyncTask class are given below :
Params : The type of the parameters sent to the task upon execution
Progress : The type of the progress units published during the background computation
Result : The type of the result of the background computation
REST APIs: It stands for Representational State Transfer (REST) is an architectural style that
defines a set of constraints and protocols to be used for creating web services. REST API is a
method of accessing web services in a very simple and flexible manner without having any
processing. A REST API endpoint is a URL that utilizes HTTP verbs to execute CRUD (Create
Read Update Delete) operations over the resources. These HTTP verbs are GET, POST,
PATCH, PUT and DELETE. It focuses on providing resources from the server to the clients.
RPC APIs: Remote Procedure Call (RPC) is a methodology used for constructing distributed,
client-server-based applications. It is also called a subroutine call or a function call. It is based on
conventional local procedure calling so that the called procedure need not exist in the very same
address space as the calling procedure executes. RPC is very well suited for a client-server
interaction in which the flow of control lingers between the two. The client and server do not
both execute at the same time instead the thread of execution jumps from one to another.
Restful Web service Call And Get And Parse JSON Data
Calling restful web service to get JSON data and parse that JSON data.
Steps :
1. Call php file (php) from server and create JSON data in php.
2. Consume JSON data by android and show on activity.
3. Parse JSON data and Show parsed data on screen(activity).