You are on page 1of 31

D20MCA11140

Section A
Ques. 1: What is meant by Android runtime?

Ans. 1: Android Runtime (ART) is an application runtime environment used by the Android operating


system. Replacing Dalvik, the process virtual machine originally used by Android, ART performs
the translation of the application's bytecode into native instructions that are later executed by the device's
runtime environment.

When we build our app and generate APK, part of that APK are .dex files. Those files contain the source
code of our app including all libraries that we used in low-level code designed for a software interpreter
— the bytecode.

When a user runs our app the bytecode written in .dex files is translated by Android Runtime into the
machine code — a set of instructions, that can be directly understood by the machine and is processed by
the CPU.

Android Runtime also manages memory and garbage collection but, to not make this article too
long I’ll focus here only on a compilation.

The compilation of the bytecode into machine code can be done using various strategies and all those
strategies have their tradeoffs. And to understand how Android Runtime works today we have to move
back in time a couple of years and first learn about Dalvik.

Android 2.2 "Froyo" brought trace-based just-in-time (JIT) compilation into Dalvik, optimizing the


execution of applications by continually profiling applications each time they run and
dynamically compiling frequently executed short segments of their bytecode into native machine code.

While Dalvik interprets the rest of application's bytecode, native execution of those short bytecode
segments, called "traces", provides significant performance improvements.[3][4]

Unlike Dalvik, ART introduces the use of ahead-of-time (AOT) compilation by compiling entire
applications into native machine code upon their installation.

By eliminating Dalvik's interpretation and trace-based JIT compilation, ART improves the overall
execution efficiency and reduces power consumption, which results in improved battery autonomy
on mobile devices.

At the same time, ART brings faster execution of applications, improved memory allocation and garbage
collection (GC) mechanisms, new applications debugging features, and more accurate high-level profiling
of applications.

1
D20MCA11140

Comparison of Dalvik and ART Architectures

2
D20MCA11140

Ques. 2: Illustrate the use of fragments in mobile applications.


Ans. 2:

According to the Android documentation, a fragment is a part of applications user interface that is bound
to an activity. Fragments have their lifecycle and layouts or UI components.

Fragments help enrich your UI design, pass data between different screens, and adapt to different device
configurations.Unlike activities, fragments are usable.

This means that they can be used to showcase different messages or functions to the user. These
functionalities or features allow you to develop more interactive applications.

Fragments also have their logic and can thus, accept and handle different events. Fragments are beneficial
since they allow code to be divided into smaller and more manageable chunks.

Fragment lifecycle

Just like activities, fragments also have a lifecycle. This component tracks the fragments in all aspects of
their lifecycle.

This includes when they are initialized, started, created, resumed, and destroyed.

A LifecycleObserver allows the developer to detect when a specific fragment is active. As a result, certain
actions can be executed. For instance, an app can display a Snackbar or Toast message.

Alternatively, callback methods can also help in the management of the fragment’s lifecycle. These
functions include onCreate, onStart, onResume, onPause, onStop, and onDestroy. The callback methods
are called depending on the fragment’s state.

Such as listed below: 

 onCreate - This method is called to initialize or add the fragment to the host activity. The layout
is also inflated in this stage. All elements initialized in this method are usually preserved
whenever the fragment is paused. 

 onStart - In this step, the fragment is visible or active. Users can interact with different UI
components. 

 onPause - The activity is paused, which causes the fragment to bear a similar state.
The onPause is called when a fragment is replaced or when the user chooses to navigate
backward. onResume - In this phase, the fragment is reactivated. 

 onStop - The fragment is stopped and the UI hidden from the user. 

 onDetach and onDestroy - All of the fragment’s instances and processes are destroyed.

3
D20MCA11140

The image below shows how the fragment lifecycle methods are classified.

4
D20MCA11140

Ques. 3: State the purpose of content providers in mobile applications.

