0% found this document useful (0 votes)
15 views55 pages

Android Development Basics and Setup Guide

The document provides an overview of Android, a Linux-based operating system for mobile devices developed by Google, including its features, application development environment, and the necessary tools for setting up development. It discusses the Android Software Development Kit (SDK), the Dalvik Virtual Machine, and the APK file format, detailing the components and structure of Android applications. Additionally, it outlines the installation process for Java Development Kit and Android Studio, as well as the importance of various SDK packages for development.

Uploaded by

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

Android Development Basics and Setup Guide

The document provides an overview of Android, a Linux-based operating system for mobile devices developed by Google, including its features, application development environment, and the necessary tools for setting up development. It discusses the Android Software Development Kit (SDK), the Dalvik Virtual Machine, and the APK file format, detailing the components and structure of Android applications. Additionally, it outlines the installation process for Java Development Kit and Android Studio, as well as the importance of various SDK packages for development.

Uploaded by

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

UNIT – I What is Android?

, Setting up development environment, Dalvik Virtual Machine &


.apk file extension, Fundamentals: Basic Building blocks - Activities, Services, Broadcast
Receivers & Content providers, UI Components - Views & notifications, Components for
communication - Intents & Intent Filters, AndroidAPI levels (versions & version names),
Application Structure (in detail), [Link], uses-permission& uses-sdk,Resources &
[Link], Assets, Layouts & Drawable Resources, Activities and Activity lifecycle.

What is Android

Before learning all topics of android, it is required to know 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 −

[Link]. Feature & Description

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

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

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

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

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

Categories of Android applications

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

Setup Android Environment for Development


You need some environment to develop your apps. Therefore, first you will be required to
download the necessary tools, SDKs and setup files to setup the environment for development.
You can use a macOS, Windows or a Linux platform for your Android Application
Development. All required packages, tools and other required files can be downloaded from the
internet. Following are the names of the files, along with their descriptions that you will be
required for developing Android apps.

Open the toolbox, you will find the following tools that are necessary for setting up an Android
development environment.

• Java SE Development Kit (JDK)


• Android Software Development Kit (SDK)
• Integrated Development Environment (IDE)
o Android Studio; or
o Eclipse + Android Developer Tools (ADT)

Java SE Development Kit (JDK)


The JDK is a set of Java libraries for building applications, applets, and components using the
Java programming language. The JDK includes tools useful for developing and testing programs
written in the Java programming language and running on the Java platform. Since the natural
language of Android programming is Java, the JDK is a necessary tool to have in your Anrdoid
development environment. Among other things, it consists of the following essential tools:

• 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

Android Software Development Kit (SDK)

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:

• Android-specific libraries for building Android applications.


• A command-line tool for managing Android projects in window terminal.
• Dalvik Virtual Machine for compiling Android applications.
• Android Emulator for test running Android applications without a physical device.
• Dalvik Debug Monitor Server (DDMS) for debugging Android applications.

Integrated Development Environment (IDE)

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

An IDE is a software application that facilitates application development. In general, an IDE


offers a composing and editing environment that consists of a code editor, a compiler, a
debugger, and a graphical user interface (GUI) builder. It provides an integrated environment
whereby a developer can quickly execute different aspects of application development all-under-
one-roof without the need to switch to other applications. A good IDE makes you more
productive and efficient. Projects can get off the ground faster with the help of scaffolding,
coding can moves faster with the help of intelligent auto completes and refactoring tools,
applications become more maintainable with the help of integrated unit testing tools.

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 with Android Development Kit (ADT)

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.

Setting Up an Android 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...

Step 0 - Installing Java Development Kit (JDK)

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.

Step 1 - Installing Android Studio

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.

• By default, your Android Studio will be located


at C:\Users\<user>\AppData\Local\Android\android-studio which contains the tools and SDK
packages.
• Setting up Android Studio on Linux:
1. Unpack the downloaded tar file, "android-studio-bundle-<version>.tgz", into an appropriate
location for your applications.
2. To launch Android Studio, navigate to the android-studio/bin/ directory in a terminal and
execute [Link].

