Android Notes
Android Notes
Android Notes
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.
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.
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.
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 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.
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)
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.
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.
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 −
1 Activities: They dictate the UI and handle the user interaction to the smart phone
screen.
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{
}
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
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.
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:
For example, you may write the following code to view the webpage.
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.
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.
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.−
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.
At the final stage it going to be open development tool to write the application code.
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.
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.
<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>
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
<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>
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.
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.
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.
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.
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.
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 )
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.
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
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.
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.
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.
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.
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
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.
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.
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.
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.
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"/>
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);
}
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.
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:
1
android:idThis is the ID which uniquely identifies the view.
2
android:layout_widthThis is the width of the layout.
3
android:layout_heightThis is the height of the layout
4
android:layout_marginTopThis is the extra space on the top side of the layout.
5
android:layout_marginBottomThis is the extra space on the bottom side of the
layout.
6
android:layout_marginLeftThis is the extra space on the left side of the layout.
7
android:layout_marginRightThis is the extra space on the right side of the layout.
8
android:layout_gravityThis specifies how child Views are positioned.
9
android:layout_weightThis specifies how much of the extra space in the layout
should be allocated to the View.
10
android:layout_xThis specifies the x-coordinate of the layout.
11
android:layout_yThis specifies the y-coordinate of the layout.
12
android:layout_widthThis is the width of the layout.
13
android:layout_widthThis is the width of the layout.
14
android:paddingLeftThis is the left padding filled for the layout.
15
android:paddingRightThis is the right padding filled for the layout.
16
android:paddingTopThis is the top padding filled for the layout.
17
android:paddingBottomThis 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.
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
center_horizonta 0x01 Place object in the horizontal center of its container, not
l changing its size.
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 −
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.
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.
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.
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)
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.
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"
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.
2 Modify src/MainActivity.java file to add click event listeners and handlers for the two
buttons defined.
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.
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.
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.
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.
GooglePlayServicesClient.ConnectionCallbacks
GooglePlayServicesClient.OnConnectionFailedListener
These interfaces provide following important callback methods, which you need to implement in
your activity class −
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.
1
abstract void onLocationChanged(Location location)
This callback method is used for receiving notifications from the LocationClient when
the location has changed.
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.
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.
1 You will use Android studio IDE to create an Android application and name it
as Tutorialspoint under a package com.example.tutorialspoint7.myapplication.
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.
7 Run the application to launch Android emulator and verify the result of the changes done
in the application.
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()
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:
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...
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.
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:
2. Screen capture
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 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