Ans. 3: A content provider component supplies data from one application to others on request. Such
requests are handled by the methods of the ContentResolver class.

A content provider can use different ways to store its data and the data can be stored in a database, in
files, or even over a network.

Content providers let you centralize content in one place and have many different applications access it
as needed.
A content provider behaves very much like a database where you can query it, edit its content, as well as
add or delete content using insert(), update(), delete(), and query() methods. In most cases this data is
stored in an SQlite database.
A content provider is implemented as a subclass of ContentProvider class and must implement a
standard set of APIs that enable other applications to perform transactions.

Content Providers are an important component of Android. They handle the access to the central
repository and supply data from one application to another on request.

This task of handling is done by methods of ContentResolver class. So, content providers can store data in
various ways such as files, database or over the internet.

These are the four operations of content providers :

 Create: It is used for the creation of data in content providers.


 Read: It reads the data stored in the content provider.
 Update: It lets the editing in existing data in content providers.
 Delete: It deletes the existing data stored in its Storage.

5
D20MCA11140

Ques. 4: Explain the term Broadcast Reciever.


Ans. 4: A broadcast receiver (receiver) is an Android component which allows you to register for system
or application events. All registered receivers for an event are notified by the Android runtime once this
event happens.

Broadcast Receivers simply respond to broadcast messages from other applications or from the system
itself. These messages are sometime called events or intents.

For example, applications can also initiate broadcasts to let other applications know that some data has
been downloaded to the device and is available for them to use, so this is broadcast receiver who will
intercept this communication and will initiate appropriate action.

There are following two important steps to make BroadcastReceiver works for the system broadcasted
intents −
 Creating the Broadcast Receiver.
 Registering Broadcast Receiver
Broadcast in android is the system-wide events that can occur when the device starts, when a message is
received on the device or when incoming calls are received, or when a device goes to airplane mode, etc.
Broadcast Receivers are used to respond to these system-wide events.
Broadcast Receivers allow us to register for the system and application events, and when that event
happens, then the register receivers get notified. There are mainly two types of Broadcast Receivers:
 Static Broadcast Receivers: These types of Receivers are declared in the manifest file and
works even if the app is closed.
 Dynamic Broadcast Receivers: These types of receivers work only if the app is active or
minimized.
A broadcast receiver is a dormant component of the Android system. Only an Intent (for which it is
registered) can bring it into action. The Broadcast Receiver’s job is to pass a notification to the user, in
case a specific event occurs.

Using a Broadcast Receiver, applications can register for a particular event. Once the event occurs, the
system will notify all the registered applications.

6
D20MCA11140

For instance, a Broadcast receiver triggers battery Low notification that you see on your mobile screen.

Other instances caused by a Broadcast Receiver are new friend notifications, new friend feeds, new
message etc. on your Facebook app.

In fact, you see broadcast receivers at work all the time. Notifications like incoming messages, WiFi
Activated/Deactivated message etc. are all real-time announcements of what is happening in the Android
system and the applications.

7
D20MCA11140

Ques. 6: Write steps to create database in SQLite.

Ans. 6: Unlike other database management systems, there is no CREATE DATABASE command in
SQLite. In this SQLite tutorial, here is how you can create a new database:

 Open the Windows Command Line tool (cmd.exe) from the start, type “cmd” and open it.
 The “cmd” will open in the default user folder, on my machine, it is “C:\Users\MGA”:







 From the Installation and packages tutorial, you should now have created an SQLite folder in
the “C” directory and copied the sqlite3.exe on it.
 After that we should select SQLite file and navigate where the sqlite3.exe is located by the
following SQLite command line:
 Followi
n
g

is the
basic
syntax
of sqlite3 command to create a database

 If you select SQLite file and navigate to the directory: “c:\sqlite”, you will find the
file “SchoolDB.db”is created as the following screen shot:







 You can ensure that the database is created by writing following SQLite commands:










