0% found this document useful (0 votes)
44 views44 pages

Android Notes

Android is an open source operating system for mobile devices. It provides features like connectivity, storage, media support and messaging. Android applications are developed in Java and distributed through app stores. The history of Android developments started in 2007 and new versions are identified by code names like Cupcake, Donut, Marshmallow.

Uploaded by

Prerna Mutreja
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)
44 views44 pages

Android Notes

Android is an open source operating system for mobile devices. It provides features like connectivity, storage, media support and messaging. Android applications are developed in Java and distributed through app stores. The history of Android developments started in 2007 and new versions are identified by code names like Cupcake, Donut, Marshmallow.

Uploaded by

Prerna Mutreja
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/ 44

lOMoARcPSD|25644675

Android Notes

COMPUTER SCIENCE ENGINEERING (Jawaharlal Nehru Technological University,


Kakinada)

Studocu is not sponsored or endorsed by any college or university


Downloaded by prerna Mutreja ([email protected])
lOMoARcPSD|25644675

DEE630:: ANDROID APPLICATION DEVELOPMENT

Android is an open source and Linux-based operating system for mobile devices such as
smartphones and tablet computers. Android was developed by the Open Handset Alliance, led by
Google, and other companies. This will teach you basic Android programming and will also take
you through some advance concepts related to Android application development.

Prerequisites
Android programming is based on Java programming language so if we have basic
understanding on Java programming,xml then it will be aeasy to learn Android application
development.

Q1. Explain Features of Android


Features of Android
Android is a powerful operating system competing with Apple 4GS and supports great features.
Few of them are listed below −

Sr.No. Feature & Description

1
Beautiful UI
Android OS basic screen provides a beautiful and intuitive user interface.

2
Connectivity
GSM/EDGE, IDEN, CDMA, EV-DO, UMTS, Bluetooth, Wi-Fi, LTE, NFC and WiMAX.

3
Storage
SQLite, a lightweight relational database, is used for data storage purposes.

4
Media support
H.263, H.264, MPEG-4 SP, AMR, AMR-WB, AAC, HE-AAC, AAC 5.1, MP3, MIDI, Ogg Vorbis, WAV,
JPEG, PNG, GIF, and BMP.

Downloaded by prerna Mutreja ([email protected])


lOMoARcPSD|25644675

5
Messaging
SMS and MMS

6
Web browser
Based on the open-source WebKit layout engine, coupled with Chrome's V8 JavaScript engine
supporting HTML5 and CSS3.

7
Multi-touch
Android has native support for multi-touch which was initially made available in handsets such
as the HTC Hero.

8
Multi-tasking
User can jump from one task to another and same time various application can run
simultaneously.

9
Resizable widgets
Widgets are resizable, so users can expand them to show more content or shrink them to save
space.

10
Multi-Language
Supports single direction and bi-directional text.

11
GCM
Google Cloud Messaging (GCM) is a service that lets developers send short message data to
their users on Android devices, without needing a proprietary sync solution.

12
Wi-Fi Direct
A technology that lets apps discover and pair directly, over a high-bandwidth peer-to-peer
connection.

13
Android Beam
A popular NFC-based technology that lets users instantly share, just by touching two NFC-
enabled phones together.

Q2. Write about Applications of Android System


Android applications are usually developed in the Java language using the Android Software
Development Kit.
Once developed, Android applications can be packaged easily and sold out either through a store
such as Google Play, SlideME, Opera Mobile Store, Mobango, F-droid and the Amazon
Appstore.
Android powers hundreds of millions of mobile devices in more than 190 countries around the
world. It's the largest installed base of any mobile platform and growing fast. Every day more than
1 million new Android devices are activated worldwide.
We will start from environment setup for Android application programming and then drill down to
look into various aspects of Android applications.

Downloaded by prerna Mutreja ([email protected])


lOMoARcPSD|25644675

Categories of Android applications


There are many android applications in the market.

There are many android applications in the market. The top categories are:

o Entertainment
o Tools
o Communication
o Productivity
o Personalization
o Music and Audio
o Social
o Media and Video
o Travel and Local etc.

The top categories are –

Q3. Explain History of Android Developments


The code names of android ranges from A to N currently, such as Aestro, Blender, Cupcake,
Donut, Eclair, Froyo, Gingerbread, Honeycomb, Ice Cream Sandwitch, Jelly Bean, KitKat,
Lollipop and Marshmallow. Let's understand the android history in a sequence.
Android is an open source and Linux-based Operating System for mobile devices such as
smartphones and tablet computers. Android was developed by the Open Handset Alliance, led by
Google, and other companies.
Android offers a unified approach to application development for mobile devices which means
developers need only develop for Android, and their applications should be able to run on
different devices powered by Android.
The first beta version of the Android Software Development Kit (SDK) was released by Google in
2007 where as the first commercial version, Android 1.0, was released in September 2008.
On June 27, 2012, at the Google I/O conference, Google announced the next Android version,
4.1 Jelly Bean. Jelly Bean is an incremental update, with the primary aim of improving the user
interface, both in terms of functionality and performance.

Downloaded by prerna Mutreja ([email protected])


lOMoARcPSD|25644675

The source code for Android is available under free and open source software licenses. Google
publishes most of the code under the Apache License version 2.0 and the rest, Linux kernel
changes, under the GNU General Public License version 2.

What is API level and Versions


API Level is an integer value that uniquely identifies the framework API revision offered by a version of the
Android platform.

Platform Version API Level VERSION_CODE

Android 6.0 23 MARSHMALLOW

Android 5.1 22 LOLLIPOP_MR1

Android 5.0 21 LOLLIPOP

Android 4.4W 20 KITKAT_WATCH KitKat for Wearables Only

Android 4.4 19 KITKAT

Q4. Explain How Android Will be Installed and Configured.


Android - Environment Setup
We can start Android application development on either of the following operating systems −
 Microsoft Windows XP or later version.
 Mac OS X 10.5.8 or later version with Intel chip.
 Linux including GNU C Library 2.7 or later.
Second point is that all the required tools to develop Android applications are freely available and
can be downloaded from the Web. We will need before start Android application programming.
 Java JDK5 or later version
 Android Studio
Here last two components are optional and if you are working on Windows machine then these
components make your life easy while doing Java based application development.

Downloaded by prerna Mutreja ([email protected])


lOMoARcPSD|25644675

Set-up Java Development Kit (JDK)


We can download the latest version of Java JDK from Oracle's Java site − Java SE Downloads.
follow the given instructions to install and configure the setup. Finally set PATH and JAVA_HOME
environment variables to refer to the directory that contains java and javac, typically
java_install_dir/bin and java_install_dir respectively.
If you are running Windows and installed the JDK in C:\jdk1.8.0_102, you would have to put the
following line in your C:\autoexec.bat file.
set PATH=C:\jdk1.8.0_102\bin;%PATH%
set JAVA_HOME=C:\jdk1.8.0_102
Alternatively, you could also right-click on My Computer, select Properties, then Advanced,
then Environment Variables. Then, you would update the PATH value and press the OK button.
On Linux, if the SDK is installed in /usr/local/jdk1.8.0_102 and you use the C shell, you would put
the following code into your .cshrc file.
setenv PATH /usr/local/jdk1.8.0_102/bin:$PATH
setenv JAVA_HOME /usr/local/jdk1.8.0_102
Alternatively, if you use Android studio, then it will know automatically where you have installed
your Java.

Android IDEs
There are so many sophisticated Technologies are available to develop android applications, the
familiar technologies, which are predominantly using tools as follows
 Android Studio
 Eclipse IDE(Deprecated)

Q5. EXPLAIN THE ARCHITECTURE OF ANDROID?


Android - Architecture
Android operating system is a stack of software components which is roughly divided into five
sections and four main layers as shown below in the architecture diagram.

Downloaded by prerna Mutreja ([email protected])