You can add android-studio/bin/ to the PATH environmental variable so that you can start
Android Studio from any directory.

Catch a glimpse of the installing screen in Figure 3.


Figure 3: Android Studio Installing...

Once installed, your Android Studio directory should look like that as shown in Figure 4.

Figure 4: Android Studio Directory

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

Figure 6: Android Studio Welcomes You

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

Step 2 - Adding SDK Packages


Android SDK organizes tools, platforms, and other components into packages that you can
download using the Android SDK Manager. The beauty of this is that when exisiting SDK tools
are updated or a new platform or new components are released, the user can use the SDK
Manager to quickly download and add them to the Android Studio. To launch the SDK Manager,
on the Welcome screen, select Configure > SDK Manager. (Figures 7 and 8)

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.

Step 3 - Adding New Sites

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

Dalvik Virtual Machine | DVM

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

• DVM supports the Android operating system only.


• In DVM executable is APK.
• Execution is faster.
• From Android 2.2 SDK Dalvik has it’s own JIT (Just In Time) compiler.
• DVM has been designed so that a device can run multiple instances of the Virtual Machine
effectively.
• Applications are given their own instances.

Disadvantages

• DVM supports only Android Operating System.


• For DVM very few Re-Tools are available.
• Requires more instructions than register machines to implement the same high-level code.
• App Installation takes more time due to dex.
• More internal storage is required.

What is an APK file?


An APK file is an app created for Android, Google's mobile operating system. Some apps come
pre-installed on Android devices, while other apps can be downloaded from Google Play. Apps
downloaded from Google Play are automatically installed on your device, while those
downloaded from other sources must be installed manually.

APK file open in Windows Explorer after extraction

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

What does an APK file contain?

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.

How do I view the contents of an 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.

How to install an APK on your Android device

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.

How to install APK Files from your computer

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.

What Are Main Building Blocks?

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.

i. A website consists of multiple pages, so does an Android application consist of multiple


activities.
ii. Just like a website has a “home page,” an Android app has a “main” activity, usually the
one that is shown first when you launch the application.
iii. And just like a website has to provide some sort of navigation among various pages, an
Android app should do the same.
iv. On the Web, you can jump from a page on one website to a page on another. Similarly, in
Android, you could be looking at an activity of one application, but shortly after you
could start another activity in a completely separate application. For example, if you are
in your Contacts app and you choose to text a friend, you’d be launching the activity to
compose a text message in the Messaging application.

Activity Life Cycle

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.

Stopped activities can be removed from memory at any point.

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.

Services have a much simpler life cycle than activities.

Fig. Service life cycle

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 −

[Link] Part & Description

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.

Create Content Provider

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.

2 Modify main activity file [Link] to add two new


methods onClickAddName() and onClickRetrieveStudents().

3 Create a new java file called [Link] under the


package [Link] to define your actual provider and associated methods.

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.

6 No need to change [Link] studio take care of [Link] file.

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

• onCreate() This method is called when the provider is started.


• query() This method receives a request from a client. The result is returned as a Cursor
object.
• insert()This method inserts a new record into the content provider.
• delete() This method deletes an existing record from the content provider.
• update() This method updates an existing record from the content provider.

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.

Creating the Broadcast Receiver

A broadcast receiver is implemented as a subclass of BroadcastReceiver class and overriding


the onReceive() method where each message is received as a Intent object parameter.
Public class MyReceiver extends BroadcastReceiver{
@Override
Public void onReceive(Context context,Intent intent){
[Link](context,"Intent Detected.",Toast.LENGTH_LONG).show();
}
}

Broadcast Receiver in Android

Registering Broadcast Receiver

An application listens for specific broadcast intents by registering a broadcast receiver