8
D20MCA11140

 You can ensure that the database is created by writing following SQLite commands:

 This will give you the list of databases created, and you should see the new database
“SchoolDB.db” listed there:

9
D20MCA11140

Ques. 7: Draw complete life cycle of a service in android.


Ans. 7: Android Services are the application components that run in the background. We can understand
it as a process that doesn’t need any direct user interaction.

As they perform long-running processes without user intervention, they have no User Interface. They can
be connected to other components and do inter-process communication (IPC).

Lifecycle of Android Services


Android services life-cycle can have two forms of services and they follow two paths, that are:

1. Started Service
2. Bounded Service
Let us see these services and their approach.

1. Started Service
A service becomes started only when an application component calls startService(). It performs a single
operation and doesn’t return any result to the caller.
Once this service starts, it runs in the background even if the component that created it destroys. This
service can be stopped only in one of the two cases:
 By using the stopService() method.
 By stopping itself using the stopSelf() method.

2. Bound Service
A service is bound only if an application component binds to it using bindService(). It gives a client-
server relation that lets the components interact with the service. The components can send requests to
services and get results.
This service runs in the background as long as another application is bound to it. Or it can be unbound
according to our requirement by using the unbindService() method.

10
D20MCA11140

Methods of Android Services


The service base class defines certain callback methods to perform operations on applications. When we
talk about Android services it becomes quite obvious that these services will do some operations and
they’ll be used. The following are a few important methods of Android services :

 onStartCommand()
 onBind()
 onCreate()
 onUnbind()
 onDestroy()
 onRebind()
Let us see these methods in detail:

1. onStartCommand()
The system calls this method whenever a component, say an activity requests ‘start’ to a service,
using startService().
Once we use this method it’s our duty to stop the service using stopService() or stopSelf().
2. onBind()
This is invoked when a component wants to bind with the service by calling bindService(). In this, we
must provide an interface for clients to communicate with the service. For interprocess communication,
we use the IBinder object.
It is a must to implement this method. If in case binding is not required, we should return null as
implementation is mandatory.
3. onUnbind()
The system invokes this when all the clients disconnect from the interface published by the service.
4. onRebind()
The system calls this method when new clients connect to the service. The system calls it after
the onBind() method.
5. onCreate()
This is the first callback method that the system calls when a new component starts the service. We need
this method for a one-time set-up.
6. onDestroy()
This method is the final clean up call for the system. The system invokes it just before the service
destroys. It cleans up resources like threads, receivers, registered listeners, etc.

11
D20MCA11140

Ques. 8: How to call context in Fragment?


Ans. 8:

getActivity() can return null if it is called before onAttach of the respective fragment.

A solution for the problem of detached fragments is to store the value


of getActivity().getApplicationContext() in an instance variable when the fragment is created and then
use that context whenever you want inside the fragment class. That context will survive fragment
detachments.

Instead of passing around the application context, create a static context inside your Application class and
initialize it onCreate(): MyApplication.sContext = getApplicationContext(); then you can access it from
any activity/fragment without worrying about detachment. 

The easiest and most precise way to get the context of the fragment that I found is to get it directly from
the ViewGroup when you call onCreateView method at least here you are sure not to get null
for getActivity():

public class FirstFragment extends Fragment {

private Context mContext;


public FirstFragment() {
// Required empty public constructor
}

@Override
public void onAttach(Context context) {
super.onAttach(context);
mContext=context;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rooView=inflater.inflate(R.layout.fragment_first, container, false);

Toast.makeText(mContext, "THIS IS SAMPLE TOAST",


Toast.LENGTH_SHORT).show();
// Inflate the layout for this fragment
return rooView;
}
}

12
D20MCA11140

Ques. 9: Is there any difference between intents and services? Justify your answer.
Ans. 9:
Difference :
Service is a base class of service implementation. Service runs on the application's main thread which
may reduce the application performance. Thus, IntentService, which is a direct subclass of Service is
available to make things easier.
Service class uses the application's main thread, while IntentService creates a worker thread and uses
that thread to run the service.