lOMoARcPSD|25644675

Linux kernel
At the bottom of the layers is Linux - Linux 3.6 with approximately 115 patches. This provides a
level of abstraction between the device hardware and it contains all the essential hardware
drivers like camera, keypad, display etc. Also, the kernel handles all the things that Linux is really
good at such as networking and a vast array of device drivers, which take the pain out of
interfacing to peripheral hardware.

Libraries
On top of Linux kernel there is a set of libraries including open-source Web browser engine
WebKit, well known library libc, SQLite database which is a useful repository for storage and
sharing of application data, libraries to play and record audio and video, SSL libraries responsible
for Internet security etc.

Android Libraries
This category encompasses those Java-based libraries that are specific to Android development.
Examples of libraries in this category include the application framework libraries in addition to
those that facilitate user interface building, graphics drawing and database access. A summary of
some key core Android libraries available to the Android developer is as follows −
 android.app − Provides access to the application model and is the cornerstone of all Android
applications.
 android.content − Facilitates content access, publishing and messaging between applications and
application components.

Downloaded by prerna Mutreja ([email protected])


lOMoARcPSD|25644675

 android.database − Used to access data published by content providers and includes SQLite database
management classes.
 android.opengl − A Java interface to the OpenGL ES 3D graphics rendering API.
 android.os − Provides applications with access to standard operating system services including
messages, system services and inter-process communication.
 android.text − Used to render and manipulate text on a device display.
 android.view − The fundamental building blocks of application user interfaces.
 android.widget − A rich collection of pre-built user interface components such as buttons, labels, list
views, layout managers, radio buttons etc.
 android.webkit − A set of classes intended to allow web-browsing capabilities to be built into
applications.
Having covered the Java-based core libraries in the Android runtime, it is now time to turn our
attention to the C/C++ based libraries contained in this layer of the Android software stack.

Android Runtime
This is the third section of the architecture and available on the second layer from the bottom.
This section provides a key component called Dalvik Virtual Machine which is a kind of Java
Virtual Machine specially designed and optimized for Android.
The Dalvik VM makes use of Linux core features like memory management and multi-threading,
which is intrinsic in the Java language. The Dalvik VM enables every Android application to run in
its own process, with its own instance of the Dalvik virtual machine.
The Android runtime also provides a set of core libraries which enable Android application
developers to write Android applications using standard Java programming language.

Downloaded by prerna Mutreja ([email protected])


lOMoARcPSD|25644675

Q6. EXPLAIN ANDROID APPLICATION FRAMEWORK?

Application Framework
The Application Framework layer provides many higher-level services to applications in the form
of Java classes. Application developers are allowed to make use of these services in their
applications.
The Android framework includes the following key services −
 Activity Manager − Controls all aspects of the application lifecycle and activity stack.
 Content Providers − Allows applications to publish and share data with other applications.
 Resource Manager − Provides access to non-code embedded resources such as strings, color settings
and user interface layouts.
 Notifications Manager − Allows applications to display alerts and notifications to the user.
 View System − An extensible set of views used to create application user interfaces.

Applications
We will find all the Android application at the top layer. we write application to be installed on this
layer only. Examples of such applications are Contacts Books, Browser, Games etc.
Application components are the essential building blocks of an Android application. These
components are loosely coupled by the application manifest file AndroidManifest.xml that
describes each component of the application and how they interact.
There are following four main components that can be used within an Android application −

Sr.No Components & Description

1 Activities: They dictate the UI and handle the user interaction to the smart phone
screen.

2 Services :They handle background processing associated with an application.

3 Broadcast Receivers :They handle communication between Android OS and


applications.

4 Content Providers :They handle data and database management issues.

Activities
An activity represents a single screen with a user interface,in-short Activity performs actions on
the screen. For example, an email application might have one activity that shows a list of new
emails, another activity to compose an email, and another activity for reading emails. If an
application has more than one activity, then one of them should be marked as the activity that is
presented when the application is launched.
An activity is implemented as a subclass of Activity class as follows −
Public class MainActivity extends Activity{
}

Downloaded by prerna Mutreja ([email protected])


lOMoARcPSD|25644675

Services
A service is a component that runs in the background to perform long-running operations. For
example, a service might play music in the background while the user is in a different application,
or it might fetch data over the network without blocking user interaction with an activity.
A service is implemented as a subclass of Service class as follows −
publicclassMyServiceextendsService{
}

Broadcast Receivers
Broadcast Receivers simply respond to broadcast messages from other applications or from the
system. 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.
A broadcast receiver is implemented as a subclass of BroadcastReceiver class and each
message is broadcaster as an Intent object.
publicclassMyReceiverextendsBroadcastReceiver{
publicvoid onReceive(context,intent){}
}

Content Providers
A content provider component supplies data from one application to others on request. Such
requests are handled by the methods of the ContentResolver class. The data may be stored in
the file system, the database or somewhere else entirely.
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.
publicclassMyContentProviderextendsContentProvider{
publicvoid onCreate(){}
}

We will go through these tags in detail while covering application components in individual
chapters.
Additional Components
There are additional components which will be used in the construction of above mentioned
entities, their logic, and wiring between them. These components are −
S.No Components & Description

1 Fragments :Represents a portion of user interface in an Activity.

2 Views: UI elements that are drawn on-screen including buttons, lists forms etc.

3 Layouts :View hierarchies that control screen format and appearance of the views.

4 Intents :Messages wiring components together.

5 Resources :External elements, such as strings, constants and drawable pictures.

Downloaded by prerna Mutreja ([email protected])


lOMoARcPSD|25644675

6 Manifest :Configuration file for the application

WRI
TEABOUTBASI
CBUI
LDI
NG BLOCKSOFANDROI
D?

Andr
oidCor
eBui
l
dingBl
ocks
An android component is simply a piece of code that has a well defined life cycle e.g. Activity,
Receiver, Service etc.

The core building blocks or fundamental components of android are activities, views, intents,
services, content providers, fragments and AndroidManifest.xml.

Act
i
vit
y
An activity is a class that represents a single screen. It is like a Frame in AWT.

Vi
ew
A view is the UI element such as button, label, text field etc. Anything that you see is a view.

I
ntent
Intent is used to invoke components. It is mainly used to:

o Start the service


o Launch an activity
o Display a web page
o Display a list of contacts
o Broadcast a message
o Dial a phone call etc.

For example, you may write the following code to view the webpage.

1. Intent intent=new Intent(Intent.ACTION_VIEW);


2. intent.setData(Uri.parse("http://www.javatpoint.com"));
3. startActivity(intent);

Ser
vice
Service is a background process that can run for a long time.

There are two types of services local and remote. Local service is accessed from within the application
whereas remote service is accessed remotely from other applications running on the same device.

Cont
entPr
ovi
der
Content Providers are used to share data between the applications.

Fr
agment
Fragments are like parts of activity. An activity can display one or more fragments on the screen at the
same time.

Downloaded by prerna Mutreja ([email protected])


lOMoARcPSD|25644675

Andr
oidMani
f
est
.xml
It contains informations about activities, content providers, permissions etc. It is like the web.xml file
in Java EE.

Andr
oidVi
rt
ualDev
ice(
AVD)
It is used to test the android application without the need for mobile or tablet etc. It can be created in
different configurations to emulate different types of real devices.

Q7. EXPLAIN ANDROID APPLICATION DEVELOPMENT?


Create Android Application
The first step is to create a simple Android Application using Android studio. When you click on
Android studio icon, it will show screen as shown below

You can start your application development by calling start a new android studio project. in a new
installation frame should ask Application name, package information and location of the project.−

Downloaded by prerna Mutreja ([email protected])


lOMoARcPSD|25644675

After entered application name, it going to be called select the form factors your application runs
on, here need to specify Minimum SDK, in our tutorial, I have declared as API23: Android
6.0(Mashmallow) −

