0% found this document useful (0 votes)
5 views8 pages

Android ch-6

Uploaded by

prateekvipin7278
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views8 pages

Android ch-6

Uploaded by

prateekvipin7278
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Chapter – 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.

All threading components belong to one of two basic categories.


 The fragment or activity attached threads: This category of threads are bound to the lifecycle
of the activity/fragment and these are terminated as soon as the activity/fragment is destroyed.
Thread components: AsyncTask, Loaders.

 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.

Life Cycle of a Thread


Thread can be in one of the five states which forms life cycle of the Thread. This life cycle of a
thread is controlled by java virtual machine (JVM).

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.

Running User Interface Thread in Android


User Interface Thread or UI-Thread in Android is a Thread element responsible for updating
the layout elements of the application implicitly or explicitly. This means, that to update an
element or change its attributes in the application layout ie the front-end of the application, one
can make use of the UI-Thread.
Realizing UI Thread:
For example, a thread action is started, and the developer wants to update the front-end element
with respect to the thread elements, the runOnUIThread{…} function can be used.

Handlers, Loopers, MessageQueue Basics

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

Android Web Services


A web service is basically required to provide interoperability, i.e. connecting various
applications. It allows different apps to communicate with each other and share the data and
services among themselves. Web services provide a standard for all the types of client
applications to invoke functions on every type of app server.

Android Web Services Components


a. Publisher: The publisher can be understood as a Service provider. The publisher is
responsible for creating the web service and making it available for the Clients.
b. Subscriber: The Subscriber is nothing but, the service requester. The Service requester is the
one that needs to contact the web service. The client application will contact through a client
application. This Client application can be based on .Net or any language based language.
c. Broker: The broker here is the application that provides access to the UDDI. The UDDI
stands for User descriptive, discovery and integration. It enables the client application to locate
the web service exactly.

The services that do are as follows:


a. Publish: Publishers Publishing the web services means informing the broker about its
existence. It is done using the Broker’s interface to make is easily accessible to the subscribers
b. Subscribe: The Subscriber will consult the broker to locate the published web service easily .
c. Bind: Once the information regarding the web services is gained from the broker, the
subscriber can bind the web service.

Characteristics of Web Services in Android


Before knowing more about web-services, we’ll understand some of the behavioral
characteristics.
1. Web services are XML – based. They use it at its data representational layer and its
transportational layer as it removes networking, operating system or even the platform binding.
These services are highly interoperable at their core level.
2. Web services are loosely coupled. That means the consumer web services and providers of
web service are not tied together directly.
3. Web services have the ability to be either Synchronous or Asynchronous. Here Synchronous
can be understood as binding the client to the execution of the service. On the other hand,
Asynchronous refers to allowing the client to invoke a service first and later executing the other
functions.
4. Web Services supports Remote Procedure Calls. Remote Procedure calls can often be referred
to as RPCs. These RPCs let the clients invoke various functions, methods, and services on
remote objects using XML.
5. There is support to Document exchange in Web Services. In fact, XML has a very generic way
to represent data as well as complex documents. Along with that, it has got various ways to
represent these documents.

Types of Web Services in Android


There are various types of Web Services as below:
1. XML-RPC: In XML-RPC, RPC stands for remote procedure calls. It is an XML based
protocol for the exchange of data between a huge range of devices over the internet.
2. UDDI: UDDI stands for Universal Descriptive, discovery, and integration. It is an XML-
based standard used for detailing, publishing and discovering new web services.
3. SOAP: SOAP here stands for Simple object access protocol. It is an XML based web service
protocol used for the exchange of data or documents over HTTP(Hypertext transfer protocol) or
SMTP(Simple Message Transfer Protocol). It allows the communication of independent
processes that operate on disparate systems.
4. REST: Here, REST is Representational State Transfer. It provides communication and
connectivity between devices and the internet.

Advantages of Web Services


 Web services enable interoperability among different Applications.
 One of the very important advantages of using web services is Reusability.
 Web services offer faster communications within and across applications and
organizations.
 They use a quality industry-standard protocol to enable communication between different
applications.
 They use SOAP over HTTP to enable the use of low-cost internet for implementing web
services.
 Web Services are deployed over the standard internet technologies.
 They allow us to expose the functions of the existing code over the internet.

Android Web Services Limitations


 Web services do not access from the browser.
 They don’t leverage emerging Web developments
 The HTTP protocol used by web services is not reliable and is insecure.

JSON(JavaScript object Annotation)


It is not a programming language, it s a data interchange format. JSON is mostly used to get and
post the data in web services. it is the mostly used format in today's application development.
It is a file in which data is written in text format.
Data types of JSON
String - "C-sharp Corner"
numbers - 1,2,-1,-2
Boolean - true,false
Array - ["java","python","HTML"] or [2,6,-1]
object - { "key1" : "value1", "key2": "value2"}

Client side consuming web services


There are two widely used methods of invoking and consuming web services

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).

You might also like