IntentService creates a queue that passes one intent at a time to onHandleIntent(). Thus, implementing a
multi-thread should be made by extending Service class directly. Service class needs a manual stop
using stopSelf(). Meanwhile, IntentService automatically stops itself when it finishes execution.

IntentService implements onBind() that returns null. This means that the IntentService can not be bound


by default.

IntentService implements onStartCommand() that sends Intent to queue and to onHandleIntent().

Service
You may think of Service as an Android component that is used to run long-running operations in the
background, such as in the Music app, where we run the app in the background while using other mobile
apps at the same time.

The best thing is that you don’t have to provide any user interface for the background operations. You
can also run some Inter-Process Communication (IPC) using Service.

Since any application component can start a Service and run in the background, you can perform
multiple operations with the aid of Service. The three ways of using the service are:

1. Foreground: A foreground service is one that informs the consumer of what is going on in the
background. In the Music app, for example, the user will see the latest song on the computer as a
notification. As a result, showing the message is a must in this case.

2. Background: The consumer will never know what is going on in the context of the application in
this case. When sending images over WhatsApp, for example, WhatsApp compresses the image
file to make it smaller. This task is carried out in the background, and the consumer is unaware
of what is happening. The Android System, however, imposes certain limitations when using the
Background Service at API level 21 or higher. So, before you use the Background Service, make
sure you’re aware of the limitations.

3. Bound: The Bound Service is used when the bindService() method is used by one or more
application components to bind the Service. The Service would be broken if the applications
unbind the Service.

13
D20MCA11140

Intent Service
The IntentService base class is the Operation. Essentially, it employs a “job queue operation,” in which
the IntentService manages clients’ on-demand requests (expressed as Intents).

As a result, the Service will be started whenever a client sends a request, and it will be stopped after each
Purpose has been addressed. Clients may use Context.startService(intent) to submit a request to start a
Service (Intent).

A worker thread is generated here, and all requests are handled by the worker thread, but only one request
is processed at a time. To use IntentService, you must extend it and enforce the onHandleIntent
(android.content.Intent).

Service Intent Service


If the task doesn’t require any and If the Background task is to be performed for a
also not a very long task you can use long time we can use the intent service.
service.
we use the we use the
method onStartService()  to start the method  Context.startService(Intent) to start
service the intent service
Service will always run on the main intent service always runs on the worker
thread. thread triggered from the main thread.
There is a chance of blocking the tasks will be performed on a queue basis i.e,
main thread. first come first serve basis.
To stop service we have to No need to stop the service, it will stop
use stopService() or stopSelf() automatically.
Easy to interact with the UI of the Difficult to interact with the UI of the
application. application.

14
D20MCA11140

Ques. 10: State the usefulness of Alarm manager.

Ans. 10: The Alarm Manager is intended for cases where you want to have your application code run at
a specific time, even if your application is not currently running. For normal timing operations (ticks,
timeouts, etc) it is easier and much more efficient to use Handler.

This class provides access to the system alarm services. These allow you to schedule your application to
be run at some point in the future.

When an alarm goes off, the Intent that had been registered for it is broadcast by the system,
automatically starting the target application if it is not already running.

Registered alarms are retained while the device is asleep (and can optionally wake the device up if they
go off during that time), but will be cleared if it is turned off and rebooted.

The Alarm Manager holds a CPU wake lock as long as the alarm receiver's onReceive() method is
executing.

This guarantees that the phone will not sleep until you have finished handling the broadcast. Once
onReceive() returns, the Alarm Manager releases this wake lock. This means that the phone will in some
cases sleep as soon as your onReceive() method completes.

If your alarm receiver called Context.startService(), it is possible that the phone will sleep before the
requested service is launched.