The next level of installation should contain selecting the activity to mobile, it specifies the default
layout for Applications.

Downloaded by prerna Mutreja ([email protected])


lOMoARcPSD|25644675

At the final stage it going to be open development tool to write the application code.

Q8. EXPLAIN ANTOMY OF ANDROID APPLICATION?


Anatomy of Android Application
Before we run Android app, we should be aware of a few directories and files in the Android
project −

Downloaded by prerna Mutreja ([email protected])


lOMoARcPSD|25644675

Sr.No. Folder, File & Description

Java :This contains the .java source files for your project. By default, it includes
1 an MainActivity.java source file having an activity class that runs when your app is
launched using the app icon.

2 res/drawable-hdpi :This is a directory for drawable objects that are designed for high-
density screens.

3 res/layout :This is a directory for files that define your app's user interface.

4 res/values :This is a directory for other various XML files that contain a collection of
resources, such as strings and colours definitions.

AndroidManifest.xml
5 This is the manifest file which describes the fundamental characteristics of the app and
defines each of its components.

Build.gradle
6 This is an auto generated file which contains compileSdkVersion, buildToolsVersion,
applicationId, minSdkVersion, targetSdkVersion, versionCode and versionName

Following section will give a brief overview of the important application files.

The Main Activity File


The main activity code is a Java file MainActivity.java. This is the actual application file which
ultimately gets converted to a Dalvik executable and runs your application. Following is the
default code generated by the application wizard for Hello World! application −

Downloaded by prerna Mutreja ([email protected])


lOMoARcPSD|25644675

package com.example.helloworld;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

publicclassMainActivityextendsAppCompatActivity{
@Override
protectedvoid onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}

Here, R.layout.activity_main refers to the activity_main.xml file located in the res/layout folder.
The onCreate() method is one of many methods that are figured when an activity is loaded.

The Manifest File


Whatever component we develop as a part of the application, we must declare all its components
in a manifest.xml which resides at the root of the application project directory. This file works as
an interface between Android OS and the application, so if we do not declare the component in
this file, then it will not be considered by the OS. For example, a default manifest file will look like
as following file −
<?xml version="1.0" encoding="utf-8"?>
<manifestxmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tutorialspoint7.myapplication">

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">

<activityandroid:name=".MainActivity">
<intent-filter>
<actionandroid:name="android.intent.action.MAIN"/>
<categoryandroid:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>

Here <application>...</application> tags enclosed the components related to the application.


Attribute android:icon will point to the application icon available under res/drawable-hdpi. The
application uses the image named ic_launcher.png located in the drawable folders
The <activity> tag is used to specify an activity and android:name attribute specifies the fully
qualified class name of the Activity subclass and the android:label attributes specifies a string to
use as the label for the activity. You can specify multiple activities using <activity> tags.
The action for the intent filter is named android.intent.action.MAIN to indicate that this activity
serves as the entry point for the application. The category for the intent-filter is
named android.intent.category.LAUNCHER to indicate that the application can be launched from
the device's launcher icon.
The @string refers to the strings.xml file explained below. Hence, @string/app_name refers to
the app_name string defined in the strings.xml file, which is "HelloWorld". Similar way, other
strings get populated in the application.

Downloaded by prerna Mutreja ([email protected])


lOMoARcPSD|25644675

Following is the list of tags which you will use in your manifest file to specify different Android
application components −
 <activity>elements for activities
 <service> elements for services
 <receiver> elements for broadcast receivers
 <provider> elements for content providers

The Strings File


The strings.xml file is located in the res/values folder and it contains all the text that your
application uses. For example, the names of buttons, labels, default text, and similar types of
strings go into this file. This file is responsible for their textual content. For example, a default
strings file will look like as following file −
<resources>
<stringname="app_name">HelloWorld</string>
<stringname="hello_world">Hello world!</string>
<stringname="menu_settings">Settings</string>
<stringname="title_activity_main">MainActivity</string>
</resources>

The Layout File


The activity_main.xml is a layout file available in res/layout directory, that is referenced by your
application when building its interface. You will modify this file very frequently to change the layout
of your application. For your "Hello World!" application, this file will have following content related
to default layout −
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:padding="@dimen/padding_medium"
android:text="@string/hello_world"
tools:context=".MainActivity"/>

</RelativeLayout>

This is an example of simple RelativeLayout which we will study in a separate chapter.


The TextView is an Android control used to build the GUI and it have various attributes
like android:layout_width, android:layout_height etc which are being used to set its width and
height etc.. The @string refers to the strings.xml file located in the res/values folder. Hence,
@string/hello_world refers to the hello string defined in the strings.xml file, which is "Hello
World!".

Running the Application


Let's try to run our Hello World! application we just created. I assume you had created
your AVD while doing environment set-up. To run the app from Android studio, open one of your
project's activity files and click Run icon from the tool bar. Android studio installs the app on

Downloaded by prerna Mutreja ([email protected])


lOMoARcPSD|25644675

your AVD and starts it and if everything is fine with your set-up and application, it will display
following Emulator window −

Congratulations!!! you have developed your first Android Application and now just keep following
rest of the tutorial step by step to become a great Android Developer. All the very best.

Downloaded by prerna Mutreja ([email protected])


lOMoARcPSD|25644675

UNIT-II
Q9. EXPLAIN ANDROID ACTIVITIES OR LIFE CYCLE OF
ANDROID ACTIVITY?
Android - Activities
An activity represents a single screen with a user interface just like window or frame of Java.Android activity is
the subclass of ContextThemeWrapper class.

If WE worked with C, C++ or Java programming language then WE must have seen that our
program starts from main() function. Very similar way, Android system initiates its program with in
an Activity starting with a call on onCreate() callback method. There is a sequence of callback
methods that start up an activity and a sequence of callback methods that tear down an activity
as shown in the below Activity life cycle diagram: (image courtesy : android.com )

The Activity class defines the following call backs i.e. events. You don't need to implement all the
callbacks methods. However, it's important that you understand each one and implement those
that ensure your app behaves the way users expect.

Sr.No Callback & Description

1 onCreate() : This is the first callback and called when the activity is first created.

2 onStart() : This callback is called when the activity becomes visible to the user.

3 onResume() : This is called when the user starts interacting with the application.

Downloaded by prerna Mutreja ([email protected])


lOMoARcPSD|25644675

onPause() : The paused activity does not receive user input and cannot execute any
4 code and called when the current activity is being paused and the previous activity is
being resumed.

5 onStop() : This callback is called when the activity is no longer visible.

6 onDestroy() : This callback is called before the activity is destroyed by the system.

7 onRestart() : This callback is called when the activity restarts after stopping it.

Example
This example will take you through simple steps to show Android application activity life cycle.
Follow the following steps to modify the Android application we created in Hello World
Example chapter −

Step Description

1 You will use Android studio to create an Android application and name it
as HelloWorld under a package com.example.helloworld as explained in the Hello World
Example chapter.

2 Modify main activity file MainActivity.java as explained below. Keep rest of the files
unchanged.

3 Run the application to launch Android emulator and verify the result of the changes done
in the application.

An activity class loads all the UI component using the XML file available in res/layout folder of the
project. Following statement loads UI components from res/layout/activity_main.xml file:
setContentView(R.layout.activity_main);

An application can have one or more activities without any restrictions. Every activity you define
for your application must be declared in your AndroidManifest.xml file and the main activity for
your app must be declared in the manifest with an <intent-filter> that includes the MAIN action
and LAUNCHER category as follows:
If either the MAIN action or LAUNCHER category are not declared for one of your activities, then
your app icon will not appear in the Home screen's list of apps.

Downloaded by prerna Mutreja ([email protected])


lOMoARcPSD|25644675

Q10. EXPLAIN ANDROID SERVICES?