in [Link] file. Consider we are going to register MyReceiver for system generated
event ACTION_BOOT_COMPLETED which is fired by the system once the Android system
has completed the boot process.
Broadcast-Receiver

UI Components - Views & notifications

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 class extends Object class and


implements [Link], [Link] and AccessibilityEventSource.

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.

XML syntax for creating a View

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.

Every view in XML has the following format:

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

• In the end, it is closed by />

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.

Apart from the above mentioned attributes, attributes


like gravity, layout_gravity, padding and margin are some other commonly used attributes.

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.

Set Android Notification Properties


The properties of Android notification are set using [Link] object. Some
of the notification properties are mention below:

o setSmallIcon(): It sets the icon of notification.


o setContentTitle(): It is used to set the title of notification.
o setContentText(): It is used to set the text message.
o setAutoCancel(): It sets the cancelable property of notification.
o setPriority(): It sets the priority of notification.

Components for communication - Intents & Intent Filters

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];.

2 Modify src/Main/Java/[Link] file and add the code to define three


listeners corresponding to three buttons defined in layout file.
3 Add a new src/Main/Java/[Link] file to have one custom activity
which will be invoked by different intents.

4 Modify layout XML file res/layout/activity_main.xml to add three buttons in linear


layout.

5 Add one layout XML file res/layout/custom_view.xml to add a simple <TextView>


to show the passed data through intent.

6 Modify [Link] to add <intent-filter> to define rules for your intent to


invoke custom activity.

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

What is ANDROID API Level?

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:

• A core set of packages and classes


• A set of XML elements and attributes for declaring a manifest file
• A set of XML elements and attributes for declaring and accessing resources
• A set of Intents
• A set of permissions that applications can request, as well as permission enforcements included
in the system
Each successive version of the Android platform can include updates to the Android application
framework API that it delivers.

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.

Platform Version API Level

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

Uses of API Level in Android

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

The [Link] file contains information of your package, including components of


the application such as activities, services, broadcast receivers, content providers etc.

It performs some other tasks also:

o It is responsible to protect the application to access any protected parts by providing


the permissions.
o It also declares the android api that the application is going to use.
o It lists the instrumentation classes. The instrumentation classes provides profiling and
other informations. These informations are removed just before the application is
published etc.

This is the required xml file for all the android application and located inside the root directory.

A simple [Link] file looks like this:

<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]" />

<category android:name="[Link]" />


</intent-filter>
</activity>
</application>
</manifest>
Elements of the [Link] file

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.

android:theme represents a common theme for all the android activities.

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

android:label represents a label i.e. displayed on the screen.

android:name represents a name for the activity class. It is required attribute.

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

It adds a category name to an intent-filter.

Using permissions
In the previous step we looked at how to create permissions, now we will look at how to use
them.

Requesting permissions

To request a permission an app must include a <uses-permission> tag in


its [Link] file.

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

Permissions and the Principle of Least Privilege

The tag <uses-permission> is used to request a permission, and the


attribute android:permission is used to enforce a permission.
Google Play uses the <uses-sdk> attributes declared in your app manifest to filter your app
from devices that do not meet its platform version requirements. Before setting these attributes,
make sure that you understand Google Play filters.

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.

When should you use <uses-permission-sdk-23>?


• For Android SDK 23 and above, you have the option to request the permission at runtime
but the permissions will be in their default state upon installation and the user will not be
prompted at installation. (Essentially this can be used to prompt the user to grant the
permission on a need-to-use basis and you have the opportunity to provide an explanation of
why it's needed.)
• However, for SDK 22 and below, the user is prompted at installation for permissions. As
some permissions can seem suspicious or dodgy to the user, you may not want to request
these for SDK 22 and below as you can't provide an explaination of why you need them
beforehand, hence the <uses-permission-sdk-23> tag.
• Additionally: the documentation is unclear as to whether sdk-23 permissions also cause the
app to be filtered in the Play Store, but if it was your intention to do this, the documentation
recommends that you make use of <uses-feature> elements instead to declare hardware
compatability.

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] file

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.