To prevent this, your BroadcastReceiver and Service will need to implement a separate wake lock policy
to ensure that the phone continues running until the service becomes available.

Android AlarmManager allows you to access system alarm.

By the help of Android AlarmManager in android, you can schedule your application to run at
a specific time in the future. It works whether your phone is running or not.

The Android AlarmManager holds a CPU wake lock that provides guarantee not to sleep the
phone until broadcast is handled.

15
D20MCA11140

activity_main.xml

You need to drag only a edittext and a button as given below.

16
D20MCA11140

Activity class

The activity class starts the alarm service when user clicks on the button.

17
D20MCA11140

Let's create BroadcastReceiver class that starts alarm.

You need to provide a receiver

entry in AndroidManifest.xml file.

18
D20MCA11140

Output:

19
D20MCA11140

Section B
Ques. 1: Discuss how Android different from IOS.

Ans. 1:

 iOS is a closed system whereas Android is more open. Users have barely any system permissions
in iOS but in Android, users can customize their phones easily.
 Android software is available for many manufacturers such as Samsung, LG etc. and this may
lead to some quality problems in the cheaper phones. However, iOS is strictly controlled by
Apple and there is no quality problem as there are few models.
 The Android applications are obtained from Google Play while iOS applications are available in
the Apple app store.
 Integration with other devices is better in Apple iOS as compared to Google Android.
 There are different voice assistants for iOS and Android namely Siri and Google Assistant.
Google assistant is much more powerful than Siri.
 The running speed of iOS devices remains consistent with time. In contrast to this, the
performance of Android devices may decline over time.

Android iOS
Developer Various, mostly Google and Open Handset Apple Inc.
Alliance
Initial release September 23, 2008 July 29, 2007
Latest stable Android 11 iOS 14.1 and iPadOS 14.1
release and
Updates
Customizabil A lot. Can change almost anything. Limited unless jailbroken
ity
Source Open source Closed, with open source components.
model
File transfer Easier than iOS. Using USB port and More difficult. Media files can be
Android File Transfer desktop app. Photos transferred using iTunes desktop app.
can be transferred via USB without apps. Photos can be transferred out via USB
without apps.
Widgets Yes, except on lockscreen Yes, except on lockscreen
Internet Google Chrome (other browsers are Safari. Any browser app can be set as
browsing available). Any browser app can be set as default but they all use the same rendering
default. Ad blocking is supported with engine (Safari/Webkit) behind the scenes.
Firefox. Ad blocking is supported via content
blockers like Firefox Focus.
Web Google Maps Apple Maps (default). Google Maps also
mapping available via a separate app download, but
not as default.
service
Available 100+ languages 40 languages
language(s)

20
D20MCA11140