Android - Services
A service is a component that runs in the background to perform long-running operations without needing to
interact with the user and it works even if application is destroyed. A service can essentially take two states –

Sr.No. State & Description

1
Started
A service is started when an application component, such as an activity, starts it by
calling startService(). Once started, a service can run in the background indefinitely,
even if the component that started it is destroyed.

2
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, get results, and even do so across processes with
interprocess communication (IPC).

A service has life cycle callback methods that you can implement to monitor changes in the
service's state and you can perform work at the appropriate stage. The following diagram on the
left shows the life cycle when the service is created with startService() and the diagram on the
right shows the life cycle when the service is created with bindService(): (image courtesy :
android.com )

Downloaded by prerna Mutreja ([email protected])


lOMoARcPSD|25644675

To create an service, you create a Java class that extends the Service base class or one of its
existing subclasses. The Service base class defines various callback methods and the most
important are given below. You don't need to implement all the callbacks methods. However, it's
important that you understand each one and implement those that ensure your app behaves the
way users expect.

Sr.No. Callback & Description

1
onStartCommand()
The system calls this method when another component, such as an activity, requests
that the service be started, by calling startService(). If you implement this method, it is
your responsibility to stop the service when its work is done, by
calling stopSelf() or stopService() methods.

2
onBind()
The system calls this method when another component wants to bind with the service
by calling bindService(). If you implement this method, you must provide an interface
that clients use to communicate with the service, by returning an IBinder object. You
must always implement this method, but if you don't want to allow binding, then you
should return null.

3
onUnbind()
The system calls this method when all clients have disconnected from a particular
interface published by the service.

4
onRebind()
The system calls this method when new clients have connected to the service, after it
had previously been notified that all had disconnected in its onUnbind(Intent).

5
onCreate()
The system calls this method when the service is first created
using onStartCommand() or onBind(). This call is required to perform one-time set-up.

6
onDestroy()
The system calls this method when the service is no longer used and is being
destroyed. Your service should implement this to clean up any resources such as
threads, registered listeners, receivers, etc.

Example
This example will take you through simple steps to show how to create your own Android Service.
Follow the following steps to modify the Android application we created in Hello World
Example chapter −

Step Description

1 You will use Android StudioIDE to create an Android application and name it as My
Application under a package com.example.tutorialspoint7.myapplication as explained in

Downloaded by prerna Mutreja ([email protected])


lOMoARcPSD|25644675

the Hello World Example chapter.

2 Modify main activity file MainActivity.java to add startService() and stopService() methods.

3 Create a new java file MyService.java under the package com.example.My Application.
This file will have implementation of Android service related methods.

4 Define your service in AndroidManifest.xml file using <service.../> tag. An application can
have one or more services without any restrictions.

5 Modify the default content of res/layout/activity_main.xml file to include two buttons in


linear layout.

6 No need to change any constants in res/values/strings.xml file. Android studio take care of
string values

7 Run the application to launch Android emulator and verify the result of the changes done
in the application.

Q11. EXPLAIN ANDROID Intens and Filters?


Android - Intents and Filters
An Android Intent is an abstract description of an operation to be performed. It can be used
with startActivity to launch an Activity, broadcastIntent to send it to any interested
BroadcastReceiver components, and startService(Intent) or bindService(Intent,
ServiceConnection, int) to communicate with a background Service.
The intent itself, an Intent object, is a passive data structure holding an abstract description of an
operation to be performed.

