Android Development Basics and Setup Guide
Android Development Basics and Setup Guide
What is Android
Android is a software package and linux based operating system for mobile devices such as
tablet computers and smartphones.
It is developed by Google and later the OHA (Open Handset Alliance). Java language is mainly
used to write the android code even though other languages can be used.
The goal of android project is to create a successful real-world product that improves the mobile
experience for end users.
Why Android?
Features of Android
Android is a powerful operating system competing with Apple 4GS and supports great features.
Few of them are listed below −
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.
Android Applications
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.
.
There are many android applications in the market. The top categories are −
Open the toolbox, you will find the following tools that are necessary for setting up an Android
development environment.
• A Java compiler javac that compiles your .java files into byte code
• A Java Runtime Environment (JRE) that executes the byte code
• A jar tool that helps build jar files
The Android SDK is a set of API libraries and development tools necessary to build, test, and
debug applications for Android. Among other things, It consists of the following main
components:
To write a computer program, at the very least, you will need another computer program to act as
a text editor where you can type the code in plain text. You may
For the purpose of Android development, you can choose between two IDEs - Android
Studio or Eclipse.
• Android Studio
Android Studio is a new open source Android development environment developed by Google
based on the open source community edition of IntelliJ IDEA. It was announced on 16 May
2013 and is currently in beta stage. While Eclipse was built to be a general all-purpose IDE
that can be used with any platforms and any languages, Android Studio is designed specifically
for Android development only. It is designed to provide new features and improvements over
Eclipse ADT and will be the official Android IDE when it is ready.
Eclipse is an open source IDE famous for Java development traditionally. It is written primarily
in Java. It is highly extensible and versatile. By means of appropriate plugins, Eclipse can also be
used to develop applications in other programming languages: Ada, ABAP, C, C++, COBOL,
Fortran, Perl, PHP,Python, R, Ruby, and many more.
To develop Android using Eclipse, a plugin called Android Development Kit (ADT) has to be
added to Eclipse. The ADT extends the capabilities of Eclipse so that a developer can quickly set
up new Android projects, create an application UI, add packages based on the Android
Framework API, debug applications using the Android SDK tools, and export .apk files for
distribution all within a single development environment.
You have learned of the tools that can be used to set up an Android development environment,
let proceed to set up one on your computer. For the IDE, I strongly recommend Android
Studio for the reasons that it is going to be the de facto IDE for Android development and its
many new features as shown in Table 1. I will walk you through setting up an Android
development environment on your computer. Let's get going...
Before setting up Android Studio, your computer will need to have JDK version 6 or greater
installed. To check if your computer have any JDK installed and its version if any, open a
terminal and type javac -version.
To open a terminal in Windows: Start menu > Run > cmd > Enter.
On Mac OS X, open Applications folder > open the Utilities folder > start the Terminal
application.
Once the JDK is installed, head straight to the Android Studio at Android Developers site and
download the correct version of Android Studio according to the platform of your computer.
• Setting up Android Studio on Windows:
1. Double-click the downloaded EXE file, "android-studio-bundle-<version>.exe".
Select Start menu > Computer > System Properties > Advanced System Properties > under
the Advanced tab > Environment Variables, and add a new system variable JAVA_HOME that
points to your JDK folder, for example C:\Program Files\Java\jdk1.6.0_25, and restart the
installation again.
You can add android-studio/bin/ to the PATH environmental variable so that you can start
Android Studio from any directory.
Once installed, your Android Studio directory should look like that as shown in Figure 4.
Once the installation is done, Android Studio will start automatically. If not, just fire it out, you
will then see the launch screen (Figure 5) followed by the welcome screen (Figure 6).
Figure 5: Android Studio Launching...
You may thought that the Android Studio is now ready for use. Not so fast. As the default SDK
does not include everything you need to start developing, you still need to add some more
components to make your Android SDK complete. So do it now...
Figure 7: Configure
Figure 8: SDK Manager
Alternatively, you can launch it inside the Android Studio by selecting Tools > Android > SDK
Manager. The packages in the Android SDK Manager are organized into three sections - Tools,
Platforms, and Extras as shown in Figure 9.
Figure 9: Android SDK Manager
Click on the arrows besides the respective sections to reveal the packages. You can select which
packages to download by toggling the corresponding checkboxes, then click the Install button to
install the selected packages. Go through the list of packages to make sure that you have at least
the following packages installed, if not download and install them.
• Tools
Figure 10: Tools Packages
• Your Android Studio would have come installed with the latest versions of the following SDK
Tools during installation.
o Android SDK Tools
o Android SDK Platform-tools
o Android SDK Build-tools
• Platforms
o SDK Platform - You must download and install at least one platform into your Android Studio
in order to compile your Android application. To get started, To get started, I would recommend
using the latest Android version which currently is SDK Platform Android L Preview, Android
4.4W (API20) SDK Platform, plus Android 2.2 (API 8) SDK Platform as the lowest version.
o System Image - If you want to test your application on the Android emulator, you will need to
download a system image (ARM EABI v71 System Image) that goes with your platform.
o Samples - It is highly recommended that you also download the samples that go with your
platform. These samples contain source code that you can use to learn and reuse in your project.
o Android Support Repository and Android Support Library are required to enable your
application to be backward-compatible with devices running older versions of Android,
o Google Repository and Google Play services are required to enable your application to use
Google Play services APIs.
This step is optional. In addition to the default packages provided by the SDK Manager, you can
add Android packages from third-parties. To manage third party add-ons, in the SDK Manager,
select Tools > Manage Add-on Sites (Figure 13).
As we know the modern JVM is high performance and provides excellent memory management.
But it needs to be optimized for low-powered handheld devices as well.
The Dalvik Virtual Machine (DVM) is an android virtual machine optimized for mobile
devices. It optimizes the virtual machine for memory, battery life and performance.
Dalvik is a name of a town in Iceland. The Dalvik VM was written by Dan Bornstein.
The Dex compiler converts the class files into the .dex file that run on the Dalvik VM. Multiple
class files are converted into one dex file.
Let's see the compiling and packaging process from the source file:
The javac tool compiles the java source file into the class file.
The dx tool takes all the class files of your application and generates a single .dex file. It is a
platform-specific tool.
The Android Assets Packaging Tool (aapt) handles the packaging process.
Advantages
Disadvantages
• Typically, users never see APK files because Android handles app installation in the
background via Google Play or another app distribution platform.
• However, there are many websites that offer direct APK file download for Android users
who want to install apps manually themselves. In this case, you should be careful that
you trust the source of the APK file, because malware can be distributed in APK files,
just as it can in the case of Windows and .EXE files.
Android packages contain all the necessary files for a single Android program. Below is a list of
the most prominent files and folders:
• META-INF/: Contains the manifest file, signature, and a list of resources in the archive
• lib/: Native libraries that run on specific device architectures (armeabi-v7a, x86, etc.)
• res/: Resources, such as images, that were not compiled into [Link]
• assets/: Raw resource files that developers bundle with the app
• [Link]: Describes the name, version, and contents of the APK file
• [Link]: The compiled Java classes to be run on the device (.DEX file)
• [Link]: The compiled resources, such as strings, used by the app (.ARSC file)
mainly .apk file.
APK files are saved in a compressed .ZIP format and can be opened by any Zip decompression
tool. Therefore, if you would like to explore the contents of an APK file, you can rename the file
extension to ".zip" and open the file, or you can open the file directly through a Zip application's
open dialog box.
How do I create APK files? Build-→ Build apk→ Generate signed apk(Google play)
Android apps are developed using Android Studio, the official IDE for Android software
developers. It is available for Windows, Mac, and Linux, and it allows users to develop apps and
prepare them for upload to a distribution service, such as Google Play. When apps are ready,
developers can build them into APK files and sign them for release.
1. You can install APK files on your Android Smartphone or tablet directly from your
browser.
2. Just open your browser, find the APK file you want to download, and tap it – you should
then be able to see it downloading on the top bar of your device.
3. Once it's downloaded, open Downloads, tap on the APK file, and tap Yes when
prompted.
4. The app will begin installing on your device.
1. First, you must find an APK file you want. Search online for an APK file and download
it to an easy-to-find location on your computer (like your desktop).
2. Before you can install it on your phone you will need to make sure that third-party
apps are allowed on your device.
3. Go to Menu > Settings > Security > and check Unknown Sources to allow your phone
to install apps from sources other than the Google Play Store.
4. Newer versions of Android do things a little differently. Rather than check a global
setting to allow installation from unknown sources, you'll be prompted to allow your
browser or file manager to install APKs the first time you attempt to do so.
The main building blocks are components that you use as an application developer to build
Android apps. They are the conceptual items that you put together to create a bigger whole.
When you start thinking about your application, it is good to take a top-down approach. You
design your application in terms of screens, features, and the interactions between them. You
start with conceptual drawing, something that you can represent in terms of “lines and circles.”
This approach to application development helps you see the big picture—how the components fit
together and how it all makes sense.
A Real-World Example
A Real-World Example
Let’s say that we want to build a Twitter app. We know that the user should be able to post status
updates. We also know the user should be able to see what her friends are up to. Those are basic
features. Beyond that, the user should also be able to set her username and password in order to
log into her Twitter account. So, now we know we should have these three screens.
Next, we would like this app to work quickly regardless of the network connection or lack
thereof. To achieve that, the app has to pull the data from Twitter when it’s online and cache the
data locally. That will require a service that runs in the background as well as a database.
Activities
An activity is usually a single screen that the user sees on the device at one time. An application
typically has multiple activities, and the user flips back and forth among them. As such,
activities are the most visible part of your application.
The activity life cycle is managed via Activity Manager. Activity Manager is responsible for
creating, destroying, and managing activities. For example, when the user starts an application
for the first time, the Activity Manager will create its activity and put it onto the screen.
Later, when the user switches screens, the Activity Manager will move that previous activity to
a holding place. This way, if the user wants to go back to an older activity, it can be started more
quickly. Older activities that the user hasn’t used in a while will be destroyed in order to free
more space for the currently active one. This mechanism is designed to help improve the
speed of the user interface and thus improve the overall user experience.
Programming for Android is conceptually different than programming for some other
environments. In Android, you find yourself responding more to certain changes in the state of
your application rather than driving that change yourself. It is a managed, container-based
environment similar to programming for Java applets or servlets.
Figure 4-1. Activity life cycle
<?xml version="1.0" encoding="utf-8"?>
<[Link]
xmlns:android="[Link]
xmlns:app="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="[Link]">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</[Link]>
Starting state
When an activity doesn’t exist in memory, it is in a starting state. While it’s starting up, the
activity will go through a whole set of callback methods that you as a developer have an
opportunity to fill out. Eventually, the activity will be in a running state.
The transition from starting state to running state is one of the most expensive operations in
terms of computing time, and this also directly affects the battery life of the device. This is the
exact reason why we don’t automatically destroy activities that are no longer shown.
Running state
The activity in a running state is the one that is currently on the screen and interacting with the
user. We also say this activity is in focus, meaning that all user interactions—such as typing,
touching the screen, and clicking buttons—are handled by this one activity. As such, there is
only one running activity at any given time.
The running activity is the one that has priority in terms of getting the memory and resources it
needs to run as quickly as possible. This is because Android wants to make sure the running
activity is zippy and responsive to the user.
Paused state
When an activity is not in focus (i.e., not interacting with the user) but still visible on the screen,
we say it’s in a paused state. This is not a typical scenario, because the device’s screen is usually
small, and an activity is either taking up the whole screen or none at all. We often see this case
with dialog boxes that come up in front of an activity, causing it to become Paused. All activities
go through a paused state en route to being stopped.
Paused activities still have high priority in terms of getting memory and other resources.
This is because they are visible and cannot be removed from the screen without making it
look very strange to the user.
Stopped state
When an activity is not visible, but still in memory, we say it’s in a stopped state. Stopped
activity could be brought back to the front to become a Running activity again. Or, it could be
destroyed and removed from memory.
The system keeps activities around in a stopped state because it is likely that the user will still
want to get back to those activities sometime soon, and restarting a stopped activity is far
cheaper than starting an activity from scratch. That is because we already have all the objects
loaded in memory and simply have to bring it all up to the foreground.
Destroyed state
A destroyed activity is no longer in memory. The Activity Manager decided that this activity is
no longer needed and has removed it. Before the activity is destroyed, it can perform certain
actions, such as save any unsaved information. However, there’s no guarantee that your
activity will be stopped prior to being destroyed. It is possible for a paused activity to be
destroyed as well.
Services
Services run in the background and don’t have any user interface components. They can perform
the same actions as activities, but without any user interface. Services are useful for actions that
we want to perform for a while, regardless of what is on the screen. For example, you might
want your music player to play music even as you are flipping between other applications.
The fact that a service runs in the background doesn’t mean it runs on a separate thread. In other
words, services and activities run on the same main application thread, often called the UI thread.
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. A content provider can use
different ways to store its data and the data can be stored in a database, in files, or even over a
network.
sometimes it is required to share data across applications. This is where content providers
become very useful.
Content providers let you centralize content in one place and have many different
applications access it as needed. A content provider behaves very much like a database
where you can query it, edit its content, as well as add or delete content using insert(),
update(), delete(), and query() methods. In most cases this data is stored in
an SQlite database.
A content provider is implemented as a subclass of ContentProvider class and must implement
a standard set of APIs that enable other applications to perform transactions.
public class My Application extends ContentProvider {
}
Content URIs
To query a content provider, you specify the query string in the form of a URI which has
following format −
<prefix>://<authority>/<data_type>/<id>
Here is the detail of various parts of the URI −
1 Prefix
This is always set to content://
authority
2 This specifies the name of the content provider, for example contacts, browser etc. For
third-party content providers, this could be the fully qualified name, such
as [Link]
data_type
3 This indicates the type of data that this particular provider provides. For example, if you
are getting all the contacts from the Contacts content provider, then the data path would
be people and URI would look like thiscontent://contacts/people
Id
4 This specifies the specific record requested. For example, if you are looking for contact
number 5 in the Contacts content provider then URI would look like
this content://contacts/people/5.
This involves number of simple steps to create your own content provider.
• First of all you need to create a Content Provider class that extends
the ContentProviderbaseclass.
• Second, you need to define your content provider URI address which will be used to
access the content.
• Next you will need to create your own database to keep the content. Usually, Android
uses SQLite database and framework needs to override onCreate() method which will
use SQLite Open Helper method to create or open the provider's database. When your
application is launched, the onCreate() handler of each of its Content Providers is called
on the main application thread.
• Next you will have to implement Content Provider queries to perform different database
specific operations.
• Finally register your Content Provider in your activity file using <provider> tag.
• Example
• This example will explain you how to create your own ContentProvider. So let's follow
the following steps to similar to what we followed while creating Hello World Example−
Step Description
1 You will use Android StudioIDE to create an Android application and name it as My
Application under a package [Link], with blank Activity.
4 Register your content provider in your [Link] file using <provider.../> tag
5 Modify the default content of res/layout/activity_main.xml file to include a small GUI to add
students records.
7 Run the application to launch Android emulator and verify the result of the changes done in
the application.
Although small amounts of data can be passed between applications via intents, content
providers are much better suited for sharing persistent data between possibly large datasets.
Figure. Content provider
ContentProvider
getType() This method returns the MIME type of the data at the given URI.
The Android system uses this mechanism all the time. For example, Contacts Provider is a
content provider that exposes all user contact data to various applications. Settings Provider
exposes system settings to various applications, including the built-in Settings application. Media
Store is responsible for storing and sharing various media, such as photos and music, across
various applications. Figure 4-5 illustrates how the Contacts app uses Contacts Provider, a totally
separate application, to retrieve data about users’ contacts. The Contacts app itself doesn’t have
any contacts data, and Contacts Provider doesn’t have any user interface.
Figure 4-5. Contacts application using Contacts Provider to get the data
This separation of data storage and the actual user interface application offers greater flexibility
to mash up various parts of the system.
Content providers are relatively simple interfaces, with the standard insert (), update (), delete (),
and query () methods. These methods look a lot like standard database methods, so it is
relatively easy to implement a content provider as a proxy to the database.
Broadcast Receivers simply respond to broadcast messages from other applications or from
the system itself. These messages are sometime called events or intents. For example,
applications can also initiate broadcasts to let other applications know that some data has been
downloaded to the device and is available fssor them to use, so this is broadcast receiver who
will intercept this communication and will initiate appropriate action.
There are following two important steps to make BroadcastReceiver works for the system
broadcasted intents −
• Creating the Broadcast Receiver.
• Registering Broadcast Receiver
There is one additional steps in case you are going to implement your custom intents then you
will have to create and broadcast those intents.
the interaction of a user with the Android application is through the user interface(UI), hence it
is very important to understand the basics about the User Interface of an android application.
Here in this tutorial, we are going to cover about various Views and ViewGroups and will try to
explain how they can be used to design the User Interface of an android application.
Views
View is the basic building block of UI(User Interface) in android. View refers to
the [Link] class, which is the super class for all the GUI components
like TextView, ImageView, Button etc.
Powered By
View can be considered as a rectangle on the screen that shows some type of content. It can be
an image, a piece of text, a button or anything that an android application can display. The
rectangle here is actually invisible, but every view occupies a rectangle shape.
The question that might be bothering you would be , what can be the size of this rectangle?
The answer is either we can set it manually, by specifying the exact size(with proper units) or by
using some predefined values. These predefined values are match_parent and wrap_content.
match_parent means it will occupy the complete space available on the display of the device.
Whereas, wrap_content means it will occupy only that much space as required for its content to
display.
A View is also known as Widget in Android. Any visual(that we can see on screen) and
interactive(with which user can interact with) is called a Widget.
Now, as we have explained earlier as well, to draw anything in your android application, you
will have to sepcify it in the design XML files. And to add functionality we will create Java files.
<ViewName
Attribute1=Value1
Attribute2=Value2
Attribute3=Value3
AttributeN=ValueN
/>
• It always start with an angle bracket, followed by the View name. We will introduce you
to various types of Views very soon.
• Then we write attributes that will define how that view will look on the screen of the
application along with a value for the attribute. Each view has its own attributes which
we will discuss in the next few tutorials which will cover various typs of views.
So, every View subclass needs to follow this format so that it can appear on the screen of the
app. And this format is nothing but default XML style. Right!
There are two attributes that are necessary for every View. These
are: android:layout_height and android:layout_width.
These attributes define the size of the invisible rectangle that a view makes. Using these
attributes we can easily control the size for every view in our android application.
Android Notification
Android Notification provides short, timely information about the action happened in the
application, even it is not running. The notification displays the icon, title and some amount of
the content text.
Intents
Intents are messages that are sent among the major building blocks. They trigger an activity to
start up, tell a service to start or stop, or are simply broadcasts. Intents are asynchronous;
meaning the code that sends them doesn’t have to wait for them to be completed.
Intent could be explicit or implicit. In an explicit intent, the sender clearly spells out which
specific component should be on the receiving end. In an implicit intent, the sender specifies the
type of receiver.
For example, your activity could send an intent saying it simply wants someone to open up a
web page. In that case, any application that is capable of opening a web page could “compete” to
complete this action.
Figure 4-2. Intents
Intent Filters
Intent has been used to call an another activity. Android OS uses filters to pinpoint the set of
Activities, Services, and Broadcast receivers that can handle the Intent with help of specified set
of action, categories, data scheme associated with an Intent. You will use <intent-
filter> element in the manifest file to list down actions, categories and data types associated
with any activity, service, or broadcast receiver.
Following is an example of a part of [Link] file to specify an
activity [Link] [Link] which can be invoked by either of the
two mentioned actions, one category, and one data −
<activityandroid:name=".CustomActivity"
android:label="@string/app_name">
<intent-filter>
<actionandroid:name="[Link]"/>
<actionandroid:name="[Link] [Link]"/>
<categoryandroid:name="[Link]"/>
<data android:scheme="http"/>
</intent-filter>
</activity>
Once this activity is defined along with above mentioned filters, other activities will be able to
invoke this activity using either the [Link], or using
the [Link] [Link] action provided their category
is [Link].
The <data> element specifies the data type expected by the activity to be called and for above
example our custom activity expects the data to start with the "[Link]
There may be a situation that intent can pass through the filters of more than one activity or
service, the user may be asked which component to activate. An exception is raised if no target
can be found.
There are following test Android checks before invoking an activity −
• A filter <intent-filter> may list more than one action as shown above but this list
cannot be empty; a filter must contain at least one <action> element, otherwise it will
block all intents. If more than one actions are mentioned then Android tries to match one
of the mentioned actions before invoking the activity.
• A filter <intent-filter> may list zero, one or more than one categories. if there is no
category mentioned then Android always pass this test but if more than one categories
are mentioned then for an intent to pass the category test, every category in the Intent
object must match a category in the filter.
• Each <data> element can specify a URI and a data type (MIME media type). There are
separate attributes like scheme, host, port, and path for each part of the URI. An Intent
object that contains both a URI and a data type passes the data type part of the test only
if its type matches a type listed in the filter.
Example
Following example is a modification of the above example. Here we will see how Android
resolves conflict if one intent is invoking two activities defined in , next how to invoke a custom
activity using a filter and third one is an exception case if Android does not file appropriate
activity defined for an intent.
Step Description
1 You will use android studio to create an Android application and name it as My
Application under a package [Link];.
7 Run the application to launch Android emulator and verify the result of the changes
done in the application.
API Level is an integer value that uniquely identifies the framework API revision offered by a
version of the Android platform.
The Android platform provides a framework API that applications can use to interact with the
underlying Android system. The framework API consists of:
Updates to the framework API are designed so that the new API remains compatible with earlier
versions of the API. That is, most changes in the API are additive and introduce new or
replacement functionality. As parts of the API are upgraded, the older replaced parts are
deprecated but are not removed, so that existing applications can still use them. In a very small
number of cases, parts of the API may be modified or removed, although typically such changes
are only needed to ensure API robustness and application or system security. All other API parts
from earlier revisions are carried forward without modification.
The framework API that an Android platform delivers is specified using an integer identifier
called "API Level". Each Android platform version supports exactly one API Level, although
support is implicit for all earlier API Levels (down to API Level 1). The initial release of the
Android platform provided API Level 1 and subsequent releases have incremented the API
Level.
The following table specifies the API Level supported by each version of the Android platform.
Android 2.3.3 10
Android 2.3 9
Android 2.2 8
Android 2.1 7
Android 2.0.1 6
Android 2.0 5
Android 1.6 4
Android 1.5 3
Android 1.1 2
Android 1.0 1
The API Level identifier serves a key role in ensuring the best possible experience for users and
application developers:
• It lets the Android platform describe the maximum framework API revision that it supports
• It lets applications describe the framework API revision that they require
• It lets the system negotiate the installation of applications on the user's device, such that version-
incompatible applications are not installed.
Each Android platform version stores its API Level identifier internally, in the Android system
itself.
Applications can use a manifest element provided by the framework API — <uses-sdk> — to
describe the minimum and maximum API Levels under which they are able to run, as well as the
preferred API Level that they are designed to support. The element offers three key attributes:
• android:minSdkVersion — Specifies the minimum API Level on which the application is able to
run. The default value is "1".
• android:targetSdkVersion — Specifies the API Level on which the application is designed to
run. In some cases, this allows the application to use manifest elements or behaviors defined in
the target API Level, rather than being restricted to using only those defined for the minimum
API Level.
• android:maxSdkVersion — Specifies the maximum API Level on which the application is able
to run. Important: Please read the <uses-sdk> documentation before using this attribute.
For example, to specify the minimum system API Level that an application requires in order to
run, the application would include in its manifest a <uses-sdk> element with
a android:minSdkVersion attribute. The value of android:minSdkVersion would be the integer
corresponding to the API Level of the earliest version of the Android platform under which the
application can run.
When the user attempts to install an application, or when revalidating an appplication after a
system update, the Android system first checks the <uses-sdk> attributes in the application's
manifest and compares the values against its own internal API Level. The system allows the
installation to begin only if these conditions are met:
• If a android:minSdkVersion attribute is declared, its value must be less than or equal to the
system's API Level integer. If not declared, the system assumes that the application requires API
Level 1.
• If a android:maxSdkVersion attribute is declared, its value must be equal to or greater than the
system's API Level integer. If not declared, the system assumes that the application has no
maximum API Level. Please read the <uses-sdk> documentation for more information about
how the system handles this attribute.
When declared in an application's manifest, a <uses-sdk> element might look like this:
<manifest>
<uses-sdkandroid:minSdkVersion="5"/>
...
</manifest>
[Link] file in android
This is the required xml file for all the android application and located inside the root directory.
<manifest xmlns:android="[Link]
package="[Link]"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/title_activity_main" >
<intent-filter>
<action android:name="[Link]" />
The elements used in the above xml file are described below.
<manifest>
manifest is the root element of the [Link] file. It has package attribute that
describes the package name of the activity class.
<application>
application is the subelement of the manifest. It includes the namespace declaration. This
element contains several subelements that declares the application component such as activity
etc.
The commonly used attributes are of this element are icon, label, theme etc.
android: icon represents the icon for all the android application components.
android:label works as the default label for all the application components.
<activity>
activity is the subelement of application and represents an activity that must be defined in the
[Link] file. It has many attributes such as label, name, theme, launch Mode etc.
<intent-filter>
intent-filter is the sub-element of activity that describes the type of intent to which activity,
service or broadcast receiver can respond to.
<action>
It adds an action for the intent-filter. The intent-filter must have at least one action element.
<category>
Using permissions
In the previous step we looked at how to create permissions, now we will look at how to use
them.
Requesting permissions
<manifest…>
<uses-permissionandroid:name="[Link].SOME_PERMISSION">
</manifest>
This example requests the permission SOME_PERMISSION in order to access some capability
provided by myamazingapp.
Android has many built-in permissions that an app can request. For example, an app can request
access to the internet as follows:
<manifest…>
<uses-permissionandroid:name="[Link]">
</manifest>
If the requested permission is a dangerous permission the user will have to agree to grant the app
that permission.
The android:permission attribute can also be set for the <application> element in the
app’s [Link] file. This becomes the overall default permission for all the app’s
components that do not have their own attribute: permission set.
syntax:
<uses-sdkandroid:minSdkVersion="integer"
android:targetSdkVersion="integer"
android:maxSdkVersion="integer"/>
contained in:
<manifest>
description:
Lets you express an application's compatibility with one or more versions of the Android
platform, by means of an API Level integer. The API Level expressed by an application
will be compared to the API Level of a given Android system, which may vary among
different Android devices.
attributes:
android:minSdkVersion
An integer designating the minimum API Level required for the application to run. The
Android system will prevent the user from installing the application if the system's API
Level is lower than the value specified in this attribute. You should always declare this
attribute.
android: targetSdkVersion
An integer designating the API Level that the application targets. If not set, the default
value equals that given to minSdkVersion.
This attribute informs the system that you have tested against the target version and the
system should not enable any compatibility behaviors to maintain your app's forward-
compatibility with the target version. The application is still able to run on older versions
(down to minSdkVersion).
As Android evolves with each new version, some behaviors and even appearances might
change. However, if the API level of the platform is higher than the version declared by
your app's targetSdkVersion, the system may enable compatibility behaviors to ensure
that your app continues to work the way you expect. You can disable such compatibility
behaviors by specifying targetSdkVersion to match the API level of the platform on
which it's running.
For example, setting this value to "11" or higher allows the system to apply a new default
theme (Holo) to your app when running on Android 3.0 or higher and also disables screen
compatibility mode when running on larger screens (because support for API level 11
implicitly supports larger screens).
There are many compatibility behaviors that the system may enable based on the value
you set for this attribute. Several of these behaviors are described by the corresponding
platform versions in the Build.VERSION_CODES reference.
Resources
Class for accessing an application's resources. This sits on top of the asset manager of the
application (accessible through getAssets()) and provides a high-level API for getting typed data
from the assets.
The Android resource system keeps track of all non-code assets associated with an application.
You can use this class to access your application's resources. You can generally acquire
the Resources instance associated with your application with getResources().
The Android SDK tools compile your application's resources into the application binary at build
time. To use a resource, you must install it correctly in the source tree (inside your
project's res/ directory) and build your application. As part of the build process, the SDK tools
generate symbols for each resource, which you can use in your application code to access the
resources.
Using application resources makes it easy to update various characteristics of your application
without modifying code, and—by providing sets of alternative resources—enables you to
optimize your application for a variety of device configurations (such as for different languages
and screen sizes). This is an important aspect of developing Android applications that are
compatible on different types of devices.
After Build.VERSION_CODES#R, Resources must be obtained by Activity or Context created
with [Link](int, Bundle). Application#getResources() may report wrong
values in multi-window or on secondary displays.
Android [Link] is an auto-generated file by aapt (Android Asset Packaging Tool) that contains
resource IDs for all the resources of res/ directory.
If you create any component in the activity_main.xml file, id for the corresponding component is
automatically created in this file. This id can be used in the activity source file to perform any
action on the component.
It can be noticed that unlike Eclipse ADT (App Development Tools), Android
Studio doesn’t contain an Assets folder in which we usually use to keep the web files
like HTML. Assets provide a way to add arbitrary files like text, XML, HTML, fonts, music,
and video in the application. If one tries to add these files as “resources“, Android will treat
them into its resource system and you will be unable to get the raw data. If one wants to access
data untouched, Assets are one way to do it. But the question arises is why in the asset folder?
We can do the same things by creating a Resource Raw Folder. So let discuss how the
assets folder is different from the Resource Raw folder?
How the asset folder is different from the Resource Raw folder?
In Android one can store the raw asset file like JSON, Text, mp3, HTML, pdf, etc
in two possible locations:
1. assets
2. res/raw folder
Both of them appears to be the same, as they can read the file and generate InputStream as
below
// From assets
[Link](assetPathFilename)
// From res/raw
[Link](resourceRawFilename)
But when to use which folder?
Below is some guidance that might be helpful to choose
1. Flexible File Name: (assets is better)
• assets: The developer can name the file name in any way, like having capital letters
(fileName) or having space (file name).
• res/raw: In this case, the name of the file is restricted. File-based resource names must
contain only lowercase a-z, 0-9, or underscore.
2. Store in subdirectory: (possible in assets)
• assets: If the developer wants to categories the files into subfolders, then he/she can do it in
assets like below.
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.
This tutorial is more about creating your GUI based on layouts defined in XML file. 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="[Link]
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"/>
</LinearLayout>
Once your layout has created, you can load the layout resource from your application code, in
your [Link]() callback implementation as shown below −
publicvoid onCreate(Bundle savedInstanceState){
[Link](savedInstanceState);
setContentView([Link].activity_main);
}
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.
1 Linear Layout
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:
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.
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_height
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.
17 android:paddingBottom
This is the bottom padding filled for the layout.
4. XML Drawables
4.1. Shape Drawables
Shape Drawables are XML files which allow to define a geometric object with colors, borders and
gradients which can get assigned to Views. The advantage of using XML Shape Drawables is that
they automatically adjust to the correct size.
You could for example assign that drawable to the background property of your layout.
<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
</EditText>
<RadioGroup
android:id="@+id/radioGroup1"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RadioButton
android:id="@+id/radio0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="@string/celsius">
</RadioButton>
<RadioButton
android:id="@+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/fahrenheit">
</RadioButton>
</RadioGroup>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/calc"
android:onClick="myClickHandler">
</Button>
</LinearLayout>
4.2. State Drawables
State drawables allow to define states. For each state a different drawable can get assigned to
the View. For example the following defines different drawables for a button depending on its
state.
<itemandroid:drawable="@drawable/button_pressed"
android:state_pressed="true"/>
<itemandroid:drawable="@drawable/button_checked"
android:state_checked="true"/>
<itemandroid:drawable="@drawable/button_default"/>
</selector>
4.3. Transition Drawables
Transition Drawables allow to define transitions which can be triggered in the coding.
As of API level 21 you can use vector drawables in your Android application. These are similar to
svg files but with a limited scope. Using vector drawables automatically scale to the density of the
device. The following listing demonstrates its usage in the [Link] file.
<vectorxmlns:android="[Link]
android: height="64dp"
android: width="64dp"
android:viewportHeight="600"
android: viewportWidth="600">
<group
android:name="rotationGroup"
android:pivotX="300.0"
android:pivotX="300.0"
android: rotation="45.0">
<path
android:name="v"
android:fillColor="#000000"
android:pathData="M300,70 l 0,-70 70,70 0,0 -70,70z"/>
</group>
</vector>
6. Animation Drawables
<!-- Animation frames are phase*.png files inside the
res/drawable/ folder -->
<animation-listandroid:id="@+id/selected"android:oneshot="false">
<itemandroid:drawable="@drawable/phase1"android:duration="400"/>
<itemandroid:drawable="@drawable/phase2"android:duration="400"/>
<itemandroid:drawable="@drawable/phase3"android:duration="400"/>
</animation-list>
ImageView img =(Image View)findViewById([Link]);
[Link] ([Link].your_animation_file);
9 Patch drawables are Drawables which have a one pixel additional border. On the top and left
you define the area which should be scaled if the Drawable is to small for the view. This is the
stretch area.
On the right and bottom side you define the area where a text should be placed if this Drawable is
used on a view which can write text on it, e.g. a Button.
The ADT supplies the draw9patch program in the android-sdk/tools installation folder, which
makes it easy to create 9 Patch drawables.
8. Custom Drawables
You can also create custom Drawable, which can use the Canvas API for their display. For these
drawables you can use the full Canvas API to design them to your need.