Video chat Google Meet and other 3rd party apps FaceTime (Apple devices only) and other
3rd party apps
Virtual Google Assistant Siri
assistant
Available on Many phones and tablets. Major iPod Touch, iPhone, iPad, Apple TV (2nd
manufacturers such as Samsung, Oppo, and 3rd generation)
OnePlus, Vivo, Honor and Xiaomi. Android
One devices are pure Android. Pixel line of
devices is made by Google, using a almost
pure version of Android
Calls and Google Messages. 3rd party apps like iMessage, FaceTime (with other Apple
messaging Facebook Messenger, WhatsApp, Google devices only). 3rd party apps like Google
Duo, Discord and Skype all work on Hangouts, Facebook Messenger, WhatsApp,
Android and iOS both. Google Duo, Discord and Skype all work on
Android and iOS both.
App store , Google Play Store – 2,000,000+ apps. Other Apple App Store – 1,000,000+ apps. Apps
Affordability app stores like Amazon and Aptoide also containing virus very rare or nonexistent.
distribute Android apps. (".APKs"). Apps
and interface containing virus rare, but existing.
Alternative Several alternative app stores other than the Apple blocks 3rd party app stores. The
app stores official Google Play Store. (e.g. Aptoide, phone needs to be jailbroken if you want to
Galaxy Apps) download apps from other stores.
and side
loading
Battery life Many but not all Android phone Apple batteries are generally not as big as
and manufacturers equip their devices with large the largest Android batteries. However,
batteries with a longer life. Apple is able to squeeze decent battery life
management via hardware/software optimizations.
Open source Kernel (Based on Linux), UI, and some The iOS kernel is not open source but is
standard apps based on the open-source Darwin OS.
File manager Yes. (Stock Android File Manager included Files app, limited and less useful (iOS 12).
on devices running Android 7.1.1)
Photos & Apps available for automatic backup of Up to 5 GB of photos and videos can be
Videos photos and videos. Google Photos allows automatically back up with iCloud, more
unlimited backup of photos at a compressed paid iCloud storage available via
backup quality. OneDrive, Amazon Photos and subscription. All other vendors like Google,
Dropbox are other alternatives. Amazon, Dropbox, Flickr and Microsoft
have auto-backup apps for both iOS and
Android.
Security Monthly security updates. Android software Occasional security updates. Security
patches are available soonest to Pixel device threats rare, because iOS is locked and
users. Manufacturers tend to lag behind in downloading apps out of the App Store is
pushing out these updates. So at any given complicated.
time a vast majority of Android devices are
running outdated OS software.
Rooting, Access and complete control over your Complete control over your device is not
bootloaders, device is available and you can unlock the available.
bootloader.
and
jailbreaking
Cloud Native integration with Google Drive Native integration with iCloud. 5GB free,
services storage. 15GB free, $2/mo for 100GB, 1TB 50GB for $1/mo, 200GB for $3/mo, 1TB
for $10. Apps available for Amazon Photos, for $10/mo. Apps available for Google
OneDrive and Dropbox. Drive and Google Photos, Amazon Photos,
OneDrive and Dropbox.

21
D20MCA11140

Interface Touch Screen Touch Screen


Biometric Fingerprint and/or Face Authentication. Fingerprint or Face Authentication. Touch
Authenticatio Availability depends on manufacturer's ID available on iPhone (5s and later) and
hardware. iPad (Air 2 and later) but not on iPhone X
n or later. Face ID available on iPhone X and
later, replacing Touch ID
OS family Linux OS X, UNIX
Headphone Some current Android smartphones and None on iPhone 7 and later, lighting to
Jack many don't. 3.5mm no longer comes with phone after
iPhone XS

22
D20MCA11140

Ques. 2: Elaborate the detailed Android Architecture.

Ans. 2: Android architecture is a software stack of components to support mobile device needs. Android
software stack contains a Linux Kernel, collection of c/c++ libraries which are exposed through an
application framework services, runtime, and application.
 
Following are main components of android architecture those are

1. Applications
2. Android Framework
3. Android Runtime
4. Platform Libraries
5. Linux Kernel

In these components, the Linux Kernel is the main component in android to provide its operating system
functions to mobile and Dalvik Virtual Machine (DVM) which is responsible for running a mobile
application.
 
Following is the pictorial representation of android architecture with different components.

23
D20MCA11140

Applications
The top layer of the android architecture is Applications. The native and third-party applications like
contacts, email, music, gallery, clock, games, etc. whatever we will build those will be installed on this
layer only.
 
The application layer runs within the Android run time using the classes and services made available from
the application framework. 

Application Framework
The Application Framework provides the classes used to create Android applications. It also provides a
generic abstraction for hardware access and manages the user interface and application resources. It
basically provides the services through which we can create a particular class and make that class helpful
for the Application creation.
 
The application framework includes services like telephony service, location services, notification
manager, NFC service, view system, etc. which we can use for application development as per our
requirements.

Android Runtime
Android Runtime environment is an important part of Android rather than an internal part and it
contains components like core libraries and the Dalvik virtual machine. The Android run time is the
engine that powers our applications along with the libraries and it forms the basis for the application
framework.
 