For example, let's assume that you have an Activity that needs to launch an email client and
sends an email using your Android device. For this purpose, your Activity would send an
ACTION_SEND along with appropriate chooser, to the Android Intent Resolver. The specified
chooser gives the proper interface for the user to pick how to send your email data.
Intent email =newIntent(Intent.ACTION_SEND,Uri.parse("mailto:"));
email.putExtra(Intent.EXTRA_EMAIL, recipients);
email.putExtra(Intent.EXTRA_SUBJECT, subject.getText().toString());
email.putExtra(Intent.EXTRA_TEXT, body.getText().toString());
startActivity(Intent.createChooser(email,"Choose an email client
from..."));

Above syntax is calling startActivity method to start an email activity and result should be as
shown below −

There are separate mechanisms for delivering intents to each type of component − activities,
services, and broadcast receivers.

Downloaded by prerna Mutreja ([email protected])


lOMoARcPSD|25644675

Sr.No Method & Description

Context.startActivity()
1
The Intent object is passed to this method to launch a new activity or get an existing
activity to do something new.

Context.startService()
2
The Intent object is passed to this method to initiate a service or deliver new instructions
to an ongoing service.

Context.sendBroadcast()
3
The Intent object is passed to this method to deliver the message to all interested
broadcast receivers.

Intent Objects
An Intent object is a bundle of information which is used by the component that receives the
intent as well as information used by the Android system.
An Intent object can contain the following components based on what it is communicating or
going to perform −
Action
This is mandatory part of the Intent object and is a string naming the action to be performed — or,
in the case of broadcast intents, the action that took place and is being reported. The action
largely determines how the rest of the intent object is structured . The Intent class defines a
number of action constants corresponding to different intents. Here is a list of Android Intent
Standard Actions
The action in an Intent object can be set by the setAction() method and read by getAction().
Data
Adds a data specification to an intent filter. The specification can be just a data type (the
mimeType attribute), just a URI, or both a data type and a URI. A URI is specified by separate
attributes for each of its parts −
These attributes that specify the URL format are optional, but also mutually dependent −

 If a scheme is not specified for the intent filter, all the other URI attributes are ignored.
 If a host is not specified for the filter, the port attribute and all the path attributes are ignored.
The setData() method specifies data only as a URI, setType() specifies it only as a MIME type,
and setDataAndType() specifies it as both a URI and a MIME type. The URI is read by getData()
and the type by getType().
Category
The category is an optional part of Intent object and it's a string containing additional information
about the kind of component that should handle the intent. The addCategory() method places a
category in an Intent object, removeCategory() deletes a category previously added, and
getCategories() gets the set of all categories currently in the object. Here is a list of Android Intent
Standard Categories.

Downloaded by prerna Mutreja ([email protected])


lOMoARcPSD|25644675

Extras
This will be in key-value pairs for additional information that should be delivered to the component
handling the intent. The extras can be set and read using the putExtras() and getExtras()
methods respectively. Here is a list of Android Intent Standard Extra Data
Flags
These flags are optional part of Intent object and instruct the Android system how to launch an
activity, and how to treat it after it's launched etc.
Component Name
This optional field is an android ComponentName object representing either Activity, Service or
BroadcastReceiver class. If it is set, the Intent object is delivered to an instance of the designated
class otherwise Android uses other information in the Intent object to locate a suitable target.
The component name is set by setComponent(), setClass(), or setClassName() and read by
getComponent().

Types of Intents
There are following two types of intents supported by Android

Explicit Intents
Explicit intent going to be connected internal world of application,suppose if you wants to connect
one activity to another activity, we can do this quote by explicit intent, below image is connecting
first activity to second activity by clicking button.

These intents designate the target component by its name and they are typically used for
application-internal messages - such as an activity starting a subordinate service or launching a
sister activity.
Implicit Intents
These intents do not name a target and the field for the component name is left blank. Implicit
intents are often used to activate components in other applications

Downloaded by prerna Mutreja ([email protected])


lOMoARcPSD|25644675

Q12. EXPLAIN ABOUT ANDROID FRAGMENTS?

Android - Fragments
A Fragment is a piece of an activity which enable more modular activity design. It will not be wrong if we say, a
fragment is a kind of sub-activity.

Following are important points about fragment −


 A fragment has its own layout and its own behaviour with its own life cycle callbacks.
 You can add or remove fragments in an activity while the activity is running.
 You can combine multiple fragments in a single activity to build a multi-pane UI.
 A fragment can be used in multiple activities.
 Fragment life cycle is closely related to the life cycle of its host activity which means when the activity is
paused, all the fragments available in the activity will also be stopped.
 A fragment can implement a behaviour that has no user interface component.
 Fragments were added to the Android API in Honeycomb version of Android which API version 11.
We create fragments by extending Fragment class and we can insert a fragment into our activity
layout by declaring the fragment in the activity's layout file, as a <fragment> element.
Prior to fragment introduction, we had a limitation because we can show only a single activity on
the screen at one given point in time. So we were not able to divide device screen and control
different parts separately. But with the introduction of fragment we got more flexibility and
removed the limitation of having a single activity on the screen at a time. Now we can have a
single activity but each activity can comprise of multiple fragments which will have their own
layout, events and complete life cycle.
Following is a typical example of how two UI modules defined by fragments can be combined into
one activity for a tablet design, but separated for a handset design.

The application can embed two fragments in Activity A, when running on a tablet-sized device.
However, on a handset-sized screen, there's not enough room for both fragments, so Activity A
includes only the fragment for the list of articles, and when the user selects an article, it starts
Activity B, which includes the second fragment to read the article.

Downloaded by prerna Mutreja ([email protected])


lOMoARcPSD|25644675

Fragment Life Cycle


Android fragments have their own life cycle very similar to an android activity. This section briefs
different stages of its life cycle.

Fragment lifecycle
Here is the list of methods which you can to override in your fragment class −
 onAttach()The fragment instance is associated with an activity instance.The fragment and the activity is
not fully initialized. Typically you get in this method a reference to the activity which uses the fragment
for further initialization work.
 onCreate() The system calls this method when creating the fragment. You should initialize essential
components of the fragment that you want to retain when the fragment is paused or stopped, then
resumed.
 onCreateView() The system calls this callback when it's time for the fragment to draw its user interface
for the first time. To draw a UI for your fragment, you must return a View component from this method
that is the root of your fragment's layout. You can return null if the fragment does not provide a UI.
 onActivityCreated()The onActivityCreated() is called after the onCreateView() method when the host
activity is created. Activity and fragment instance have been created as well as the view hierarchy of the
activity. At this point, view can be accessed with the findViewById() method. example. In this method
you can instantiate objects which require a Context object
 onStart()The onStart() method is called once the fragment gets visible.
 onResume()Fragment becomes active.
 onPause() The system calls this method as the first indication that the user is leaving the fragment. This
is usually where you should commit any changes that should be persisted beyond the current user
session.
 onStop()Fragment going to be stopped by calling onStop()
 onDestroyView()Fragment view will destroy after call this method
 onDestroy()onDestroy() called to do final clean up of the fragment's state but Not guaranteed to be
called by the Android platform.

How to use Fragments?


This involves number of simple steps to create Fragments.
 First of all decide how many fragments you want to use in an activity. For example let's we want to use
two fragments to handle landscape and portrait modes of the device.

Downloaded by prerna Mutreja ([email protected])


lOMoARcPSD|25644675

 Next based on number of fragments, create classes which will extend the Fragment class. The
Fragment class has above mentioned callback functions. You can override any of the functions based
on your requirements.
 Corresponding to each fragment, you will need to create layout files in XML file. These files will have
layout for the defined fragments.
 Finally modify activity file to define the actual logic of replacing fragments based on your requirement.

Types of Fragments
Basically fragments are divided as three stages as shown below.
 Single frame fragments − Single frame fragments are using for hand hold devices like mobiles, here we
can show only one fragment as a view.
 List fragments − fragments having special list view is called as list fragment
 Fragments transaction − Using with fragment transaction. we can move one fragment to another
fragment.

Downloaded by prerna Mutreja ([email protected])


lOMoARcPSD|25644675

UNIT-III
Android - UI Layouts
The basic building block for user interface is a View object which is created from the View class
and occupies a rectangular area on the screen and is responsible for drawing and event handling.
View is the base class for widgets, which are used to create interactive UI components like
buttons, text fields, etc.
The ViewGroup is a subclass of View and provides invisible container that hold other Views or
other ViewGroups and define their layout properties.
At third level we have different layouts which are subclasses of ViewGroup class and a typical
layout defines the visual structure for an Android user interface and can be created either at run
time using View/ViewGroup objects or you can declare your layout using simple XML
file main_layout.xml which is located in the res/layout folder of your project.

Layout params
A layout may contain any type of widgets such as buttons, labels, textboxes, and so on. Following
is a simple example of XML file having LinearLayout −
<?xml version="1.0" encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">

<TextViewandroid:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is a TextView"/>

<Buttonandroid:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is a Button"/>

Downloaded by prerna Mutreja ([email protected])


lOMoARcPSD|25644675

<!-- More GUI components go here -->


</LinearLayout>

Once your layout has created, you can load the layout resource from your application code, in
your Activity.onCreate() callback implementation as shown below −
publicvoid onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

Android Layout Types


There are number of Layouts provided by Android which you will use in almost all the Android
applications to provide different view, look and feel.

Sr.No Layout & Description

1 Linear Layout : LinearLayout is a view group that aligns all children in a single direction,
vertically or horizontally.

2 Relative Layout : RelativeLayout is a view group that displays child views in relative
positions.

3 Table Layout : TableLayout is a view that groups views into rows and columns.

4 Absolute Layout :AbsoluteLayout enables you to specify the exact location of its
children.

5 Frame Layout : The FrameLayout is a placeholder on screen that you can use to display
a single view.

6 List View : ListView is a view group that displays a list of scrollable items.

7 Grid View : GridView is a ViewGroup that displays items in a two-dimensional, scrollable


grid.

Layout Attributes
Each layout has a set of attributes which define the visual properties of that layout. There are few
common attributes among all the layouts and their are other attributes which are specific to that
layout. Following are common attributes and will be applied to all the layouts:

Sr.No Attribute & Description

1
android:idThis is the ID which uniquely identifies the view.

2
android:layout_widthThis is the width of the layout.

3
android:layout_heightThis is the height of the layout

4
android:layout_marginTopThis is the extra space on the top side of the layout.

5
android:layout_marginBottomThis is the extra space on the bottom side of the
layout.

Downloaded by prerna Mutreja ([email protected])


lOMoARcPSD|25644675

6
android:layout_marginLeftThis is the extra space on the left side of the layout.

7
android:layout_marginRightThis is the extra space on the right side of the layout.

8
android:layout_gravityThis specifies how child Views are positioned.

9
android:layout_weightThis specifies how much of the extra space in the layout
should be allocated to the View.

10
android:layout_xThis specifies the x-coordinate of the layout.

11
android:layout_yThis specifies the y-coordinate of the layout.

12
android:layout_widthThis is the width of the layout.

13
android:layout_widthThis is the width of the layout.

14
android:paddingLeftThis is the left padding filled for the layout.

15
android:paddingRightThis is the right padding filled for the layout.

16
android:paddingTopThis is the top padding filled for the layout.

17
android:paddingBottomThis is the bottom padding filled for the layout.

Here width and height are the dimension of the layout/view which can be specified in terms of dp
(Density-independent Pixels), sp ( Scale-independent Pixels), pt ( Points which is 1/72 of an
inch), px( Pixels), mm ( Millimeters) and finally in (inches).
You can specify width and height with exact measurements but more often, you will use one of
these constants to set the width or height −
 android:layout_width=wrap_content tells your view to size itself to the dimensions required by its
content.
 android:layout_width=fill_parent tells your view to become as big as its parent view.
Gravity attribute plays important role in positioning the view object and it can take one or more
(separated by '|') of the following constant values.

Constant Value Description

top 0x30 Push object to the top of its container, not changing its size.

bottom 0x50 Push object to the bottom of its container, not changing its
size.

left 0x03 Push object to the left of its container, not changing its size.

right 0x05 Push object to the right of its container, not changing its size.

center_vertical 0x10 Place object in the vertical center of its container, not changing
its size.

fill_vertical 0x70 Grow the vertical size of the object if needed so it completely

Downloaded by prerna Mutreja ([email protected])


lOMoARcPSD|25644675

fills its container.

center_horizonta 0x01 Place object in the horizontal center of its container, not
l changing its size.

fill_horizontal 0x07 Grow the horizontal size of the object if needed so it


completely fills its container.

center 0x11 Place the object in the center of its container in both the
vertical and horizontal axis, not changing its size.

fill 0x77 Grow the horizontal and vertical size of the object if needed so
it completely fills its container.

clip_vertical 0x80 Additional option that can be set to have the top and/or bottom
edges of the child clipped to its container's bounds. The clip
will be based on the vertical gravity: a top gravity will clip the
bottom edge, a bottom gravity will clip the top edge, and
neither will clip both edges.

clip_horizontal 0x08 Additional option that can be set to have the left and/or right
edges of the child clipped to its container's bounds. The clip
will be based on the horizontal gravity: a left gravity will clip the
right edge, a right gravity will clip the left edge, and neither will
clip both edges.

start 0x0080000 Push object to the beginning of its container, not changing its
3 size.

end 0x0080000 Push object to the end of its container, not changing its size.
5

View Identification
A view object may have a unique ID assigned to it which will identify the View uniquely within the
tree. The syntax for an ID, inside an XML tag is −
android:id="@+id/my_button"
Following is a brief description of @ and + signs −
 The at-symbol (@) at the beginning of the string indicates that the XML parser should parse and expand
the rest of the ID string and identify it as an ID resource.
 The plus-symbol (+) means that this is a new resource name that must be created and added to our
resources. To create an instance of the view object and capture it from the layout, use the following −

Button myButton =(Button)findViewById(R.id.my_button);

Downloaded by prerna Mutreja ([email protected])


lOMoARcPSD|25644675

Q13. EXPLAIN ABOUT USER CONTROLS IN ANDROID DEVELOPMENTS.

Android - UI Controls
Input controls are the interactive components in your app's user interface. Android provides a wide
variety of controls you can use in your UI, such as buttons, text fields, seek bars, check box, zoom
buttons, toggle buttons, and many more.

UI Elements
A View is an object that draws something on the screen that the user can interact with and
a ViewGroup is an object that holds other View (and ViewGroup) objects in order to define the
layout of the user interface.
You define your layout in an XML file which offers a human-readable structure for the layout,
similar to HTML.

Android UI Controls
There are number of UI controls provided by Android that allow you to build the graphical user
interface for your app.

Sr.No. UI Control & Description

1 TextView
This control is used to display text to the user.

2 EditText
EditText is a predefined subclass of TextView that includes rich editing capabilities.

3 AutoCompleteTextView
The AutoCompleteTextView is a view that is similar to EditText, except that it shows a list of
completion suggestions automatically while the user is typing.

4 Button
A push-button that can be pressed, or clicked, by the user to perform an action.

5 ImageButton
An ImageButton is an AbsoluteLayout which enables you to specify the exact location of its
children. This shows a button with an image (instead of text) that can be pressed or clicked
by the user.

6 CheckBox
An on/off switch that can be toggled by the user. You should use check box when presenting
users with a group of selectable options that are not mutually exclusive.

7 ToggleButton
An on/off button with a light indicator.

Downloaded by prerna Mutreja ([email protected])


lOMoARcPSD|25644675

8 RadioButton
The RadioButton has two states: either checked or unchecked.

9 RadioGroup
A RadioGroup is used to group together one or more RadioButtons.

10 ProgressBar
The ProgressBar view provides visual feedback about some ongoing tasks, such as when
you are performing a task in the background.

11 Spinner
A drop-down list that allows users to select one value from a set.

12 TimePicker
The TimePicker view enables users to select a time of the day, in either 24-hour mode or
AM/PM mode.

13 DatePicker
The DatePicker view enables users to select a date of the day.

Downloaded by prerna Mutreja ([email protected])


lOMoARcPSD|25644675

Android - Event Handling


Events are a useful way to collect data about a user's interaction with interactive components
of Applications. Like button presses or screen touch etc. The Android framework maintains an event
queue as first-in, first-out (FIFO) basis. You can capture these events in your program and take
appropriate action as per requirements.

There are following three concepts related to Android Event Management −


 Event Listeners − An event listener is an interface in the View class that contains a single callback
method. These methods will be called by the Android framework when the View to which the listener
has been registered is triggered by user interaction with the item in the UI.
 Event Listeners Registration − Event Registration is the process by which an Event Handler gets
registered with an Event Listener so that the handler is called when the Event Listener fires the event.
 Event Handlers − When an event happens and we have registered an event listener for the event, the
event listener calls the Event Handlers, which is the method that actually handles the event.

Event Listeners & Event Handlers


Event Handler Event Listener & Description

OnClickListener()
onClick() This is called when the user either clicks or touches or focuses upon
any widget like button, text, image etc. You will use onClick() event
handler to handle such event.

OnLongClickListener()
onLongClick() This is called when the user either clicks or touches or focuses upon
any widget like button, text, image etc. for one or more seconds. You
will use onLongClick() event handler to handle such event.

OnFocusChangeListener()
onFocusChange() This is called when the widget looses its focus ie. user goes away
from the view item. You will use onFocusChange() event handler to
handle such event.

OnFocusChangeListener()
onKey() This is called when the user is focused on the item and presses or
releases a hardware key on the device. You will use onKey() event
handler to handle such event.

OnTouchListener()
onTouch() This is called when the user presses the key, releases the key, or any
movement gesture on the screen. You will use onTouch() event
handler to handle such event.

OnMenuItemClickListener()
onMenuItemClick()
This is called when the user selects a menu item. You will use
onMenuItemClick() event handler to handle such event.

onCreateContextMenu( onCreateContextMenuItemListener()
) This is called when the context menu is being built(as the result of a
sustained "long click)

Downloaded by prerna Mutreja ([email protected])


lOMoARcPSD|25644675

There are many more event listeners available as a part of View class like OnHoverListener,
OnDragListener etc which may be needed for your application. So I recommend to refer official
documentation for Android application development in case you are going to develop a
sophisticated apps.

Event Listeners Registration


Event Registration is the process by which an Event Handler gets registered with an Event
Listener so that the handler is called when the Event Listener fires the event. Though there are
several tricky ways to register your event listener for any event, but I'm going to list down only top
3 ways, out of which you can use any of them based on the situation.
 Using an Anonymous Inner Class
 Activity class implements the Listener interface.
 Using Layout file activity_main.xml to specify event handler directly.
Below section will provide you detailed examples on all the three scenarios −

Touch Mode
Users can interact with their devices by using hardware keys or buttons or touching the
screen.Touching the screen puts the device into touch mode. The user can then interact with it by
touching the on-screen virtual buttons, images, etc.You can check if the device is in touch mode
by calling the View class’s isInTouchMode() method.

Focus
A view or widget is usually highlighted or displays a flashing cursor when it’s in focus. This
indicates that it’s ready to accept input from the user.
 isFocusable() − it returns true or false
 isFocusableInTouchMode() − checks to see if the view is focusable in touch mode. (A view may be
focusable when using a hardware key but not when the device is in touch mode)

android:foucsUp="@=id/button_l"

Event Handling Examples


Event Listeners Registration Using an Anonymous Inner Class
Here you will create an anonymous implementation of the listener and will be useful if each class
is applied to a single control only and you have advantage to pass arguments to event handler. In
this approach event handler methods can access private data of Activity. No reference is needed
to call to Activity.
But if you applied the handler to more than one control, you would have to cut and paste the code
for the handler and if the code for the handler is long, it makes the code harder to maintain.
Following are the simple steps to show how we will make use of separate Listener class to
register and capture click event. Similar way you can implement your listener for any other
required event type.

Step Description

1 You will use Android studio IDE to create an Android application and name it
as myapplication under a package com.example.myapplication as explained in the Hello
World Example chapter.

Downloaded by prerna Mutreja ([email protected])


lOMoARcPSD|25644675

2 Modify src/MainActivity.java file to add click event listeners and handlers for the two
buttons defined.

3 Modify the detault content of res/layout/activity_main.xml file to include Android UI


controls.

4 No need to declare default string constants.Android studio takes care default constants.

5 Run the application to launch Android emulator and verify the result of the changes done
in the aplication.

Android - Location Based Services


Android location APIs make it easy for you to build location-aware applications, without needing to
focus on the details of the underlying location technology.

This becomes possible with the help of Google Play services, which facilitates adding location
awareness to your app with automated location tracking, geofencing, and activity recognition.
This tutorial shows you how to use Location Services in your APP to get the current location, get
periodic location updates, look up addresses etc.

The Location Object


The Location object represents a geographic location which can consist of a latitude, longitude,
time stamp, and other information such as bearing, altitude and velocity. There are following
important methods which you can use with Location object to get location specific information −

Sr.No. Method & Description

1
float distanceTo(Location dest)
Returns the approximate distance in meters between this location and the given
location.

2
float getAccuracy()
Get the estimated accuracy of this location, in meters.

3
double getAltitude()
Get the altitude if available, in meters above sea level.

4
float getBearing()
Get the bearing, in degrees.

5
double getLatitude()
Get the latitude, in degrees.

6
double getLongitude()
Get the longitude, in degrees.

7
float getSpeed()
Get the speed if it is available, in meters/second over ground.

Downloaded by prerna Mutreja ([email protected])


lOMoARcPSD|25644675

8
boolean hasAccuracy()
True if this location has an accuracy.

9
boolean hasAltitude()
True if this location has an altitude.

10
boolean hasBearing()
True if this location has a bearing.

11
boolean hasSpeed()
True if this location has a speed.

12
void reset()
Clears the contents of the location.

13
void setAccuracy(float accuracy)
Set the estimated accuracy of this location, meters.

14
void setAltitude(double altitude)
Set the altitude, in meters above sea level.

15
void setBearing(float bearing)
Set the bearing, in degrees.

16
void setLatitude(double latitude)
Set the latitude, in degrees.

17
void setLongitude(double longitude)
Set the longitude, in degrees.

18
void setSpeed(float speed)
Set the speed, in meters/second over ground.

19
String toString()
Returns a string containing a concise, human-readable description of this object.

Get the Current Location


To get the current location, create a location client which is LocationClient object, connect it to
Location Services using connect() method, and then call its getLastLocation() method. This
method returns the most recent location in the form of Location object that contains latitude and
longitude coordinates and other information as explained above. To have location based
functionality in your activity, you will have to implement two interfaces −

 GooglePlayServicesClient.ConnectionCallbacks
 GooglePlayServicesClient.OnConnectionFailedListener

Downloaded by prerna Mutreja ([email protected])


lOMoARcPSD|25644675

These interfaces provide following important callback methods, which you need to implement in
your activity class −

Sr.No. Callback Methods & Description

1
abstract void onConnected(Bundle connectionHint)
This callback method is called when location service is connected to the location client
successfully. You will use connect() method to connect to the location client.

2
abstract void onDisconnected()
This callback method is called when the client is disconnected. You will
use disconnect() method to disconnect from the location client.

3
abstract void onConnectionFailed(ConnectionResult result)
This callback method is called when there was an error connecting the client to the
service.
You should create the location client in onCreate() method of your activity class, then connect it in onStart(), so
that Location Services maintains the current location while your activity is fully visible. You should disconnect the
client in onStop() method, so that when your app is not visible, Location Services is not maintaining the current
location. This helps in saving battery power up-to a large extent.

Get the Updated Location


If you are willing to have location updates, then apart from above mentioned interfaces, you will
need to implement LocationListener interface as well. This interface provide following callback
method, which you need to implement in your activity class −

Sr.No. Callback Method & Description

1
abstract void onLocationChanged(Location location)
This callback method is used for receiving notifications from the LocationClient when
the location has changed.

Location Quality of Service


The LocationRequest object is used to request a quality of service (QoS) for location updates
from the LocationClient. There are following useful setter methods which you can use to handle
QoS. There are equivalent getter methods available which you can check in Android official
documentation.

Sr.No. Method & Description

1
setExpirationDuration(long millis)
Set the duration of this request, in milliseconds.

2
setExpirationTime(long millis)
Set the request expiration time, in millisecond since boot.

3
setFastestInterval(long millis)
Explicitly set the fastest interval for location updates, in milliseconds.

Downloaded by prerna Mutreja ([email protected])


lOMoARcPSD|25644675

4
setInterval(long millis)
Set the desired interval for active location updates, in milliseconds.

5
setNumUpdates(int numUpdates)
Set the number of location updates.

6
setPriority(int priority)
Set the priority of the request.

Now for example, if your application wants high accuracy location it should create a location
request with setPriority(int) set to PRIORITY_HIGH_ACCURACY and setInterval(long) to 5
seconds. You can also use bigger interval and/or other priorities like PRIORITY_LOW_POWER
for to request "city" level accuracy or PRIORITY_BALANCED_POWER_ACCURACY for "block"
level accuracy.
Activities should strongly consider removing all location request when entering the background (for example at
onPause()), or at least swap the request to a larger interval and lower quality to save power consumption.

Displaying a Location Address


Once you have Location object, you can use Geocoder.getFromLocation() method to get an
address for a given latitude and longitude. This method is synchronous, and may take a long time
to do its work, so you should call the method from the doInBackground() method of
an AsyncTask class.
The AsyncTask must be subclassed to be used and the subclass will
override doInBackground(Params...) method to perform a task in the background
and onPostExecute(Result) method is invoked on the UI thread after the background
computation finishes and at the time to display the result. There is one more important method
available in AyncTask which is execute(Params... params), this method executes the task with
the specified parameters.
Create Android Application
Step Description

1 You will use Android studio IDE to create an Android application and name it
as Tutorialspoint under a package com.example.tutorialspoint7.myapplication.

2 add src/GPSTracker.java file and add required code.

3 Modify src/MainActivity.java file and add required code as shown below to take care of
getting current location and its equivalent address.

4 Modify layout XML file res/layout/activity_main.xml to add all GUI components which
include three buttons and two text views to show location/address.

5 Modify res/values/strings.xml to define required constant values

6 Modify AndroidManifest.xml as shown below

7 Run the application to launch Android emulator and verify the result of the changes done
in the application.

Downloaded by prerna Mutreja ([email protected])


lOMoARcPSD|25644675

Q1.Whati
sAndr
oid?
Android is an open-source, Linux-based operating system used in mobiles, tablets, televisions, etc.
2)Whoi
sthef
ounderofAndr
oid?
Andy Rubin.
3)Expl
aint
heAndr
oidappl
i
cat
i
onAr
chi
t
ect
ure.
Following is a list of components of Android application architecture:
o Services: Used to perform background functionalities.
o Intent: Used to perform the interconnection between activities and the data passing
mechanism.
o Resource Externalization: strings and graphics.
o Notification: light, sound, icon, notification, dialog box and toast.
o Content Providers: It will share the data between applications.
4)Whatar
ethecodenamesofandr
oid?
1. Aestro 8. Honeycomb
2. Blender 9. Ice Cream Sandwich
3. Cupcake 10. Jelly Bean
4. Donut 11. KitKat
5. Eclair 12. Lollipop
6. Froyo 13. Marshmallow
7. Gingerbread
5)Whatar
etheadv
ant
agesofAndr
oid?
Open-source: It means no license, distribution and development fee.
Platform-independent: It supports Windows, Mac, and Linux platforms.
Supports various technologies: It supports camera, Bluetooth, wifi, speech, EDGE etc. technologies.
Highly optimized Virtual Machine: Android uses a highly optimized virtual machine for mobile
devices, called DVM (Dalvik Virtual Machine).
6)Doesandr
oidsuppor
tot
herl
anguagest
hanj
ava?
Yes, an android app can be developed in C/C++ also using android NDK (Native Development Kit). It
makes the performance faster. It should be used with Android SDK.
7)Whatar
ethecor
ebui
l
dingbl
ocksofandr
oid?
The core building blocks of Android are:

o Activity o Service
o View o Content Provider
o Intent o Fragment etc.
8)Whati
sact
i
vit
yinAndr
oid?
Activity is like a frame or window in java that represents GUI. It represents one screen of android.
9)Whatar
ethel
i
fec
ycl
emet
hodsofandr
oidact
i
vit
y?
There are 7 life-cycle methods of activity. They are as follows:

1. onCreate() 5. onStop()
2. onStart() 6. onRestart()
3. onResume() 7. onDestroy()
4. onPause()

Downloaded by prerna Mutreja ([email protected])


lOMoARcPSD|25644675

10)Whati
sint
ent
?
It is a kind of message or information that is passed to the components. It is used to launch an
activity, display a web page, send SMS, send email, etc. There are two types of intents in android:

1. Implicit Intent

2. Explicit Intent
11)Howar
evi
ewel
ement
sident
i
fiedi
ntheandr
oidpr
ogr
am?
View elements can be identified using the keyword findViewById.
12)DefineAndr
oidt
oast
.
An android toast provides feedback to the users about the operation being performed by them. It
displays the message regarding the status of operation initiated by the user.
13)Gi
veal
i
stofi
mpot
entf
older
sinandr
oid
The following folders are declared as impotent in android:

o AndroidManifest.xml o src/
o build.xml o res/
o bin/ o assets/
14)Expl
aint
heuseof'
bundl
e'i
nandr
oid?
We use bundles to pass the required data to various subfolders.
15)Whati
sanappl
i
cat
i
onr
esour
cefil
e?
The files which can be injected for the building up of a process are called as application resource file.
16)Whati
stheuseofLI
NUXI
Dinandr
oid?
A unique Linux ID is assigned to each application in android. It is used for the tracking of a process.
17)Cant
hebyt
ecodebewr
it
teni
njav
aber
unonandr
oid?
No
18)Li
stt
hev
ari
ouss
tor
agest
hatar
epr
ovi
dedbyAndr
oid.
The various storage provided by android are:

o Shared Preferences o SQLite Databases


o Internal Storage o Network Connection
o External Storage
19)Howar
elay
out
spl
acedi
nAndr
oid?
Layouts in Android are placed as XML files.
20)Wher
ear
elay
out
spl
acedi
nAndr
oid?
Layouts in Android are placed in the layout folder.
21)Whati
sthei
mpl
i
citi
ntenti
nandr
oid?
The Implicit intent is used to invoke the system components.
22)Whati
sexpl
i
citi
ntenti
nandr
oid?
An explicit intent is used to invoke the activity class.
23)Howt
ocal
lanot
heract
i
vit
yinandr
oid?
1. Intent i = new Intent(getApplicationContext(), ActivityTwo.class);

2. startActivity(i);
24)Whati
sser
vicei
nandr
oid?
A service is a component that runs in the background. It is used to play music, handle network
transaction, etc.

More details...

Downloaded by prerna Mutreja ([email protected])


lOMoARcPSD|25644675

25)Whati
sthenameoft
hedat
abaseusedi
nandr
oid?
SQLite: An opensource and lightweight relational database for mobile devices.
26)Whati
sAAPT?
AAPT is an acronym for android asset packaging tool. It handles the packaging process.
27)Whati
sacont
entpr
ovi
der
?
A content provider is used to share information between Android applications.
28)Whati
sfr
agment
?
The fragment is a part of Activity by which we can display multiple screens on one activity.
29)Whati
sADB?
ADB stands for Android Debug Bridge. It is a command line tool that is used to communicate with the
emulator instance.
30)Whati
sNDK?
NDK stands for Native Development Kit. By using NDK, you can develop a part of an app using native
language such as C/C++ to boost the performance.
31)Whati
sANR?
ANR stands for Application Not Responding. It is a dialog box that appears if the application is no
longer responding.
32)Whati
stheGoogl
eAndr
oidSDK?
The Google Android SDK is a toolset which is used by developers to write apps on Android-enabled
devices. It contains a graphical interface that emulates an Android-driven handheld environment and
allows them to test and debug their codes.
33)Whati
sanAPKf
ormat
?
APK is a short form stands for Android Packaging Key. It is a compressed key with classes, UI's,
supportive assets and manifest. All files are compressed to a single file is called APK.
34)Whi
chl
anguagedoesAndr
oidsuppor
ttodev
elopanappl
i
cat
i
on?
Android applications are written by using the java (Android SDK) and C/C++ (Android NDK).
35)Whati
sADTi
nAndr
oid?
ADT stands for Android Development Tool. It is used to develop the applications and test the
applications.
36)Whati
sVi
ewGr
oupi
nAndr
oid?
View Group is a collection of views and other child views. It is an invisible part and the base class for
layouts.
37)Whati
stheAdapt
eri
nAndr
oid?
An adapter is used to create a child view to present the parent view items.
38)Whati
sni
ne-
pat
chi
magest
ool
inAndr
oid?
We can change bitmap images into nine sections with four corners, four edges, and an axis.
39)Whi
chk
erneli
susedi
nAndr
oid?
Android is a customized Linux 3.6 kernel.
40)Whati
sappl
i
cat
i
onWi
dget
sinAndr
oid?
Application widgets are miniature application views that can be embedded in other applications and
receive periodic updates.
41)Whi
cht
ypesofflagsar
eusedt
orunanappl
i
cat
i
ononAndr
oid?
Following are two types of flags to run an application in Android:

o FLAG_ACTIVITY_NEW_TASK

o FLAG_ACTIVITY_CLEAR_TOP
42)Whati
sasi
ngl
etonc
lassi
nAndr
oid?
A singleton class is a class which can create only an object that can be shared by all other classes.
43)Whati
ssl
eepmodei
nAndr
oid?
In sleep mode, CPU is slept and doesn't accept any commands from android device except Radio
interface layer and alarm.

Downloaded by prerna Mutreja ([email protected])


lOMoARcPSD|25644675

44)Whatdoy
oumeanbyadr
awabl
efol
deri
nAndr
oid?
In Android, a drawable folder is compiled a visual resource that can use as a background, banners,
icons, splash screen, etc.
45)Whati
sDDMS?
DDMS stands for Dalvik Debug Monitor Server. It gives the wide array of debugging features:

1. Port forwarding services

2. Screen capture

3. Thread and heap information

4. Network traffic tracking

5. Location data spoofing


46)DefineAndr
oidAr
chi
t
ect
ure
?
The Android architecture consists of 4 components:

1. Linux Kernal

2. Libraries

3. Android Framework

4. Android Applications
47)Whati
sapor
tabl
ewi
-fihot
spot
?
The portable wi-fi hotspot is used to share internet connection to other wireless devices.
48)Namet
hedi
al
ogboxwhi
chi
ssuppor
tedbyAndr
oid?
o Alert Dialog

o Progress Dialog

o Date Picker Dialog

o Time picker Dialog


49)Namesomeex
cept
i
onsi
nAndr
oid?
o Inflate Exception

o Surface.OutOfResourceException

o SurfaceHolder.BadSurfaceTypeException

o WindowManager.BadTokenException
50)Whatar
ethebas
ict
ool
susedt
odev
elopanAndr
oidapp?
o JDK

o Eclipse+ADT plugin

o SDK Tools

Downloaded by prerna Mutreja ([email protected])

You might also like