Note: If you delete [Link] file, android creates it automatically.

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.

• res/raw: In this case, files can only be in the root folder.


3. Compile-time checking: (possible in res/raw)
• assets: Here, the way to read it into InputStream is given below. If the filename doesn’t
exist, then we need to catch it.
[Link](“filename”)
• res/raw folder: Here, the way to read it into InputStream is:
[Link]([Link])
So putting a file in the res/raw folder will provide ensure the correct file-name during compile
time check.
4. List filenames at runtime: (possible in assets)
• assets: If the developer wants to list all the files in the assets folder, he/she has used
the list() function and provide the folder name or ” “ on the root folder as given below.
[Link](FOLDER_NAME)?.forEach {
println(it)
}
• res/raw: This is not possible in this folder. The developer has to know the filename during
development, and not runtime.
So, in assets, one can read the filename during runtime, list them, and use them dynamically. In
res/raw, one needs to code them ready, perhaps in the string resources file.
5. Filename accessible from XML: (possible in res/raw)
• assets: No simple way the developer can arrange an XML file (e.g. [Link])
to point to the file in the assets folder.
• res/raw: In any XML files like in Java, the developer can access the file in res/raw
using @raw/filename easily.
So if you need to access your file in any XML, put it in the res/raw folder. Let’s make a table
to remember the whole scenario easily.

Scenario Assets Folder Res/Raw Folder

Flexible File Name YES NO

Store in subdirectory YES NO

Compile-time checking NO YES

List filenames at runtime YES NO

Filename accessible from XML NO YES


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.

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"/>

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

</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);
}

Android Layout Types

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

[Link] Layout & Description

1 Linear Layout

LinearLayout is a view group that aligns all children in a single direction,


vertically or horizontally.

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

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

4 Absolute Layout
AbsoluteLayout enables you to specify the exact location of its children.
5 Frame Layout
The FrameLayout is a placeholder on screen that you can use to display a single
view.

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

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

Layout Attributes

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

[Link] Attribute & Description

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

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

3 android:layout_height
This is the height of the layout

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

5 android:layout_marginBottom
This is the extra space on the bottom side of the layout.
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.

15 android: padding Right


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

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

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.

The following listing shows an example of a Shape Drawable.

<?xml version="1.0" encoding="UTF-8"?>


<shape
xmlns:android="[Link]
android: shape="rectangle">
<stroke
android: width="2dp"
android: color="#FFFFFFFF"/>
<gradient
android:endColor="#DDBBBBBB"
android:startColor="#DD777777"
android: angle="90"/>
<corners
android:bottomRightRadius="7dp"
android:bottomLeftRadius="7dp"
android:topLeftRadius="7dp"
android:topRightRadius="7dp"/>
</shape>

You could for example assign that drawable to the background property of your layout.

<?xml version="1.0" encoding="utf-8"?>


<LinearLayoutxmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/myshape"
android:orientation="vertical">

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

<?xml version="1.0" encoding="utf-8"?>


<selectorxmlns:android="[Link]

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

<?xml version="1.0" encoding="utf-8"?>


<transitionxmlns:android="[Link]
<itemandroid:drawable="@drawable/first_image"/>
<itemandroid:drawable="@drawable/second_image"/>
</transition>
final ImageView image = (ImageView) findViewById([Link]);
final ToggleButton button = (ToggleButton) findViewById([Link]);
[Link] (new OnClickListener() {
@Override
public void onClick(final View v) {
TransitionDrawable drawable = (TransitionDrawable) [Link]();
if ([Link]()) {
[Link](500);
} else {
[Link](500);
}
}
});
5. Vector drawables

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

// Get the AnimationDrawable object.


AnimationDrawable frameAnimation =(AnimationDrawable)[Link]();

// Start the animation (looped playback by default).


[Link]();
7. 9 Patch Drawables

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.

You might also like