Dalvik Virtual Machine (DVM) is a register-based virtual machine like Java Virtual Machine (JVM). It
is specially designed and optimized for android to ensure that a device can run multiple instances
efficiently. It relies on the Linux kernel for threading and low-level memory management.
 
The core libraries in android runtime will enable us to implement android applications using standard
JAVA programming language.

Platform Libraries
The Platform Libraries includes various C/C++ core libraries and Java-based libraries such as SSL, libc,
Graphics, SQLite, Webkit, Media, Surface Manger, OpenGL, etc. to provide support for Android
development.
The following are the summary details of some core android libraries available for android development.
 

 Media library for playing and recording audio and video formats
 The Surface manager library to provide a display management
 SGL and OpenGL Graphics libraries for 2D and 3D graphics

24
D20MCA11140

 SQLite is for database support and FreeType for font support


 Web-Kit for web browser support and SSL for Internet security.

Linux Kernel
Linux Kernel is a bottom layer and heart of the android architecture. It manages all the drivers such as
display drivers, camera drivers, Bluetooth drivers, audio drivers, memory drivers, etc. which are mainly
required for the android device during the runtime.
 
The Linux Kernel will provide an abstraction layer between the device hardware and the remainder of the
stack. It is responsible for memory management, power management, device management, resource
access, etc.

25
D20MCA11140

Ques. 3: Elucidate the concept of services in android, explain its complete life cycle.

Ans. 3: Android service is a component that is used to perform operations on the background such as
playing music, handle network transactions, interacting content providers etc. It doesn't has any UI (user
interface).

The service runs in the background indefinitely even if application is destroyed.

Moreover, service can be bounded by a component to perform interactivity and inter process
communication (IPC).

The android.app.Service is subclass of ContextWrapper class.

Types of Services

These are the three different types of services:

Foreground

A foreground service performs some operation that


is noticeable to the user. For example, an audio app would use a foreground service to play an audio
track. Foreground services must display a Notification. Foreground services continue running even when
the user isn't interacting with the app.

When you use a foreground service, you must display a notification so that users are actively aware that
the service is running. This notification cannot be dismissed unless the service is either stopped or
removed from the foreground.

Background

A background service performs an operation that isn't directly noticed by the user. For example, if an app
used a service to compact its storage, that would usually be a background service.

Bound

A service is bound when an application component binds to it by calling bindService(). A bound service


offers a client-server interface that allows components to interact with the service, send requests, receive
results, and even do so across processes with interprocess communication (IPC).

A bound service runs only as long as another application component is bound to it. Multiple components
can bind to the service at once, but when all of them unbind, the service is destroyed.

26
D20MCA11140

Life Cycle of Android Service


There can be two forms of a service.The lifecycle of service can follow two different paths: started or
bound.

1. Started
2. Bound

1) Started Service

A service is started when component (like activity)


calls startService() method, now it runs in the background
indefinitely. It is stopped by stopService() method. The
service can stop itself by calling the stopSelf() method.

2) Bound Service

A service is bound when another component (e.g. client)


calls bindService() method. The client can unbind the
service by calling the unbindService() method.

The service cannot be stopped until all clients unbind the


service.

Methods Description
onStartCommand( The Android service calls this method when a component(eg:
) activity)
requests to start a service using startService(). Once the
service is started,
it can be stopped explicitly using stopService() or stopSelf()
methods.
onBind() This method is mandatory to implement in android service and
is invoked
whenever an application component calls the bindService()
method in order to
bind itself with a service. User-interface is also provided to
communicate
with the service effectively by returning an IBinder object.

27
D20MCA11140

If the binding of service is not required then the method must


