Module1 MAD
Module1 MAD
Android is a Linux based operating system developed by Google for Smartphone’s and other
mobile devices (such as tablets). It can run on many different devices from many different
manufacturers.
Android includes a software development kit for writing original code and assembling
software modules to create apps for Android users.
It also provides a marketplace to distribute apps. All together, Android represents an
ecosystem for mobile apps.
Android, Inc. was founded in Palo Alto, California in October 2003 by Andy Rubin, Rich
Miner, Nick Sears, and Chris White to develop, in Rubin's words, "smarter mobile devices
those are more aware of its owner's location and preferences".
Google acquired Android Inc. on August 17, 2005; key employees of Android Inc.,
including Rubin, Miner, and White, stayed at the company after the acquisition.
VTUPulse.com
services, creating new businesses, and providing games and other types of content for users.
Developers choose to develop for Android in order to reach the majority of mobile device
users.
1
Android notes Module 1
Android Architecture Diagram:
Android operating system is roughly divided into five sections and four main layers as
shown below in the architecture diagram.
VTUPulse.com
Applications Layer
Your apps live at this level, along with core system apps for email, SMS messaging,
calendars, Internet browsing, or contacts.
2
Android notes Module 1
Libraries and Android Runtime:
Native libraries such as WebKit, OpenGL, FreeType, SQLite, Media, C runtime library
(libc) etc.
The WebKit library is responsible for browser support.
SQLite is for database
FreeType for font support
Media for playing and recording audio and video formats.
SSL libraries responsible for Internet security
Android Runtime
In android runtime, there are core libraries and DVM (Dalvik Virtual Machine) which is
responsible to run android application. DVM is like JVM but it is optimized for mobile
devices. It consumes less memory and provides fast performance.
Linux kernel
It is the heart of android architecture that exists at the root of android architecture. Linux
kernel is responsible for device drivers, power management, memory management, device
management like camera, keypad, display etc. and resource access.
Many distribution options:
VTUPulse.com
You can distribute your Android app in many different ways: email, website or an app
marketplace such as Google Play.
Android versions:
Android versions= Code Name (Version Name)+ Version number +API level
September 23,
(No codename)[2] 1.0 1 Unsupported
2008
3
Android notes Module 1
September 15,
Donut[3] 1.6 4 Unsupported
2009
October 26,
Eclair[4] 2.0 – 2.1 5–7 Unsupported
2009
December 6,
Gingerbread[6] 2.3 – 2.3.7 9 – 10 Unsupported
2010
February 22,
Honeycomb[7] 3.0 – 3.2.6 11 – 13 Unsupported
2011
October 18,
Ice Cream Sandwich[8] 4.0 – 4.0.4 14 – 15 Unsupported
VTUPulse.com
2011
October 31,
KitKat[10] 4.4 – 4.4.4 19 – 20 Unsupported[11]
2013
4
Android notes Module 1
The challenges of Android app development
While the Android platform provides rich functionality for app development, there are still a
number of challenges you need to address, such as:
Building for a multi-screen world: Devices can come in different sizes and shapes
that affect the screen designs for UI elements in your application.
Getting performance right: how fast it runs, how easily it connects to the network,
and how well it manages battery and memory usage—is affected by factors such as
battery life, multimedia content, and Internet access. You must be aware of these
limitations and write code in such a way that the resource utilization is balanced and
distributed optimally. For example, you will have to balance the background services
by enabling them only when necessary; this will save battery life of the user’s device.
Keeping your code and your users secure: You need to take precautions to secure
your code and the user’s experience when using your app. Use tools such as ProGuard
(provided in Android Studio), which detects and removes unused classes, fields,
methods, and attributes, and encrypt all of your app's code and resources while
packaging the app.
Remaining compatible with older platform versions: Consider how to add new
VTUPulse.com
Android platform version features to an app, while ensuring that the app can still run
on devices with older platform versions.
Understanding the market and the user.
5
Android notes Module 1
The above diagram is a high-level picture of the development process, with the following
steps:
Defining the idea and its requirements: Most apps start with an idea of what it should do.
During this stage the app's requirements are defined.
Prototyping the user interface: Use drawings and prototypes to show what the user
interface would look like, and how it would work.
Developing and testing the app: An app consists of one or more activities. For each activity
you can use Android Studio to do the following, in no particular order:
Create the layout: Place UI elements on the screen in a layout, and assign string resources
and menu items, using the Extensible Markup Language (XML).
Write the Java code: Create source code for components and tests, and use testing and
debugging tools.
Register the activity: Declare the activity in the manifest file.
Define the build: Use the default build configuration or create custom builds for different
versions of your app.
Publishing the app: Assemble the final APK (package file) and distribute it through channels
VTUPulse.com
such as the Google Play.
6
Android notes Module 1
1. The Toolbar. The toolbar carries out a wide range of actions, including running the
Android app and launching Android tools.
2. The Navigation Bar. The navigation bar allows navigation through the project and open
files for editing. It provides a more compact view of the project structure.
3. The Editor Pane. This pane shows the contents of a selected file in the project. For
example, after selecting a layout (as shown in the figure), this pane shows the layout editor
with tools to edit the layout. After selecting a Java code file, this pane shows the code with
tools for editing the code.
4. The Status Bar. The status bar displays the status of the project and Android Studio itself,
as well as any warnings or messages. You can watch the build progress in the status bar.
5. The Project Pane. The project pane shows the project files and project hierarchy.
6. The Monitor Pane. The monitor pane offers access to the TODO list for managing tasks,
the Android Monitor for monitoring app execution (shown in the figure), the logcat for
viewing log messages, and the Terminal application for performing Terminal activities.
Exploring a project:
Each project in Android Studio contains the AndroidManifest.xml file, component source-
VTUPulse.com
code files, and associated resource files. By default, Android Studio organizes your project
files based on the file type, and displays them within the Project: Android view in the left tool
pane, as shown below. The view provides quick access to your project's key files.
7
Android notes Module 1
AndroidManifest.xml
The manifest file which describes the fundamental characteristics of the app and defines each
of its components.
The java folder. This folder includes activities, tests, and other components in Java source
code. Every activity, service, and other component is defined as a Java class, usually in its
own file. The name of the first activity (screen) the user sees, which also initializes app-wide
resources, is customarily MainActivity.
The res folder. This folder holds resources, such as XML layouts, UI strings, and images. An
activity usually is associated with an XML resource file that specifies the layout of its views.
The build.gradle (Module: App) file. This file specifies the module's build configuration.
This file defines the build configuration, including the minSdkVersion attribute that declares
the minimum version for the app, and the targetSdkVersion attribute that declares the highest
(newest) version for which the app has been optimized. This file also includes a list of
dependencies, which are libraries required by the code — such as the AppCompat library for
supporting a wide range of Android versions.
VTUPulse.com
Whatever component you use as a part of your application, you must declare all its
components in a manifest file called AndroidManifest.xml which resides at the root of the
application project directory. This file works as an interface between Android OS and your
application, so if you do not declare your component in this file, then it will not be considered
by the OS. For example, a default manifest file will look like as following file:
8
Android notes Module 1
Android namespace and application tag:
The Android Manifest is coded in XML and always uses the Android namespace:
<xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.helloworld">
Here <application>...</application> tags enclosed the components related to the application.
Automatic backup
The android:allowBackup attribute enables automatic app data backup:
...
android:allowBackup="true"
...
Setting the android:allowBackup attribute to true enables the app to be backed up
automatically and restored as needed.
The app icon
The android:icon attribute sets the icon for the app:
...
android:icon="@mipmap/ic_launcher"
...
VTUPulse.com
The android:icon attribute assigns an icon in the mipmap folder (inside the res folder in
Project: Android view) to the app. The icon appears in the Launcher for launching the app.
The icon is also used as the default icon for app components.
App label and string resources
As you can see in the previous figure, the android:label attribute shows the string "Hello
World" highlighted. If you click on this string, it changes to show the string resource
@string/app_name :
...
android:label="@string/app_name"
...
The app theme
The android:theme attribute sets the app's theme, which defines the appearance of user
interface elements such as text:
...
android:theme="@style/AppTheme">
...
9
Android notes Module 1
Declaring the Android version:
Use the <uses-sdk> manifest tag and its minSdkVersion attribute.
<manifest ... >
<uses-sdk android:minSdkVersion="14" android:targetSdkVersion="19" />
...
</manifest>
Viewing and editing Java code:
Components are written in Java and listed within module folders in the java folder in the
Project: Android view. Each module name begins with the domain name (such as
com.example.android) and includes the app name.
VTUPulse.com
Layout resources are written in XML and listed within the layout folder in the res folder in
the Project: Android view. Click res > layout and then double-click activity_main.xml to
see the layout file in the editing pane.
10
Android notes Module 1
Understanding the build process:
The Android application package (APK) is the package file format for distributing and
installing Android mobile apps. The build process involves tools and processes that
automatically convert each project into an APK. Android Studio uses Gradle as the
foundation of the build system, with more Android-specific capabilities provided by the
Android Plugin for Gradle. This build system runs as an integrated tool from the Android
Studio menu.
Understanding build.gradle files:
Android Studio automatically generates the necessary build files in the Gradle Scripts folder
in Project: Android view. Android Studio build files are named build.gradle as shown
below:
VTUPulse.com
This is the top-level build file for the entire project, located in the root project directory,
which defines build configurations that apply to all modules in your project. This file,
generated by Android Studio, should not be edited.
build.gradle (Module: app):
Android Studio creates separate build.gradle (Module: app) files for each module. You can
edit the build settings to provide custom packaging options for each module, such as
additional build types and product flavors, and to override settings in the manifest or top-
level build.gradle file. This file is most often the file to edit when changing app-level
configurations, such as declaring dependencies in the dependencies section. The following
shows the contents of a project's build.gradle (Module: app) file:
11
Android notes Module 1
Plug-in and Android blocks
In the above build.gradle (Module: app) file, the first statement applies the Android-specific
Gradle plug-in build tasks:
apply plugin: 'com.android.application'
android {...}
The android { } block specifies the following for the build:
The target SDK version for compiling the code: compileSdkVersion 24:
The version of the build tools to use for building the app:buildToolsVersion "24.0.1"
The defaultConfig block
Core settings and entries for the app are specified in a defaultConfig { } block within the
android { } block:
...
defaultConfig {
applicationId "com.example.hello.helloworld"
minSdkVersion 15
targetSdkVersion 23
versionCode 1
versionName "1.0"
testInstrumentationRunner
"android.support.test.runner.AndroidJUnitRunner"
}
VTUPulse.com
Build types
Build types for the app are specified in a buildTypes { } block, which controls how the app
is built and packaged.
...
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
}
}
Dependencies
Dependencies for the app are defined in the dependencies { } block, which is the part of the
build.gradle file that is most likely to change as you start developing code that depends on
other libraries. The block is part of the standard Gradle API and belongs outside the android {
} block.
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:24.2.0'
12
Android notes Module 1
testCompile 'junit:junit:4.12'
}
In the above snippet, the statement compile fileTree(dir: 'libs', include: ['*.jar']) adds a
dependency of all ".jar" files inside the libs directory.
The compile configuration compiles the main application — everything in it is added to the
compilation classpath, and also packaged into the final APK.
VTUPulse.com
13
Android notes Module 1
VTUPulse.com
general log messages in the logcat tab of the Android Monitor pane of Android Studio.
Adding logging statements to your app:
Logging statements add whatever messages you specify to the log. Adding logging
statements at certain points in the code allows the developer to look at values, execution
paths, and exceptions.
For example, the following logging statement adds "MainActivity" and "Hello World" to the
log:
Log.d("MainActivity", "Hello World");
The following are the elements of this statement:
Log : The Log class is the API for sending log messages.
You assign a log level so that you can filter the log messages using the drop-down menu in
the centre of the logcat tab pane. The following are log levels you can assign:
d : Choose Debug or Verbose to see these messages.
e : Choose Error or Verbose to see these messages.
w : Choose Warning or Verbose to see these messages.
i : Choose Info or Verbose to see these messages.
14
Android notes Module 1
Views. Views are user interface elements that display data and respond to user
actions. Every element of the screen is a view. The Android system provides many
different kinds of views.
Presenters. Presenters connect the application's views to the model. They provide the
views with data as specified by the model, and also provide the model with user input
from the view.
Model. The model specifies the structure of the app's data and the code to access and
VTUPulse.com
manipulate the data. Some of the apps you create in the lessons work with models for
accessing data. The Hello Toast app does not use a data model, but you can think of
its logic — display a message, and increase a tap counter — as the model.
Views:
Every element of the screen is a view. The View class represents the basic building block for
all UI components, and the base class for interactive UI components such as buttons,
checkboxes, and text entry fields.
The Android system provides hundreds of predefined views, including those that display:
Text (TextView)
Fields for entering and editing text (EditText)
Buttons users can tap (Button) and other interactive components
Scrollable text (ScrollView) and scrollable items (RecyclerView)
Images (ImageView)
You can specify the views in XML layout resource files. Layout resources are written in
XML and listed within the layout folder in the res folder in the Project: Android view.
15
Android notes Module 1
View groups:
Views can be grouped together inside a view group (ViewGroup), which acts as a container
of views. The relationship is parent-child, in which the parent is a view group, and the child
is a view or view group within the group. The following are common view groups:
ScrollView: A group that contains one other child view and enables scrolling the child
view.
RecyclerView: A group that contains a list of other views or view groups and enables
scrolling them by adding and removing views dynamically from the screen.
VTUPulse.com
In the above figure:
1. The root is view group.
2. The first set of child views and view groups whose parent is the root.
Some view groups are elected or chosen as layouts because they organize child views in a
specific way and are typically used as the root view group. Some examples of layouts are:
S.N. Layout & Description
1 Linear Layout
LinearLayout is a view group that aligns all children (Child View) 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
16
Android notes Module 1
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.
For Example:
VTUPulse.com
In the figure above:
1. LinearLayout root layout, which contains all the child views, set to a vertical orientation.
2. Button ( button_toast ) child view. As the first child view, it appears at the top in the linear
layout.
3. TextView ( show_count ) child view. As the second child view, it appears under the first
child view in the linear layout.
4. Button ( button_count ) child view. As the third child view, it appears under the second
child view in the linear layout.
17
Android notes Module 1
You define views in the layout editor, or by entering XML code. The layout editor shows a
visual representation of XML code.
Using the layout editor: Demonstrate using layout editor
Using XML: Demonstrate using XML.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
... >
<Button
android:id="@+id/button_toast"
android:layout_width="@dimen/my_view_width"
android:layout_height="wrap_content"
... />
<TextView
android:id="@+id/show_count"
android:layout_width="@dimen/my_view_width"
... />
...
VTUPulse.com
android:layout_height="@dimen/counter_height"
</LinearLayout>
XML attributes (view properties):
android:id="@+id/button_count": To uniquely identify a view and reference it from
your code, you must give it an id.
android:layout_width="match_parent": match_parent expands the view to fill its
parent by width or height. When the LinearLayout is the root view, it expands to the
size of the device screen. For a view within a root view group, it expands to the size
of the parent view group.
android:layout_height="match_parent": wrap_content shrinks the view dimensions
just big enough to enclose its content. (If there is no content, the view becomes
invisible.)
18
Android notes Module 1
Style-related attributes:
You specify style attributes to customize the view's appearance. Views that don't have style
attributes, such as android:textColor , android:textSize , and android:background , take on the
styles defined in the app's theme.
The following are style-related attributes used in the XML layout example in the previous
section:
android:background : Specifies a color or drawable resource to use as the background.
android:text : Specifies text to display in the view.
android:textColor : Specifies the text color.
android:textSize : Specifies the text size.
android:textStyle : Specifies the text style, such as bold .
Resource files are a way of separating static values from code so that you don't have to
change the code itself to change the values. You can store all the strings, layouts,
dimensions, colors, styles, and menu text separately in resource files.
Resource files
Resource files are stored in folders located in the res folder, including:
VTUPulse.com
drawable: For images and icons
layout: For layout resource files
menu: For menu items
mipmap: For pre-calculated, optimized collections of app icons used by the Launcher
values: For colors, dimensions, strings, and styles (theme attributes)
String resources are located in the strings.xml file in the values folder inside the res folder
when using the Project:
Android view. You can edit this file directly by opening it:
<resources>
<string name="app_name">Hello Toast</string>
<string name="button_label_count">Count</string>
<string name="button_label_toast">Toast</string>
<string name="count_initial_value">0</string>
</resources>
19
Android notes Module 1
Colours
Color resources are located in the colors.xml file in the values folder inside the res folder
when using the Project: Android view. You can edit this file directly:
<resources>
<color name="colorPrimary">#3F51B5</color>
<color name="colorPrimaryDark">#303F9F</color>
<color name="colorAccent">#FF4081</color>
<color name="myBackgroundColor">#FFF043</color>
</resources>
Dimensions:
Dimension resources are located in a dimens.xml file in the values folder inside the res
folder:
Device-independent pixels ( dp ) are independent of screen resolution.
scaled-pixel ( sp )
Styles:
A style is a resource that specifies common attributes such as height, padding, font color, font
size, background color. Styles are meant for attributes that modify the look of the view. Styles
are defined in the styles.xml file in the values folder inside the res folder.
VTUPulse.com
Responding to view clicks:
A click event occurs when the user taps or clicks a clickable view, such as a Button,
ImageButton, ImageView (tapping orclicking the image), or FloatingActionButton.
The onClick attribute: Android Studio provides a shortcut for setting up a clickable view,
and for associating an event handler with the view: use the android:onClick attribute with the
clickable view's element in the XML layout.
android:onClick="showToast"
To refer to the view in your code, use the findViewById() method of the View class
20
Android notes Module 1
Text and Scrolling Views:
TextView class, which is a subclass of the View class that is used to displays single line or
multi line text on the screen.
EditText is a subclass of TextView with editable text
TextView attributes:
The most often used attributes with TextView are the following:
android:text: Set the text to display.
android:textColor: Set the color of the text
android:textAppearance: The appearance of the text, including its color, typeface,
style, and size. You set this attribute to a predefined style resource or theme that
already defines these values.
android:textSize: Set the text size (if not already set by android:textAppearance ). Use
sp (scaled-pixel) sizes such as 20sp or 14.
android:textStyle: Set the text style . Use normal , bold , italic , or bold | italic
Android:typeface: Set the text typeface (if not already set by android:textAppearance
). Use normal , sans , serif , or monospace .
android:lineSpacingExtra: Set extra spacing between lines of text. Use sp (scaled-
VTUPulse.com
pixel) or dp (device-independent pixel)
Referring to a TextView in code:
TextView t=(TextView)findViewById(R.id.textview);
t.setText(“Hello world”);
Scrolling views:
If the information you want to show in your app is larger than the device's display, you can
create a scrolling view so that the user can scroll vertically by swiping up or down, or
horizontally by swiping right or left.
Useful for writing the news, article and stories etc.
Creating a layout with a ScrollView
The ScrollView class provides the layout for a vertical scrolling view. (For horizontal
scrolling, you would use HorizontalScrollView.)
ScrollView is a subclass of FrameLayout, which means that you can place only one view as
a child within it; that child contains the entire contents to scroll
21
Android notes Module 1
VTUPulse.com
Understanding Activities and Intents:
Android Components are building block of an Android application and these components are
specified in manifest file. There are following four main components that can be used within
an Android application:
Activity
Services
Broadcast Receiver
Content Provider
Activity:
An activity represents a single screen with a user interface where the user can interact. For
example, an email app might have one activity that shows a list of new emails, another
activity to compose an email, and another activity for reading individual messages.
Application may cointain one or more activities out of that you have make any one activity as
22
Android notes Module 1
Lancher activity(i.s first screen that appears when user opens an application).Each activity
can then start other activities in order to perform different actions.
Creating activities
To implement an activity in your app, do the following:
Create an activity Java class.
Implement a user interface for that activity.
Declare that new activity in the app manifest.
VTUPulse.com
layout files. When the setContentView() method is called, the system creates all the initial
views from the specified layout and adds them to your activity. This is often referred to as
inflating the layout.
Implement a user interface:
The most common way to define a user interface using views is with an XML layout file
stored as part of your app's resources. Defining your layout in XML enables you to maintain
the design of your user interface separately from the source code that defines the activity's
behavior.
Declare the activity in the manifest: Each activity in your app must be declared in the
Android app manifest with the <activity> element, inside <application> . When you create a
new project or add a new activity to your project in Android Studio, your manifest is created
or updated to include skeleton activity declarations for each activity.
Intent:
All Android activities are started or activated with an intent. Intents are message objects that
make a request to the Android runtime to start an activity or other app component in your app
or in some other app.
23
Android notes Module 1
When you start your app from the device home screen, the Android runtime sends an intent to
your app to start your app's main activity. To start other activities in your app, you build your
own intents with the Intent class and call the startActivity() method to send that intent.
In addition to starting activities, intents are also used to pass data between activities. When
you create an intent to start a new activity, you can include information about the data that
you want to operate in new activity.
Intent types
There are two types of intents in Android:
1. Explicit intents specify the receiving activity (or other component) by that activity's
fully qualified class name. Use an explicit intent to start a component in your own app
(for example, to move between screens in the user interface), because you already
know the package and class name of that component.
2. Implicit intents do not specify a specific activity or other component to receive the
intent. Instead you declare a general action to perform in the intent. The Android
system matches your request to an activity or other component that can handle your
requested action.
VTUPulse.com
Explicit intents:
Intent objects and fields:
An Intent object is an instance of the Intent class. For explicit intents, the key fields of an
intent include the following:
The activity class (for explicit intents). This is the class name of the activity or other
component that should receive the intent, for example,
com.example.SampleActivity.class. Use the intent constructor or the intent's
setComponent(), setComponentName() or setClassName() methods to specify the
class.
The intent data. The intent data field contains a reference to the data that you want to
operate in receiving activity, as a Uri object.(URI= Uniform Resource
Indetifier(Reference) is string of charecters used to identify a resources either by
location or a name or both.) The Uri.parse( ) method creates new Uri object , using
string passed to it and the string is hidden from user. Every URL is URI but every
URI is not URL.
Intent extras. These are key-value pairs that carry information that is required for the
receiving activity to accomplish the requested action.
24
Android notes Module 1
Intent flags. These are additional bits of metadata, defined by the Intent class. The
flags may instruct the Android system how to launch an activity or how to treat it after
it's launched.
To start a specific activity within your application, use an explicit intent and the
startActivity() method. Explicit intents include the fully-qualified class name for the activity
or other component in the Intent object. All the other intent fields are optional, and null by
default.
For example, if you wanted to start the ShowMessageActivity to show a specific message in
an email app, use code like this.
Intent messageIntent = new Intent(this, ShowMessageActivity.class);
startActivity(messageIntent);
The started activity remains on the screen until the user taps the back button on the device.
You can also manually close the started activity in response to a user action (such as a button
click) with the finish() method:
VTUPulse.com
Passing data between activities with intents:
In addition to simply starting one activity from another, you can also use intents to pass
information between activities. The intent object you use to start an activity can include intent
data (the URI of an object to act on), or intent extras, which are bits of additional data the
activity might need.
In the first (sending) activity, you:
1. Create the Intent object.
2. Put data or extras into that intent.
3. Start the new activity with startActivity().
In the second (receiving) activity, you:
1. Get the intent object the activity was started with.
2. Retrieve the data or extras from the Intent object.
25
Android notes Module 1
VTUPulse.com
// a Sample file URI
messageIntent.setData(Uri.fromFile(new File("/sdcard/sample.jpg")));
// A sample content: URI for your app's data model
messageIntent.setData(Uri.parse("content://mysample.provider/data"));
// Custom URI
messageIntent.setData(Uri.parse("custom:" + dataID + buttonId));
After you've added the data, you can start the activity with the intent as usual.
startActivity(messageIntent);
26
Android notes Module 1
Intent extras
Intent extras are used to pass any other random data to the started activity. Intent extras are
stored in a Bundle object as key and value pairs. Bundles are a map, optimized for Android,
where the keys are strings, and the values can be any primitive or object type (objects must
implement the Parcelable interface).
To put data into the intent extras, you can use putExtra() method of Intent class, or create
your own bundle and put it into the intent with putExtras().
Use the intent extras:
If you want to pass more than one piece of information to the started activity.
If any of the information you want to pass is not expressible by a URI.
Add extras to the intent:
To add intent extras to an explicit intent from the originating activity:
1. Determine the keys to use for the information you want to put into the extras, or define
your own. Each piece of information needs its own unique key.
2. Use the putExtra() methods to add your key/value pairs to the intent extras. Optionally you
VTUPulse.com
can create a Bundle object, add your data to the bundle, and then add the bundle to the intent.
The Intent class includes several intent extra keys you can use, defined as constants that begin
with the word EXTRA_.
For example, you could use Intent. EXTRA_EMAIL to indicate an array of email addresses
(as strings).
You can also define your own intent extra keys. Conventionally you define intent extra keys
as static variables with names that begin with EXTRA_.
For Example:
Intent messageIntent = new Intent(this, ShowMessageActivity.class);
Use a putExtra() method with a key to put data into the intent extras. The Intent class defines
many putExtra() methods for different kinds of data:
messageIntent.putExtra(EXTRA_MESSAGE, "this is my message");
messageIntent.putExtra(EXTRA_POSITION_X, 100);
messageIntent.putExtra(EXTRA_POSITION_Y, 500);
Creating Bundle and adding data.
Bundle extras = new Bundle();
extras.putString(EXTRA_MESSAGE, "this is my message");
27
Android notes Module 1
extras.putInt(EXTRA_POSITION_X, 100);
extras.putInt(EXTRA_POSITION_Y, 500);
After you've populated the bundle, add it to the intent with the putExtras() method (note the
"s" in Extras):
messageIntent.putExtras(extras);
Retrieve the data from the intent in the started activity:
When you start an activity with an intent, the started activity has access to the intent and the
data it contains.
To retrieve the intent the activity (or other component) was started with, use the getIntent()
method:
Intent intent = getIntent();
To get the extras out of the intent, you'll need to know the keys for the key/value pairs. You
can use the standard Intent extras if you used those, or you can use the keys you defined in
the originating activity (if they were defined as public.)
Use one of the getExtra() methods to extract extra data out of the intent object:
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
int positionX = intent.getIntExtra(MainActivity.EXTRA_POSITION_X);
VTUPulse.com
int positionY = intent.getIntExtra(MainActivity.EXTRA_POSITION_Y);
You can get the entire extras bundle from the intent and extract the values with the various
Bundle methods:
Bundle extras = intent.getExtras();
String message = extras.getString(MainActivity.EXTRA_MESSAGE);
28
Android notes Module 1
Implement onActivityResult() in the originating activity to process the returned data.
VTUPulse.com
Then put your return data into the intent as usual:
returnIntent.putExtra(“key”, “Value”);
public final static String EXTRA_RETURN_MESSAGE =” return”;
Ex: returnIntent.putExtra(EXTRA_RETURN_MESSAGE, “Hello Good Morning”);
Use the setResult() method with a response code and the intent with the response data:
setResult(RESULT_OK, replyIntent);
The response codes are defined by the Activity class, and can be
RESULT_OK. :The request was successful.
RESULT_CANCELED: the user cancelled the operation.
RESULT_FIRST_USER: for defining your own result codes.
Step 3: Implement onActivityResult() in the originating activity to process the returned
data. Or Read response data in onActivityResult( )
Now that the launched activity has sent data back to the originating activity with an intent, To
handle returned data in the originating activity, implement the onActivityResult() callback
method.
29
Android notes Module 1
Example:
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TEXT_REQUEST) {
if (resultCode == RESULT_OK) {
String reply = data.getStringExtra(SecondActivity.EXTRA_RETURN_MESSAGE);
// process data
}
}
}
The three arguments to the onActivityResult() contain all the information you need to handle
the return data.
Request code. The request code you set when you launched the activity with
startActivityForResult().
Result code: the result code set in the launched activity, usually one of RESULT_OK
or RESULT_CANCELED.
Intent data. The intent that contains the data returned from the launch activity.
VTUPulse.com
Activity navigation:
Application consists of multiple activities and the user wants to move around your app and
between activities, then the consistent navigation becomes more important.
So designing navigation for your apps will make more predictable and reliable for your users.
Android system supports two different forms of navigation strategies for your app.
Temporal or Back navigation, provided by the device back button, and the back stack.
Ancestral, or Up navigation, provided by you as an option in the app's action bar.
Back navigation, tasks, and the back stack:
Back navigation allows your users to return to the previous activity by tapping the device
back button . Back navigation is also called temporal navigation because the back button
navigates through the history of recently viewed screens, in reverse sequential order.
The back stack is the set of activities that the user has visited and that can be returned to by
the user with the back button. Each time when a new activity starts, it is pushed onto the back
stack and takes user focus. The previous activity is stopped but is still available in the back
stack. The back stack operates on a "last in, first out" mechanism, so when the user is done
30
Android notes Module 1
with the current activity and presses the Back button, that activity is popped from the stack
(and destroyed) and the previous activity resumes.
In most cases you don't have to worry about managing either tasks or the back stack for your
app—the system keeps track of these things for you, and the back button is always available
on the device.
Up navigation:
Up navigation, sometimes referred to as ancestral or logical navigation, is used to navigate
within an app based on the explicit hierarchical relationships between screens. With Up
navigation, your activities are arranged in a hierarchy, and "child" activities show a left-
VTUPulse.com
facing arrow in the action bar that returns the user to the "parent" activity. The topmost
activity in the hierarchy is usually your main activity, and the user cannot go up from there.
In many cases, Up and Back navigation may provide the same behavior: to just return to the
previous activity. Providing Up behavior for your app is optional, but a good design practice,
to provide consistent navigation for the activities in your app.
Implement up navigation with parent activities:
31
Android notes Module 1
VTUPulse.com
the foreground, and receives the user focus. When you start a second activity (Activity 2),
that new activity is also created and started, and the main activity is stopped. When you're
done with the second activity and navigate back, the first activity resumes. The second
activity stops and is no longer needed; if the user does not resume the second activity, it is
eventually destroyed by the system.
Activity states and lifecycle callback methods:
When you run a application an activity transit into different lifecycle states, the Android
system calls several lifecycle callback methods at each stage. All of the callback methods are
defined in Activity Class and you can override them depending on requirement. Keep in
mind that the lifecycle states (and callbacks) are per activity, not per app, and you may
implement different behavior at different points in the lifecycle for different activities in
your app.
32
Android notes Module 1
VTUPulse.com
The activity enters into the created state when it is started for the first time. When an activity
is first created the system calls the onCreate() method to initialize that activity. For
example, when the user taps your app icon from the Home screen to start that app, the system
calls the onCreate() method for the activity in your app that you've declared to be the
"launcher" or "main" activity. In this case the main activity's onCreate() method is similar to
the main() method in other programs.
Similarly, if your app starts another activity with an intent (either explicit or implicit), the
system matches your intent request with an activity and calls onCreate() for that new activity.
The onCreate() method is the only required callback you must implement in your
activity class. In your onCreate() method you perform basic application startup logic that
should happen only once, such as setting up the user interface, assigning class-scope
variables, or setting up background tasks.
onCreate() is called only once when the activity is created.
Activity started (onStart() method)
@Override
protected void onStart() {
super.onStart();
// The activity is about to become visible.}
33
Android notes Module 1
After your activity is initialized with onCreate(), the system calls the onStart() method, and
the activity is in the started state. The onStart() method is also called if a stopped activity
returns to the foreground, such as when the user clicks the back or up buttons to navigate to
the previous screen. While onCreate() is called only once when the activity is created, the
onStart() method may be called many times during the lifecycle of the activity as the user
navigates around your app.
When an activity is in the started state and visible on the screen, the user cannot interact with
it until onResume() is called, the activity is running, and the activity is in the foreground.
VTUPulse.com
interacting with your app. For the first time when activity is started, the system calls the
onResume() method just after onStart(). The onResume() method may also be called multiple
times, each time the app comes back from the paused state.
Activity paused (onPause() method)
@Override
protected void onPause() {
super.onPause();
// Another activity is taking focus
// (this activity is about to be "paused").
}
The paused state can occur in several situations:
The activity is going into the background, but has not yet been fully stopped. This is
the first indication that the user is leaving your activity.
The activity is only partially visible on the screen, because a dialog or other
transparent activity is overlaid on top of it.
34
Android notes Module 1
In multi-window or split screen mode (API 24), the activity is displayed on the screen,
but some other activity has the user focus.
When the activity moves into the paused state, the system calls the onPause() method when
the activity moves into the paused state. Because the onPause() method is the first indication
you get that the user may be leaving the activity, you can use onPause() to stop animation or
video playback, release any hardware-intensive resources.
Activity stopped (onStop() method)
@Override
protected void onStop() {
super.onStop();
// The activity is no longer visible (it is now "stopped")
}
An activity is in the stopped state when it is no longer visible on the screen . This happens
because the user has started another activity, or returned to the home screen. The system
retains the activity instance in the back stack, and if the user returns to that activity it is
restarted again. Stopped activities may be killed altogether by the Android system if
resources are low. The system calls the onStop() method when the activity stops.
VTUPulse.com
Activity destroyed (onDestroy() method)
@Override
protected void onDestroy() {
super.onDestroy();
// The activity is about to be destroyed.
}
When your activity is destroyed it is shut down completely, and the Activity instance is
reclaimed by the system. This can happen in several cases:
You call finish() in your activity to manually shut it down.
The user navigates back to the previous activity.
The device is in a low memory situation where the system reclaims stopped activities
to free more resources.
A device configuration change occurs.
Activity restarted (onRestart() method)
@Override
protected void onRestart() {
35
Android notes Module 1
super.onRestart();
// The activity is about to be restarted.
}
The restarted state is a transient state that only occurs if a stopped activity is started again. In
this case the onRestart() method is called in between onStop() and onStart().
Configuration changes and activity state
The activities may be destroyed when the user navigates back, by you with the finish()
method, or by the system when it needs to free resources. The fourth time your activities are
destroyed is when the device undergoes a configuration change. Configuration changes occur
on the device, in runtime. The most common form of a configuration change is when the
device is rotated. When the device rotates from portrait to landscape, or vice versa, the entire
layout for your app needs to changed. The system recreates the activity to adapt to the new
configuration by loading alternative resources (such as a landscape-specific layout).
When a configuration change occurs Android system shuts down your activity (calling
onPause(), onStop(), and onDestroy()), and then starts it over again from the start (calling
onCreate(), onStart(), and onResume()).
Activity instance state:
VTUPulse.com
When an activity is destroyed and recreated, then the state of the activity is not retained.
Whereas when an activity is paused or stopped, the state of the activity is retained because
that activity is still held in memory.
The activity state is stored as a set of key/value pairs in a Bundle object called the activity
instance state. The system saves default state information to instance state bundle just before
the activity is stopped, and passes that bundle to the new activity instance to restore.
You can add your own instance data to the instance state bundle by overriding the
onSaveInstanceState() callback. The state bundle is passed to the onCreate() method, so
you can restore that instance state data when your activity is created.
Because device rotation is a common use case for you app, make sure you test that your
activity behaves correctly in response to this configuration change, and implement instance
state if you need to.
Saving activity instance state:
To save information to the instance state bundle, use the onSaveInstanceState() callback. This
is not a lifecycle callback method, but it is called when the user is leaving your activity
(sometime before the onStop() method).
36
Android notes Module 1
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
// Save the user's current game state
savedInstanceState.putInt("score", mCurrentScore);
savedInstanceState.putInt("level", mCurrentLevel);
}
Restoring activity instance state:
Once you've saved the activity instance state, you also need to restore it when the activity is
recreated. To restore the saved instances state in onCreate(), test for the existence of a state
bundle before you try to get data out of it. When your activity is started for the first time there
will be no state and the bundle will be null.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // Always call the superclass first
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
VTUPulse.com
// Restore value of members from saved state
mCurrentScore = savedInstanceState.getInt("score");
mCurrentLevel = savedInstanceState.getInt("level");
} else
{
// Probably initialize members with default values for a new instance
}
Implicit intents:
The basic use of Intent is to start an activity or other app component and to pass the data
between activities. With an explicit intents, where you can start one activity from another by
specifying the class name of that activity.
A more flexible use of intents is the implicit intent. With implicit intents you do not specify
the exact activity (or other component) to run—instead, you include just enough information
in the intent about the task you want to perform. The Android system matches the
information in your request intent with activities available on the device that can perform that
37
Android notes Module 1
task. If there's only one activity that matches, that activity is launched. If there are multiple
matching activities, the user is presented with an app chooser that enables them to pick which
app they would like to perform the task.
Example: Playing the Videos.
Activities register themselves with the system as being able to handle implicit intents with
intent filters, declared in the Android manifest.
Intent actions, categories, and data:
The key fields are used by implicit intents:
The intent action:
which is the generic action the receiving activity should perform. The intent actions are
defined as constants in the Intent class and begin with the word ACTION_. A common intent
action is ACTION_VIEW, which is use when you have some information that an activity can
show to the user, such as a photo to view in a gallery app, or an address to view in a map app.
You can specify the action for an intent in the intent constructor, or with the setAction()
method.
An intent category:
An intent category, which provides additional information about the category of component
VTUPulse.com
that should handle the intent. Intent categories are optional, and you can add more than one
category to an intent. Intent categories are also defined as constants in the Intent class and
begin with the word CATEGORY_. You can add categories to the intent with the
addCategory() method.
The data type:
The data type, which indicates the MIME type of data the activity should operate on. Usually,
this is inferred from the URI in the intent data field, but you can also explicitly define the
data type with the setType() method.
Sending implicit intents:
Starting activities with implicit intents, and passing data between those activities, works
much the same way as it does for explicit intents:
1. In the sending activity, create a new Intent object.
2. Add information about the request to the Intent object, such as data or extras.
3. Send the intent with startActivity() (to just start the activity) or startActivityforResult() (to
start the activity and expect a result back).
38
Android notes Module 1
When you create an implicit Intent object, you:
Do not specify the specific activity or other component to launch.
Add an intent action or intent categories (or both).
Resolve the intent with the system before calling startActivity() or
startActivityforResult().
Show an app chooser for the request (optional).
Create implicit Intent objects:
To use an implicit intent, create an Intent object as you did for an explicit intent, only without
the specific component name.
Intent sendIntent = new Intent();
You can also create the Intent object with a specific action:
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
Once you have an Intent object you can add other information (category, data, extras) with
the various Intent methods.
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, textMessage);
sendIntent.setType("text/plain");
VTUPulse.com
Resolve the activity before starting it:
When you define an implicit intent with a specific action and/or category, there is a
possibility that there won't be any activities on the device that can handle your request. If you
just send the intent and there is no appropriate match, your app will crash.
To verify that an activity or other component is available to receive your intent, use the
resolveActivity() method with the system package manager like this:
if (sendIntent.resolveActivity(getPackageManager()) != null)
{
startActivity(sendIntent);
}
If the result of resolveActivity() is not null, then there is at least one app available that can
handle the intent, and it's safe to call startActivity(). Do not send the intent if the result is null.
Show the app chooser:
To find an activity or other component that can handle your intent requests, the Android
system matches your implicit intent with an activity whose intent filters indicate that they can
39
Android notes Module 1
perform that action. If there are multiple apps installed that match, the user is presented with
an app chooser that lets them select which app they want to use to handle that intent.
Receiving implicit intents:
If you want an activity in your app to respond to implicit intents (from your own app or other
apps), declare one or more intent filters in the Android manifest. Each intent filter specifies
the type of intents it accepts based on the intent's action, data, and category. The system will
deliver an implicit intent to your app component only if that intent can pass through one of
your intent filters.
Intent filters
Define intent filters with one or more <intent-filter> elements in the app's manifest file,
nested in the corresponding <activity> element. Inside <intent-filter> , specify the type of
intents your activity can handle. The Android system matches an implicit intent with an
activity or other app component only if the fields in the Intent object match the intent filters
for that component. An intent filter may contain these elements, which correspond to the
fields in the Intent object described above:
<action> : The intent action.
<data> : The type of data accepted, including the MIME type or other attributes of the
VTUPulse.com
data URI (such as scheme, host,port, path, and so no).
<category> : The intent category.
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
This intent filter has the action MAIN and the category LAUNCHER. The <action> element
specifies that this is the "main" entry point to the application. The <category> element
specifies that this activity should be listed in the system's application launcher (to allow users
to launch this activity). Only the main activity for your app should have this intent filter.
Actions
An intent filter can declare zero or more <action> elements for the intent action. The action is
defined in the name attribute, and consists of the string "android.intent.action." plus the name
of the intent action, minus the ACTION_ prefix.
So, for example, an implicit intent with the action ACTION_VIEW matches an intent filter
whose action is android.intent.action.VIEW.
40
Android notes Module 1
For example, this intent filter matches either ACTION_EDIT and ACTION_VIEW:
<intent-filter>
<action android:name="android.intent.action.EDIT" />
<action android:name="android.intent.action.VIEW" />
...
</intent-filter>
To get through this filter, the action specified in the incoming Intent object must match at
least one of the actions. You must include at least one intent action for an incoming implicit
intent to match.
Categories
An intent filter can declare zero or more <category> elements for intent categories. The
category is defined in the name attribute, and consists of the string "android.intent.category."
plus the name of the intent category, minus the CATEGORY prefix.
For example, this intent filter matches either CATEGORY_DEFAULT and
CATEGORY_BROWSABLE:
<intent-filter>
<category android:name="android.intent.category.DEFAULT" />
... VTUPulse.com
<category android:name="android.intent.category.BROWSABLE" />
</intent-filter>
Data
An intent filter can declare zero or more <data> elements for the URI contained in the intent
data. As the intent data consists of a URI and (optionally) a MIME type, you can create an
intent filter for various aspects of that data, including:
URI Scheme
URI Host
URI Path
Mime type
For example, this intent filter matches data intents with a URI scheme of http and a MIME
type of either "video/mpeg" or
"audio/mpeg".
<intent-filter>
<data android:mimeType="video/mpeg" android:scheme="http" />
41
Android notes Module 1
<data android:mimeType="audio/mpeg" android:scheme="http" />
...
</intent-filter>
VTUPulse.com
The Android Studio debugger
Testing frameworks such as JUnit or Espresso
Dalvik Debug Monitor Server (DDMS), to track resource usage.
To debug your app with the Android Studio debugger, set and view breakpoints, step through
your code, and examine variables.
Running the debugger:
Running an app in debug mode is similar to just running that app. You can either run an app
in debug mode, or attach the debugger to an already-running app.
Run your app in debug mode:
To start debugging, click Debug in the toolbar. Android Studio builds an APK, signs it
with a debug key, installs it on your selected device.
Debug a running app:
If your app is already running on a device or emulator, start debugging that app with these
steps:
1. Select Run > Attach debugger to Android process or click the Attach icon in the
toolbar.
42
Android notes Module 1
2. In the Choose Process dialog, select the process to which you want to attach the debugger.
By default, the debugger shows the device and app process for the current project, as well as
any connected hardware
devices or virtual devices on your computer. Select Show all processes to show all processes
on all devices.
3. Click OK. The Debug window appears as before.
Resume or Stop Debugging
To resume executing an app after debugging it, select Run > Resume Program or click the
Resume icon. To stop debugging your app, select Run > Stop or click the Stop
icon in the toolbar.
Using Breakpoints:
A breakpoint is a place in your code where you want to pause the normal execution of your
app to perform other actions such as examining variables or evaluating expressions, or
executing your code line by line to determine the causes of runtime errors.
Add breakpoints:
To add a breakpoint to a line in your code, use these steps:
VTUPulse.com
1. Locate the line of code where you want to pause execution.
2. Click in the left gutter of the editor window at that line, next to the line numbers. A red dot
appears at that line, indicating a breakpoint.
You can also use Run > Toggle Line Breakpoint or Control-F8 (Command-F8 on OS X) to
set a breakpoint at a line.
When your code execution reaches the breakpoint, Android Studio pauses execution of your
app. You can then use the tools in the Android debugger to view the state of the app and
debug that app as it runs.
View and configure breakpoints:
To view all the breakpoints you've set and configure breakpoint settings, click the View
Breakpoints icon on the left edge of the debugger window. The Breakpoints window
appears. In this window all the breakpoints you have set appear in the left pane, and you can
enable or disable each breakpoint with the check boxes. If a breakpoint is disabled, Android
Studio does not pause your app when execution reaches that breakpoint.
Disable (Mute) all breakpoints: Disabling a breakpoint enables you to temporarily "mute"
that breakpoint without removing it from your code. If you remove a breakpoint altogether
43
Android notes Module 1
you also lose any conditions or other features you created for that breakpoint, so disabling it
can be a better choice.
To mute all breakpoints, click the Mute Breakpoints icon. Click the icon again to
enable (unmute) all breakpoints.
Use conditional breakpoints:
Conditional breakpoints are breakpoints that only stop execution of your app if the test in the
condition is true. To define a test for a conditional breakpoint, use these steps:
1. Right click on a breakpoint icon, and enter a test in the Condition field.
2. Run your app in debug mode. Execution of your app stops at the conditional breakpoint, if
the condition evaluates to true.
Stepping through code:
After your app's execution has stopped because a breakpoint has been reached, you can
execute your code from that point one line at a time with the Step Over, Step Into, and Step
Out functions.
To use any of the step functions:
1. Begin debugging your app. Pause the execution of your app with a breakpoint. Your app's
VTUPulse.com
execution stops, and the debugger shows the current state of the app. The current line is
highlighted in your code.
2. Click the Step Over icon, select Run > Step Over, or type F8.
Step Over executes the next line of the code in the current class and method, executing all of
the method calls on that line and remaining in the same file.
3. Click the Step Into icon, select Run > Step Into, or type F7.
Step Into jumps into the execution of a method call on the current line (versus just executing
that method and remaining on the same line).
4. Click the Step Out icon, select Run > Step Out, or type Shift-F8.
Step Out finishes executing the current method and returns to the point where that method
was called.
5. To resume normal execution of the app, select Run > Resume Program or click the
Resume icon
VTUPulse.com
UI testing, which allows you to test that your app behaves correctly when a user interacts
with your app's activities or enters a specific input.
For most forms of user interface testing, you use the Espresso framework, which allows
you to write automated UI tests.
Unit Testing:
Unit tests are fundamental tests in your app testing strategy. By creating and running unit
tests against your code, you can verify that the logic of individual functional code areas or
units is correct. Running unit tests after every build helps you catch and fix problems
introduced by code changes to your app.
The Android Testing Support Library
The Android Testing Support Library provides the infrastructure and APIs for testing
Android apps, including support for JUnit 4. With the testing support library you can build
and run test code for your apps. You may already have the Android Testing Support Library
installed with Android Studio. To check for the Android Support Repository, follow these
steps:
1. In Android Studio choose Tools > Android > SDK Manager.
45
Android notes Module 1
2. Click the SDK Tools tab, and look for the Support Repository.
3. If necessary, update or install the library.
The Android Testing Support Library classes are located under the android.support.test
package. You should use the support libraries first, when given a choice between the support
libraries and the older APIs, as the support libraries help build and distribute tests in a cleaner
and more reliable fashion than directly coding against the API itself.
Setting up testing:
To prepare your project for testing in Android Studio, you need to:
Organize your tests in a source set.
Configure your project's gradle dependencies to include testing-related APIs.
VTUPulse.com
The androidTest source set, for Android instrumented tests.
Source sets appear in the Android Studio Android view under the package name for your app.
The main source set includes just the package name. The test and androidTest source sets
have the package name followed by (test) or (androidTest), respectively.
46
Android notes Module 1
VTUPulse.com
default gradle build file for your project includes some of these dependencies by default, but
you may need to add more dependencies for additional testing features such as matching or
mocking frameworks.
dependencies {
// Required -- JUnit 4 framework
testCompile 'junit:junit:4.12'
// Optional -- hamcrest matchers
testCompile 'org.hamcrest:hamcrest-library:1.3'
// Optional -- Mockito framework
testCompile 'org.mockito:mockito-core:1.10.19'
}
After you add dependencies to your build.gradle file you may have to sync your project to
continue. Click Sync Now in Android Studio when prompted.
Configure a test runner:
Test runner is a library or set of tools that enables testing to occur and the results to be printed
to a log. Your Android project has access to a basic JUnit test runner as part of the JUnit4
APIs. The Android test support library includes a test runner for instrumented and Espresso
tests, AndroidJUnitRunner , which also supports Junit 3 and 4.
android
{
47
Android notes Module 1
defaultConfig {
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
}
VTUPulse.com
Use JUnit 4 syntax and annotations to write your tests. For example, the test class shown
below includes the following annotations:
The @RunWith annotation indicates the test runner that should be used for the tests in
this class.
The @SmallTest annotation indicates that this is a small (and fast) test.
The @Before annotation marks a method as being the set up for the test.
The @Test annotation marks a method as an actual test.
For more information on JUnit Annotations, see the JUnit Reference documentation.
@RunWith(JUnit4.class)
@SmallTest
public class CalculatorTest {
private Calculator mCalculator;
// Set up the environment for testing
@Before
public void setUp() {
mCalculator = new Calculator();
48
Android notes Module 1
}
// test for simple addition
@Test
public void addTwoNumbers()
{
double resultAdd = mCalculator.add(1d, 1d);
assertThat(resultAdd, is(equalTo(2d)));
}
}
The addTwoNumbers() method is the only actual test. The key part of a unit test is the
assertion, which is defined here by the assertThat() method. Assertions are expressions that
must evaluate and result in a value of true for the test to pass.
JUnit 4 provides a number of assertion methods, but assertThat() is the most flexible, as it
allows for general-purpose comparison methods called matchers.
VTUPulse.com
To run a single test, right-click that test method and select Run.
To test all the methods in a test class, right-click the test file in the project view and
select Run.
To run all tests in a directory, right-click on the directory and select Run tests.
49
Android notes Module 1
Backward-compatible versions of framework components. These compatibility
libraries allow you to use features and components available on newer versions of the
Android platform even when your app is running on an older platform version. For
example, older devices may not have access to newer features such as fragments,
action bars, or Material Design elements. The support library provides access to those
features on older devices.
Additional layout and user interface elements. The support library includes views and
layouts that can be useful for your app, but are not included in the standard Android
framework. For example, the RecyclerView
Support for different device form factors, such as TV or wearables: For example, the
Leanback library includes components specific to app development on TV devices.
Design support: The design support library includes components to support Material
Design elements in your app, including floating action buttons (FAB). You'll learn
more about Material Design.Various other features such as palette support,
annotations, percentage-based layout dimensions, and preferences.
VTUPulse.com
v4 support library
The v4 support libraries include the largest set of APIs compared to the other libraries,
including support for application components, user interface features, accessibility, data
handling, network connectivity, and programming utilities.
The v4 support libraries include these specific components:
v4 compat library: Compatibility wrappers (classes that include the word "Compat")
for a number of core framework APIs.
v4 core-utils library: Provides a number of utility classes
v4 core-ui library: Implements a variety of UI-related components
v4 media-compat library: Backports portions of the media framework from API 21.
v4 fragment library: Adds support for Android fragments.
v7 support library
The v7 support library includes both compatibility libraries and additional features. The v7
support library includes all the v4 support libraries, so you don't have to add those separately.
A dependency on the v7 support library is included in every new Android Studio project, and
new activities in your project extend from AppCompatActivity.
50
Android notes Module 1
The v7 support libraries include these specific components:
v7 appcompat library: Adds support for the Action Bar user interface design pattern
and support for material design user interface implementations.
v7 cardview library: Provides the CardView class, a view that lets you show
information inside cards.
v7 gridlayout library: Includes the GridLayout class, which allows you to arrange user
interface elements using a grid of rectangular cells
v7 mediarouter library: Provides MediaRouter and related media classes that support
Google Cast.
v7 palette library: Implements the Palette class, which lets you extract prominent
colors from an image.
v7 recyclerview library: Provides the RecyclerView class, a view for efficiently
displaying large data sets by providing a limited window of data items.
v7 preference library: Provides APIs to support preference objects in app settings.
VTUPulse.com
51