return null.
onUnbind() The Android system invokes this method when all the clients
get disconnected from a particular service interface.
onRebind() Once all clients are disconnected from the particular interface
of service and
there is a need to connect the service with new clients, the
system calls this method.
onCreate() Whenever a service is created either using onStartCommand()
or onBind(),
the android system calls this method. This method is necessary
to perform
a one-time-set-up.
onDestroy() When a service is no longer in use, the system invokes this
method
 just before the service destroys as a final clean up call.
Services must
 implement this method in order to clean up resources like
registered listeners,
 threads, receivers, etc.

28
D20MCA11140

Ques. 5: Compare SOAP and Restful API in detail. Explain benefits of SOAP.
Ans. 5:

SOAP
SOAP is a protocol which was designed before REST and came into the picture. The main idea behind
designing SOAP was to ensure that programs built on different platforms and programming languages
could exchange data in an easy manner. SOAP stands for Simple Object Access Protocol.

REST
REST was designed specifically for working with components such as media components, files, or even
objects on a particular hardware device. Any web service that is defined on the principles of REST can be
called a RestFul web service. A Restful service would use the normal HTTP verbs of GET, POST, PUT
and DELETE for working with the required components. REST stands for Representational State
Transfer.

Sr. Key REST API SOAP API


No.

Implementatio Rest API is implemented as it On other hand SOAP API has


n has no official standard at all an official standard because it is
1
because it is an architectural a protocol.
style.

Internal REST APIs uses multiple SOAP APIs is largely based and
communication standards like HTTP, JSON, uses only HTTP and XML.
2
URL, and XML for data
communication and transfer.

Resource As REST API deploys and On other hand Soap API


requirement uses multiple standards as requires more resource and
stated above, so it takes fewer bandwidth as it needs to convert
3
resources and bandwidth as the data in XML which increases
compared to SOAP API. its payload and results in the
large sized file.

4 Description REST API uses Web On other hand SOAP API used
Application Description Web Services Description
Language for describing the

29
D20MCA11140

Sr. Key REST API SOAP API


No.

functionalities being offered by language for the same.


web services.

Security REST has SSL and HTTPS for On other hand SOAP has
security. SSL( Secure Socket Layer) and
WS-security due to which in the
5
cases like Bank Account
Password, Card Number, etc.
SOAP is preferred over REST.

Abbreviation REST stands for On other hand SOAP stands for


6 Representational State Simple Object Access Protocol
Transfer.

Interchange REST can make use of SOAP On other hand SOAP cannot
as the underlying protocol for make use of REST since SOAP
7 web services, because in the is a protocol and REST is an
end it is just an architectural architectural pattern.
pattern.

Benefits of SOAP:

SOAP is the protocol used for data interchange between applications. Below
are some of the reasons as to why SOAP is used.

 When developing SOAP based Web services, you need to have some of language which can be
used for web services to talk with client applications. SOAP is the perfect medium which was
developed in order to achieve this purpose. This protocol is also recommended by the W3C
consortium which is the governing body for all web standards.
 SOAP is a light-weight protocol that is used for data interchange between applications. Note the
keyword ‘light.’ Since SOAP programming is based on the XML language, which itself is a light
weight data interchange language, hence SOAP as a protocol that also falls in the same category.
 SOAP is designed to be platform independent and is also designed to be operating system
independent. So the SOAP protocol can work any programming language based applications on
both Windows and Linux platform.
 It works on the HTTP protocol –SOAP works on the HTTP protocol, which is the default
protocol used by all web applications. Hence, there is no sort of customization which is required
to run the web services built on the SOAP protocol to work on the World Wide Web.

30
D20MCA11140

 SOAP is a communication protocol designed to communicate via Internet.


 SOAP can extend HTTP for XML messaging.
 SOAP provides data transport for Web services.
 SOAP can exchange complete documents or call a remote procedure.
 SOAP can be used for broadcasting a message.
 SOAP is platform- and language-independent.
 SOAP is the XML way of defining what information is sent and how.
 SOAP enables client applications to easily connect to remote services and invoke remote
methods.

31

You might also like