Android Courseware Updated
Android Courseware Updated
TABLE OF CONTENTS
CHAPTER OVERVIEW:
Android is an operating system based on the Linux kernel. Android is developed in the Android Open
Source Project (AOSP). This project is lead by Google.
1.1-Introduction to Android
OBJECTIVES:
LEARNING OUTCOME:
• Android versions
• Android application
• Technology stack needed for android apps development
• API level
• Version
• Environment Setup
CORE DISCUSSION:
• Historical approach :
The founding of Android-In October 2003, well before the term “smartphone” was used by most of the
public, and several years before Apple announced its first iPhone and its iOS, the company Android Inc
was founded in Palo Alto, California. Its four founders were Rich Miner, Nick Sears, Chris White, and
Andy Rubin. At the time of its public founding, Rubin was quoted as saying that Android Inc was going
to develop “smarter mobile devices that are more aware of its owner’s location and preferences.”
1
Course Manual for Android App Development
• Fundamental technology
Android Studio : Android Studio is the official integrated development environment (IDE) for
Google's Androidoperating system, built on JetBrains' IntelliJ IDEA software and designed specifically
for Android development. It is available for download on Windows, macOS and Linux based operating
systemsIt is a replacement for the Eclipse Android Development Tools (ADT) as primary IDE for native
Android application development.
Eclipse IDE: Eclipse IDE (integrated development environment). Included in the Android SDK
download, the Eclipse IDE provides the “hands-on” controls you need for writing your app using Java,
the Android SDK and the Android ADT. Android ADT (Android Development.Apr 25, 2013
• Alternative technology
The Android environment setup topic of the Unity Manual contains a basic outline of the tasks that you
must complete before you are able to run code on your Android device, or in the Android emulator. For
more in-depth information on setting your Android development environment, see the step-by-step
instructions on the Android developer portal.
1.1-Introduction to Android:
The Android operating system can be divided into the four areas as depicted in the following graphic. An
Android application developer typically works with the two layers on top to create new Android
applications.
• Applications - Contains the applications, like the Browser, Camera, Gallery, Music and Phone
• Application framework - An API which allows high-level interactions with the Android system
• Libraries and runtime - The libraries for many common framework functions, like graphic rendering,
data storage, web browsing. Also contains the Android runtime, as well as the core Java libraries for
running Android applications.
• Linux kernel - Communication layer for the underlying hardware.
2
Course Manual for Android App Development
Android versions
The Android operating system is published in different versions. The following table gives an overview of
the available versions.
Oreo 8.0 26
Marshmallow 6.0 23
Lollipop 5.1 22
Lollipop 5.0 21
Honeycomb 3.2.x 13
Froyo 2.2.x 8
Eclair 2.1 7
Donut 1.6 4
Cupcake 1.5 3
3
Course Manual for Android App Development
Android application
An Android application (app) is a single installable unit which can be started and used independently. An
Android application consists of configuration files, Java source and resource files. You can define the
following components in your configuration files:
• Application
• Activities
• Services
• Content Provider
• Broadcast Receiver
1. JDK
2. Android SDK
3. Android Studio
4
Course Manual for Android App Development
Select Start menu > Computer > System Properties > Advanced System Properties. Then open Advanced
tab >Environment Variables and add a new system variable JAVA_HOME that points to your JDK
folder, for example C:\Program Files\Java\jdk
Configure your computer for setting up android application development environment (practical)
PRACTICE:
https://commonsware.com/Android/Android-4.7-CC.pdf
http://www.wrox.com/WileyCDA/WroxTitle/Professional-Android-2-Application-
Development.productCd-0470565527.html
REFERENCE LINK:
https://developer.android.com/guide/
https://developer.android.com/training/basics/firstapp/
5
Course Manual for Android App Development
CHAPTER OVERVIEW:
Programming paradigm based on the concept of "objects", which may contain data, in the form of fields,
often known as attributes; and code, in the form of procedures, often known as methods. A feature of
objects is that an object's procedures can access and often modify the data fields of the object with which
they are associated (objects have a notion of "this" or "self"). In OOP, computer programs are designed by
making them out of objects that interact with one another
2.1-OOP Concepts
2.2-Java basic
OBJECTIVES:
LEARNING OUTCOME:
• Abstraction
• Encapsulation
• Polymorphism
• Inheritance
• Association
• Aggregation
• Composition
• Data types in Java
• Work with java variables: integer, string, double
• Understand conditional statement, looping
• If-statement
6
Course Manual for Android App Development
CORE DISCUSSION:
• Historical approach :
OOP languages simula (1967) is generally accepted as being the first language with the primary features
of an object-oriented language. It was created for making simulation programs, in which what came to be
called objects were the most important information representation.
• Fundamental technology
Java view technologies and frameworks- are web-basedsoftware libraries that provide the user
interface, or "view-layer", of Javaweb applications. Such application frameworks are used for
defining web pages and handling the HTTPrequests (clicks) generated by those web pages. As a sub-
category of web frameworks, view-layer frameworks often overlap to varying degrees with web
frameworks that provide other functionality for Java web applications
1. Java Servlets.
2. Core Java
3. JavaServer Pages (JSP)
4. Enterprise JavaBeans (EJB)
5. Java Database Connectivity (JDBC)
1. Abstraction
2. Encapsulation
3. Polymorphism
4. Inheritance
5. Association
6. Aggregation
7. Composition
7
Course Manual for Android App Development
Abstraction:Abstraction is the concept of hiding the internal details and describing things in simple
terms. For example, a method that adds two integers. The method internal processing is hidden from outer
world. There are many ways to achieve abstraction in object oriented programming, such as encapsulation
and inheritance.
A java program is also a great example of abstraction. Here java takes care of converting simple
statements to machine language and hides the inner implementation details from outer world.
Access modifier keywords are used for encapsulation in object oriented programming. For example,
encapsulation in java is achieved using private, protected and public keywords.
Compile time polymorphism is achieved by method overloading. For example, we can have a class as
below.
publicclassCircle{
publicvoid draw(){
System.out.println("Drwaing circle with default color Black and diameter 1 cm.");
}
Here we have multiple draw methods but they have different behavior. This is a case of method
overloading because all the methods name is same and arguments are different. Here compiler will be
able to identify the method to invoke at compile time, hence it’s called compile time polymorphism.
Runtime polymorphism is implemented when we have “IS-A” relationship between objects. This is also
called as method overriding because subclass has to override the superclass method for runtime
polymorphism. If we are working in terms of superclass, the actual implementation class is decided at
runtime. Compiler is not able to decide which class method will be invoked. This decision is done at
runtime, hence the name as runtime polymorphism or dynamic method dispatch.
package com.journaldev.test;
8
Course Manual for Android App Development
publicinterfaceShape{
publicvoid draw();
}
package com.journaldev.test;
publicclassCircleimplementsShape{
@Override
publicvoid draw(){
System.out.println("Drwaing circle");
}
}
package com.journaldev.test;
publicclassSquareimplementsShape{
@Override
publicvoid draw(){
System.out.println("Drawing Square");
}
Shape is the superclass and there are two subclasses Circle and Square. Below is an example of runtime
polymorphism.
Shape sh =newCircle();
sh.draw();
In above examples, java compiler don’t know the actual implementation class of Shape that will be used
at runtime, hence runtime polymorphism.
Inheritance:Inheritance is the object oriented programming concept where an object is based on another
object. Inheritance is the mechanism of code reuse. The object that is getting inherited is called superclass
and the object that inherits the superclass is called subclass.
We use extends keyword in java to implement inheritance. Below is a simple example of inheritance in
java.
package com.journaldev.java.examples1;
classSuperClassA{
publicvoid foo(){
System.out.println("SuperClassA");
9
Course Manual for Android App Development
classSubClassBextendsSuperClassA{
publicvoid bar(){
System.out.println("SubClassB");
}
publicclassTest{
publicstaticvoid main(String args[]){
SubClassB a =newSubClassB();
a.foo();
a.bar();
}
}
Association:Association is the OOPS concept to define the relationship between objects. Association
defines the multiplicity between objects. For example Teacher and Student objects. There is one to many
relationship between a teacher and students. Similarly a student can have one to many relationship with
teacher objects. However both student and teacher objects are independent of each other.
Aggregation:Aggregation is a special type of association. In aggregation, objects have their own life
cycle but there is an ownership. Whenever we have “HAS-A” relationship between objects and ownership
then it’s a case of aggregation.
2.2-Java basic:
10
Course Manual for Android App Development
Integer: An integer is a number that can be written without a fractional component. For example, 21, 4,
0, and −2048 are integers, while 9.75, 5 1⁄2, and √2 are not.
Double: The double data type is a double-precision 64-bit IEEE 754 floating point. It is specified in the
Floating-Point Types, Formats, and Values section of the Java Language Specification. For decimal
values, this data type is generally the default choice. As mentioned above, this data type should never be
used for precise values, such as currency.
We use control statements when we want to change the default sequential order of execution
If-statement
The “if” statement in Java works exactly like in most programming languages. With the help of “if” you
can choose to execute a specific block of code when a predefined condition is met. The structure of the
“if” statement in Java looks like this:
11
Course Manual for Android App Development
Loops
Java provides three repetition statements/loop statements that enable programmers to control the flow of
execution by repetitively performing a set of statements as long as the continuation condition remains
true. These three looping statements are called [ for, while, and do...while ] statements. The ‘for
and while’ statements perform the repetition declared in their body zero or more times. If the loop
continuation condition is false, it stops execution. The ‘do...while’ loop is slightly different in the sense
that it executes the statements within its body for one or more times.
Switch
A ‘switch’ statement allows a variable to be tested for equality against a list of values. Each value is called a
case, and the variable being switched on is checked for each case.
12
Course Manual for Android App Development
Break
The ‘continue’ keyword can be used in any of the loop control structures. It causes the loop to
immediately jump to the next iteration of the loop.
In a for loop, the continue keyword causes control to immediately jump to the update statement.In a while
loop or do/while loop, control immediately jumps to the Boolean expression.
Methods in java
A Java method is a collection of statements that are grouped together to perform an operation.
In addition to the basic data types already described, Java supports user-defined data types, which are
aggregations of these basic types. These complex data types include arrays, sequences, enumerations, and
constructed data types you define yourself using structs and unions.
A complex data type is used in IDL by first giving it a type name, then using the type name wherever you
would use a basic data- or interface-type name (e.g., declaring attributes, method arguments). There are a
few ways a name is assigned to a complex data type:
• With structures, unions, and enumerations, the name is included in the declaration of the data
type.
Before we go on to see how complex data types are declared in IDL, let's take a look at how
a typedef assigns a type name to a complex data type.
13
Course Manual for Android App Development
PRACTICE:
https://www.pdfdrive.net/head-first-javapdf-e18943750.html
http://www.academia.edu/32243463/Java_A_Beginners_Guide_6th_Edition_PDF_
REFERENCE LINK:
https://docs.oracle.com/javase/tutorial/java/concepts/
http://www.exforsys.com/tutorials/oops-concepts/the-history-of-object-oriented-
programming.html
14
Course Manual for Android App Development
CHAPTER OVERVIEW:
You can set environment variables for Android Studio and the command-line tools that specify things
like where the SDK is installed and where user-specific data is stored. This page describes the most
commonly used environment variables.
OBJECTIVES:
LEARNING OUTCOME:
• Understand View and Layout
• Adding a Form Widgets
15
Course Manual for Android App Development
CORE DISCUSSION:
The New Project wizard lets you choose the form factors for your app and populates the project structure
with everything you need to get started.
If you don't have a project opened, Android Studio shows the Welcome screen, where you can click Start
a new Android Studio project.
16
Course Manual for Android App Development
The next window lets you select the device form factors you want to build for, and the minimum version
you want to support for each. For each device you select, the wizard adds a corresponding module to your
project.
Each module contains all the code and resources that will be built into an Android app package (APK) for
the corresponding device. If you later decide to add support for a new device, you can add a module at
that time. And you can share code and resources between modules using an Android library.
To see more information about the different Android versions, click Help me choose. This opens a new
window that shows the distribution of devices running each version of Android. Click on an API level to
see a summary of top features introduced in that version. To return to the wizard, click OK.
17
Course Manual for Android App Development
Once you've selected your form factors and API versions, click Next.
The next screen lets you select an activity type to add to your app, as shown in figure 3. This screen
displays a different set of activities for each of the form factors you selected earlier.
Note: If you choose "Add No Activity," click Finish to create the project.
18
Course Manual for Android App Development
The next screen lets you configure the activity to add to your app, as shown in figure 4.
Enter the activity name, the layout name, and the activity title. Then click Finish. Android Studio now
sets up your project and opens the IDE.
19
Course Manual for Android App Development
View:
View is a simple rectangle box which responds to the user's actions. View refers to the android.view.View
class, which is the base class of all UI classes. Examples are EditText, Button, CheckBox etc..
Layout:
A layout defines the visual structure for a user interface, such as the UI for an activity or app widget. You
can declare a layout in two ways:
• Declare UI elements in XML. Android provides a straightforward XML vocabulary that corresponds
to the View classes and subclasses, such as those for widgets and layouts.
• Instantiate layout elements at runtime. Your application can create View and ViewGroup objects
(and manipulate their properties) programmatically.
Widgets in Android Studio are a layout builder that enables users to make UI Element easily.
20
Course Manual for Android App Development
Design a simple activity layout for some basic user operation (practical)
In the Project window, right-click the app folder and select New > Activity > Empty Activity.
In the Configure Activity window, enter "DisplayMessageActivity" for Activity Name and click Finish
(leave all other properties set to the defaults).
Every app project must have an AndroidManifest.xml file (with precisely that name) at the root of the
project source set. The manifest file describes essential information about your app to the Android build
tools, the Android operating system, and Google Play.
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:largeHeap="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
21
Course Manual for Android App Development
2. Click Create Virtual Device, at the bottom of the AVD Manager dialog.
22
Course Manual for Android App Development
If you don't see the hardware profile you want, you can create or import a hardware profile.
4. Select the system image for a particular API level, and then click Next.
The Recommended tab lists recommended system images. The other tabs include a more
complete list. The right pane describes the selected system image. x86 images run the fastest in
the emulator.
If you see Download next to the system image, you need to click it to download the system
image. You must be connected to the internet to download it.
23
Course Manual for Android App Development
The API level of the target device is important, because your app won't be able to run on a system
image with an API level that's less than that required by your app, as
Click Show Advanced Settings to show more settings, such as the skin.
The new AVD appears in the Your Virtual Devices page or the Select Deployment Target
dialog.
24
Course Manual for Android App Development
PRACTICE:
https://www.pdfdrive.net/head-first-javapdf-e18943750.html
http://www.academia.edu/32243463/Java_A_Beginners_Guide_6th_Edition_PDF_
REFERENCE LINK:
https://developer.android.com/studio/projects/create-project.html
https://developer.android.com/guide/topics/appwidgets/index.htmlhttps://developer.android.com/guide/in
dex.html
25
Course Manual for Android App Development
CHAPTER OVERVIEW:
The following pages cover everything about user input, from basic touch input and gestures, to
keyboards and game controllers. You can add conventient features such as copy/paste and spell
checking to your app, and develop your own text services to offer custom keyboards (Input Method
Editors), dictionaries, and spelling checkers that you can distribute to users as applications.
OBJECTIVES:
4.1-Android Themes
4.2- Simplifying User Input
4.3-Declaring Variables
LEARNING OUTCOME:
26
Course Manual for Android App Development
• Android Themes
CORE DISCUSSION:
• Fundamental technology:
An input method editor (IME) is a user control that enables users to enter text. Android provides an
extensible input-method framework that allows applications to provide users alternative input
methods, such as on-screen keyboards or even speech input. After installing the desired IMEs, a user
can select which one to use from the system settings, and use it across the entire system; only one
IME may be enabled at a time.
To add an IME to the Android system, you create an Android application containing a class that
extends Input Method Service. In addition, you usually create a "settings" activity that passes
options to the IME service. You can also define a settings UI that's displayed as part of the system
settings.
• Scope of implementation & case study
4.1-Android Themes :
Styles and themes on Android allow you to separate the details of your app design from the UI structure
and behavior, similar to stylesheets in web design.
A style is a collection of attributes that specify the appearance for a single View. A style can specify
attributes such as font color, font size, background color, and much more.
A theme is a type of style that's applied to an entire app, activity, or view hierarchy, not just an individual
view. When you apply your style as a theme, every view in the app or activity applies each style attribute
that it supports. Themes can also apply styles to non-view elements, such as the status bar and window
background.
27
Course Manual for Android App Development
Styles and themes are declared in a style resource file in res/values/, usually named styles.xml.
Figure 1. Two themes applied to the same activity: Theme.AppCompat (left) and
Theme.AppCompat.Light (right)
To create a new style or theme, open your project's res/values/styles.xml file. For each style you want to
create, follow these steps:
1. Add a <style> element with a name that uniquely identifies the style.
2. Add an <item> element for each style attribute you want to define.
The name in each item specifies an attribute you would otherwise use as an XML attribute in your layout.
The value in the <item> element is the value for that attribute.
28
Course Manual for Android App Development
<TextView
style="@style/GreenText"
... />
Each attribute specified in the style is applied to that view if the view accepts it. The view simply ignores
any attributes that it does not accept.
Note: Only the element to which you add the style attribute receives those style attributes—any child
views do not apply the styles. If you want child views to inherit styles, instead apply the style with the
android:theme attribute.
Every text field expects a certain type of text input, such as an email address, phone number, or just plain
text. So it's important that you specify the input type for each text field in your app so the system displays
the appropriate soft input method (such as an on-screen keyboard).
Beyond the type of buttons available with an input method, you should specify behaviors such as whether
the input method provides spelling suggestions, capitalizes new sentences, and replaces the carriage
return button with an action button such as a Done or Next. This lesson shows how to specify these
characteristics
You should always declare the input method for your text fields by adding the android:inputType attribute
to the <EditText> element.
For example, if you'd like an input method for entering a phone number, use the "phone" value:
<EditText
android:id="@+id/phone"
29
Course Manual for Android App Development
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="@string/phone_hint"
android:inputType="phone"/>
Or if the text field is for a password, use the "textPassword" value so the text field conceals the user's
input:
<EditText
android:id="@+id/password"
android:hint="@string/password_hint"
android:inputType="textPassword"
... />
There are several possible values documented with the android:inputType attribute and some of the values
can be combined to specify the input method appearance and additional behaviors.
30
Course Manual for Android App Development
The android:inputType attribute allows you to specify various behaviors for the input method. Most
importantly, if your text field is intended for basic text input (such as for a text message), you should
enable auto spelling correction with the "textAutoCorrect" value.
You can combine different behaviors and input method styles with the android:inputType attribute. For
example, here's how to create a text field that capitalizes the first word of a sentence and also auto-
corrects misspellings:
<EditText
android:id="@+id/message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType=
"textCapSentences|textAutoCorrect"
... />
Specify the Input Method Action
Most soft input methods provide a user action button in the bottom corner that's appropriate for the
current text field. By default, the system uses this button for either a Next or Done action unless your text
field allows multi-line text (such as with android:inputType="textMultiLine"), in which case the action
button is a carriage return. However, you can specify additional actions that might be more appropriate
for your text field, such as Send or Go.
To specify the keyboard action button, use the android:imeOptions attribute with an action value such as
"actionSend" or "actionSearch". For example:
31
Course Manual for Android App Development
<EditText
android:id="@+id/search"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="@string/search_hint"
android:inputType="text"
android:imeOptions="actionSend"/>
You can then listen for presses on the action button by defining a TextView.OnEditorActionListener for
the EditText element. In your listener, respond to the appropriate IME action ID defined in the EditorInfo
class, such as IME_ACTION_SEND. For example:
If you want to provide suggestions to users as they type, you can use a subclass of EditText called
AutoCompleteTextView. To implement auto-complete, you must specify an Adapter that provides the
text suggestions. There are several kinds of adapters available, depending on where the data is coming
from, such as from a database or an array.
32
Course Manual for Android App Development
The following procedure describes how to set up an AutoCompleteTextView that provides suggestions
from an array, using ArrayAdapter:
1. Add the AutoCompleteTextView to your layout. Here's a layout with only the text field:
2. Define the array that contains all text suggestions. For example, here's an array of country names
that's defined in an XML resource file (res/values/strings.xml):
Every text field expects a certain type of text input, such as an email address, phone number, or just plain
text. So it's important that you specify the input type for each text field in your app so the system displays
the appropriate soft input method (such as an on-screen keyboard).
Beyond the type of buttons available with an input method, you should specify behaviors such as whether
the input method provides spelling suggestions, capitalizes new sentences, and replaces the carriage
return button with an action button such as a Done or Next. This lesson shows how to specify these
characteristics
33
Course Manual for Android App Development
4.3-Declaring Variables:
Identifiers are the names of variables. They must be composed of only letters, numbers, the underscore,
and the dollar sign ($). They cannot contain white spaces. Identifiers may only begin with a letter, the
underscore, or the dollar sign. A variable cannot begin with a number. All variable names are case
sensitive.
For example:
Initialisation
For example;
ch='a';
a=0;
string=”abcd”
Boolean=true;
Boolean=0;
4.4Working With Mathematical Operations:
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Maths Function" />
<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number" >
34
Course Manual for Android App Development
<requestFocus />
</EditText>
<EditText
android:id="@+id/editText2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number" />
<Button
android:id="@+id/buttonsum"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Sum/Addition" />
<Button
android:id="@+id/buttonsub"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Subtraction" />
<Button
android:id="@+id/buttondiv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Division" />
<Button
android:id="@+id/buttonmul"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="multiplication" />
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
package dev.androidapplink.mathsfunapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
35
Course Manual for Android App Development
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
@Override
public void onClick(View v) {
int x = new Integer(etv.getText().toString());
int y = new Integer(etv2.getText().toString());
int sum = x + y; //Perform Maths operation
result.setText("The ANS of " + x + " + " + y + " = " + sum);//print answer
}
});
btnsub.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
int x = new Integer(etv.getText().toString());
int y = new Integer(etv2.getText().toString());
int sub = x - y; //Perform Maths operation
result.setText("The ANS of " + x + " - " + y + " = " + sub);//print answer
}
});
btndiv.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
36
Course Manual for Android App Development
btnmul.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
int x = new Integer(etv.getText().toString());
int y = new Integer(etv2.getText().toString());
int mul = x * y; //Perform Maths operation
result.setText("The ANS of " + x + " * " + y + " = " + mul);//Print answer
}
});
}
Addition/Sum:
37
Course Manual for Android App Development
Subtraction:
Division:
38
Course Manual for Android App Development
Multiplication:
PRACTICE:
https://commonsware.com/Android/Android-4.7-CC.pdf
https://developer.android.com/guide/topics/text/creating-input-method
REFERENCE LINK:
https://www.tutorialspoint.com/android/android_resources.htm
39
Course Manual for Android App Development
CHAPTER OVERVIEW:
OBJECTIVES:
LEARNING OUTCOME:
CORE DISCUSSION:
• Historical approach:
Detecting and recognizing brake lights is essential to avoid collisions and accidents caused by a vehicle
driving behind another vehicle. This refers to traffic risk, among other things, to man-controlled vehicles
as well as autonomous cars. There are many systems supporting drivers, which are also applied in
autonomous cars. This paper presents a mobile decision-making system warning against traffic risks
related to breaking a preceding vehicle. The new approach is two-stage and real-time one. Unlike other
approaches, the presented solution, thanks to proper limitation of a searched area, works effectively on a
mobile platform with restricted system resources. The results of experiments conducted on real video
sequences on roads in various weather conditions showed high effectiveness of the proposed approach.
40
Course Manual for Android App Development
Step 3- Here add you app icon. You can just simply copy and paste the image in mipmap folder.
Step 4- After placing the image in the mipmap folder. You need to rename the default icon name to your
icon image name.
Step 5- Go to (app -> manifests) open AndroidManifest.xml file. Here find the following code.
android:icon=”@mipmap/ic_launcher“
Here ic_launcher is the default image name, rename it.
41
Course Manual for Android App Development
Important Note:You can make any image as your app icon just define a correct path of the image in
AndroidManifest.xml file.
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
42
Course Manual for Android App Development
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:id="@+id/text"
android:text="@string/ChoiceText" />
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/text"
android:id="@+id/myRadioGroup"
android:background="#abf234"
android:checkedButton="@+id/sound" >
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/sound"
android:text="@string/Sound" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
43
Course Manual for Android App Development
android:id="@+id/vibration"
android:text="@string/Vibration" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/silent"
android:text="@string/Silent" />
</RadioGroup>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/myRadioGroup"
android:layout_marginTop="10dp"
android:id="@+id/chooseBtn"
android:text="@string/Choose" />
</RelativeLayout>
44
Course Manual for Android App Development
The basic attribute of RadioGroup is android:checkedButton , that specifies which radio button should
be checked by default. The other components are inherited from the View class. As you can notice from
the code above, the set of the radio buttons are embodied by a RadioGroup , so every configuration of its
component affects the radio buttons too.
At this step we just going to declare the string references from the activity_main.xml to the appropriate
resource.
So open res/values/strings.xml , go to the respective tab and paste the following code.
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">RadioGroupExample</string>
<string name="action_settings">Settings</string>
<string name="Sound">Sound</string>
<string name="Vibration">Vibration</string>
<string name="Silent">Silent</string>
<string name="Choose">Choose</string>
</resources>
45
Course Manual for Android App Development
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;
46
Course Manual for Android App Development
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
if(checkedId == R.id.silent) {
Toast.makeText(getApplicationContext(), "choice:
Silent",
Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "choice:
Sound",
Toast.LENGTH_SHORT).show();
47
Course Manual for Android App Development
} else {
Toast.makeText(getApplicationContext(), "choice:
Vibration",
Toast.LENGTH_SHORT).show();
});
button = (Button)findViewById(R.id.chooseBtn);
button.setOnClickListener(new OnClickListener() {
@Override
48
Course Manual for Android App Development
if(selectedId == sound.getId()) {
} else {
});
Now let’s have a look at the code above. When a checked radio button is changed in its
group, OnCheckedChangeListener is invoked in order to handle this situation.
The onCheckedChanged() method of this interface, includes the unique id of the radio button that was
selected and caused the invoke of the callback.
In this example we will show you another way of selecting the choice information (for example when a
button is pressed). This can be done through getCheckedRadioButtonId() , which is a public function
of RadioGroup class. This method returns the unique id of the radio button that is chosen from the
group. You can have a look at the code to see how you can handle both situations.
Of course Android system provides us a more dynamic way of changing and handling the attributes of the
application views. As a prerequisite is to map every view with the unique id component of the XML. This
can be done via findViewById() method.
49
Course Manual for Android App Development
Let's say part of a program we're writing needs to calculate if the purchaser of a ticket is eligible for a
child's discount. Anyone under the age of 16 gets a 10% discount on the ticket price.
We can let our program make this decision by using an if-then statement:
In our program, an integer variable called age holds the age of the ticket purchaser. The condition (i.e., is
the ticket purchaser under 16) is placed inside the brackets. If this condition is true, then the statement
beneath the if statement is executed -- in this case a boolean variable isChild is set to true.
The syntax follows the same pattern every time. The if keyword followed by a condition in brackets, with
the statement to execute underneath:
if (condition is true)
execute this statement
The key thing to remember is the condition must equate to a boolean value (i.e., true or false).
Often, a Java program needs to execute more than one statement if a condition is true. This is achieved by
using a block (i.e., enclosing the statements in curly brackets):
This form of the if-then statement is the most commonly used, and it's recommended to use curly
brackets even when there is only one statement to execute.
It improves the readability of the code and leads to fewer programming mistakes. Without the curly
brackets, it's easy to overlook the effect of the decision being made or to come back later and add another
statement to execute but forget to also add the curly brackets.
The if-then statement can be extended to have statements that are executed when the condition is false.
The if-then-else statement executes the first set of statements if the condition is true, otherwise, the
second set of statements are executed:
50
Course Manual for Android App Development
if (condition)
{
execute statement(s) if condition is true
}
else
{
execute statement(s) if condition is false
}
In the ticket program, let's say we need to make sure the discount is equal to 0 if the ticket purchaser is
not a child:
The if-then-else statement also allows the nesting of if-then statements. This allows decisions to follow a
path of conditions. For example, the ticket program might have several discounts. We might first test to
see if the ticket purchaser is a child, then if they're a pensioner, then if they're a student and so on:
As you can see, the if-then-else statement pattern just repeats itself. If at any time the condition is true ,
then the relevant statements are executed and any conditions beneath are not tested to see whether they
are true or false.
For example, if the age of the ticket purchaser is 67, then the highlighted statements are executed and
the (isStudent == true) condition is never tested and the program just continues on.
There is something worth noting about the (isStudent == true) condition. The condition is written to
make it clear that we're testing whether isStudent has a value of true, but because it is a boolean variable,
we can actually write:
51
Course Manual for Android App Development
else if (isStudent)
{
discount = 5;
}
If this is confusing, the way to think about it is like this -- we know a condition is tested to be true or
false.
For integer variables like age, we have to write an expression that can be evaluated to true or false
(e.g., age == 12, age > 35, etc..).
However, boolean variables already evaluate to be true or false. We don't need to write an expression to
prove it because if (isStudent) is already saying "if isStudent is true..". If you want to test that a boolean
variable is false, just use the unary operator!. It inverts a boolean value, therefore if (!isStudent) is
essentially saying "if isStudent is false."
• Switch Case
The switch statement provides an effective way to deal with a section of code that could branch in
multiple directions based on a single variable. It does not support the conditional operators that the if-
then statement does, nor can it handle multiple variables. It is, however, a preferable choice when the
condition will be met by a single variable, because it can improve performance and is easier to maintain.
Here's an example:
switch ( single_variable ) {
case value:
//code_here;
break;
case value:
//code_here;
break;
default:
//set a default;
}
52
Course Manual for Android App Development
Most of the android devices have built-in sensors that measure motion, orientation, and various
environmental condition. The android platform supports three broad categories of sensors.
• Motion Sensors
• Environmental sensors
• Position sensors
Some of the sensors are hardware based and some are software based sensors. Whatever the sensor is,
android allows us to get the raw data from these sensors and use it in our application. For this android
provides us with some classes.
Android provides SensorManager and Sensor classes to use the sensors in our application. In order to
use sensors, first thing you need to do is to instantiate the object of SensorManager class. It can be
achieved as follows.
SensorManager sMgr;
sMgr = (SensorManager)this.getSystemService(SENSOR_SERVICE);
The next thing you need to do is to instantiate the object of Sensor class by calling the
getDefaultSensor() method of the SensorManager class. Its syntax is given below −
Sensor light;
light = sMgr.getDefaultSensor(Sensor.TYPE_LIGHT);
Once that sensor is declared, you need to register its listener and override two methods which are
onAccuracyChanged and onSensorChanged. Its syntax is as follows −
sMgr.registerListener(this, light,SensorManager.SENSOR_DELAY_NORMAL);
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
sMgr =(SensorManager)this.getSystemService(SENSOR_SERVICE);
53
Course Manual for Android App Development
Apart from the these methods, there are other methods provided by the SensorManager class for
managing sensors framework. These methods are listed below −
1 getDefaultSensor(int type)
This method returns a description of the current primary clip on the clipboard but not a
copy of its data.
3
getInclination(float[] I)
This method computes the geomagnetic inclination angle in radians from the inclination
matrix.
This method unregisters a listener for the sensors with which it is registered.
This method computes the device's orientation based on the rotation matrix.
This method computes the Altitude in meters from the atmospheric pressure and the
pressure at sea level.
54
Course Manual for Android App Development
Example
Here is an example demonstrating the use of SensorManager class. It creates a basic application that
allows you to view the list of sensors on your device.
To experiment with this example, you can run this on an actual device or in an emulator.
Steps Description
1 You will use Android studio to create an Android application under a package
com.example.sairamkrishna.myapplication.
4 Run the application and choose a running android device and install the application on it
and verify the results.
package com.example.sairamkrishna.myapplication;
import android.app.Activity;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
55
Course Manual for Android App Development
import android.widget.TextView;
import java.util.List;
import android.hardware.Sensor;
import android.hardware.SensorManager;
publicclassMainActivityextendsActivity{
TextView tv1=null;
privateSensorManager mSensorManager;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1.setVisibility(View.GONE);
tv1.setVisibility(View.VISIBLE);
56
Course Manual for Android App Development
@Override
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
returntrue;
@Override
// Handle action bar item clicks here. The action bar will
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if(id == R.id.action_settings){
returntrue;
returnsuper.onOptionsItemSelected(item);
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"
57
Course Manual for Android App Development
android:layout_height="match_parent"android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:transitionGroup="true">
<TextViewandroid:text="Sensor "android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textview"
android:textSize="35dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point"
android:id="@+id/textView"
android:layout_below="@+id/textview"
android:layout_centerHorizontal="true"
android:textColor="#ff7aff24"
android:textSize="35dp"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
58
Course Manual for Android App Development
android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:theme="@style/Base.TextAppearance.AppCompat"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="@+id/textView2"
android:layout_below="@+id/imageView"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"/>
</RelativeLayout>
<resources>
<stringname="app_name">My Application</string>
<stringname="hello_world">Hello world!</string>
<stringname="action_settings">Settings</string>
59
Course Manual for Android App Development
</resources>
<manifestxmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name">
<intent-filter>
<actionandroid:name="android.intent.action.MAIN"/>
<categoryandroid:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run our application we just modified. I assume you had created your AVD while doing
environment setup. To run the app from Android studio, open one of your project's activity files and
60
Course Manual for Android App Development
click Run icon from the toolbar. Android studio installs the app on your AVD and starts it and if
everything is fine with your setup and application, it will display following Emulator window −
Now if you will look at your device screen, you will see the list of sensors supported by your device
along with their name and version and other information.
If you would run this application on different devices, the output would be different because the output
depends upon the number of sensors supported by your device.
PRACTICE:
Launcher Icon -> RadioGroup Controls -> Conditional Statements-> Different Types of Sensors
https://nanopdf.com/download/9781133597209pptch04_pdf
REFERENCE LINK:
http://abhiandroid.com/androidstudio/change-icon-android-studio.html
http://www.vogella.com/tutorials/AndroidSensor/article.html
61
Course Manual for Android App Development
CHAPTER OVERVIEW:
An ordered collection (also known as a sequence). The user of this interface has precise control over
where in the list each element is inserted. The user can access elements by their integer index (position
in the list), and search for elements in the list.
6.3-Implement onListItemClick
6.5- Simple app using the module taught. E.g.: Simple MediaPlayer
OBJECTIVES:
LEARNING OUTCOME:
• ListView Layout
• ListView Item Layout
62
Course Manual for Android App Development
CORE DISCUSSION:
• Fundamental technology
1. Create your own custom ListView. Your activity should extend ListActivity.
2. Override onListItemClick.
3. In onListItemClick implementation, create a dialog box, set its content view and then show
the dialog.
4. The dialog box should contain the illustrator’s name and picture.
ListView Layout
If you are new to creating list view, read my article on building customized ListView.
Below XML is the layout of ListView.
<?xmlversion="1.0"encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/taskListParent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
63
Course Manual for Android App Development
<ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</LinearLayout>
List Item will show the cartoon character, some description about the character and the character’s name.
Below XML describes its layout.
cartoon_list_item_view.xml:
<?xmlversion="1.0"encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="@+id/cartoon_pic"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_marginRight="6dip"
android:layout_weight="0"/>
64
Course Manual for Android App Development
<TextView
android:id="@+id/about_cartoon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/name"
android:layout_weight="1"/>
</LinearLayout>
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/name"/>
</LinearLayout>
Here is our ListActivity class. In our activity class, we set the content view to ListView’s layout and then
attach the model.
CartoonListActivity:
packagecom.javarticles.android;
importjava.util.ArrayList;
importjava.util.List;
importandroid.app.Dialog;
importandroid.app.ListActivity;
importandroid.os.Bundle;
importandroid.view.View;
importandroid.view.View.OnClickListener;
importandroid.widget.Button;
65
Course Manual for Android App Development
importandroid.widget.ListView;
importandroid.widget.TextView;
publicclassCartoonListActivity extendsListActivity {
privateCartoonListAdapter cartoonListAdapter;
@Override
protectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cartoon_list_view);
List cartoonList = newArrayList();
cartoonList
.add(newCartoon(
"Tintin",
R.drawable.tintin_thumb,
"Tintin is a fictional character in The Adventures of Tintin, the comics series by Belgian
cartoonist Hergé.",
"Herge", R.drawable.herge));
cartoonList
.add(newCartoon(
"Asterix",
R.drawable.asterix_thumb,
"Asterix is a fictional character, the titular hero of the French comic book series The
Adventures of Asterix. The series portrays him as a diminutive but fearless Gaulish warrior living in the
time of Julius Caesar's Gallic Wars",
"Abbert Underzo", R.drawable.albbert_uderzo));
cartoonListAdapter = newCartoonListAdapter(this,
R.layout.cartoon_list_item_view, cartoonList);
setListAdapter(cartoonListAdapter);
}
}
Our Model contains simple beans of Cartoon class.
CartoonListAdapter:
packagecom.javarticles.android;
importjava.util.List;
importandroid.content.Context;
importandroid.view.LayoutInflater;
importandroid.view.View;
importandroid.view.ViewGroup;
importandroid.widget.ArrayAdapter;
importandroid.widget.ImageView;
importandroid.widget.TextView;
publicclassCartoonListAdapter extendsArrayAdapter{
privateList cartoonItems;
privateContext context;
66
Course Manual for Android App Development
@Override
publicView getView(intposition, View convertView, ViewGroup parent) {
if(cartoon != null) {
// name
TextView nameTextView = (TextView) view.findViewById(R.id.name);
nameTextView.setText(cartoon.getName());
// thumb image
ImageView imageView = (ImageView) view.findViewById(R.id.cartoon_pic);
imageView.setImageResource(cartoon.getCartoonPicRes());
returnview;
}
}
Now comes the part, we are most interested in, that is, to display the illustrator details on selecting the
item.
Our dialog will contain a text field and a ‘close’ dialog button. We will set the illustrator’s name and
picture dynamically in the onListItemClick() as soon as the list item is selected.
author_dialog.xml:
?xmlversion="1.0"encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
67
Course Manual for Android App Development
<TextView
android:id="@+id/author_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/illustrator"/>
<Button
android:id="@+id/close_author_dialog_button"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/close"/>
</LinearLayout>
6.3-Implement onListItemClick :
In onListItemClick, based on the list item selected, we will first get the Cartoon bean the row represents.
Next step would be to create a customized dialog. We will create a Dialog Object and set its title. The title
would be manufactured based on the cartoon character’s name.
Once we create the dialog object, we need to set its content view to author_dialog layout.
Next step would be to populate the dialog fields. We need to find the illustrator’s text widget from the
dialog’s view and set the illustrator’s name. We also need to set the picture of the illustrator on the same
text field, using textView.setCompoundDrawablesWithIntrinsicBounds.
The dialog box has a ‘Close’ button to close the dialog. We will set a listener to the ‘Close’ button to
close the dialog using dialog.dismiss(). The final step would be to show the dialog using dialog.show().
CartoonListActivity:
packagecom.javarticles.android;
importjava.util.ArrayList;
importjava.util.List;
importandroid.app.Dialog;
importandroid.app.ListActivity;
68
Course Manual for Android App Development
importandroid.os.Bundle;
importandroid.view.View;
importandroid.view.View.OnClickListener;
importandroid.widget.Button;
importandroid.widget.ListView;
importandroid.widget.TextView;
publicclassCartoonListActivity extendsListActivity {
privateCartoonListAdapter cartoonListAdapter;
@Override
protectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cartoon_list_view);
List cartoonList = newArrayList();
cartoonList
.add(newCartoon(
"Tintin",
R.drawable.tintin_thumb,
"Tintin is a fictional character in The Adventures of Tintin, the comics series by Belgian
cartoonist Hergé.",
"Herge", R.drawable.herge));
cartoonList
.add(newCartoon(
"Asterix",
R.drawable.asterix_thumb,
"Asterix is a fictional character, the titular hero of the French comic book series The
Adventures of Asterix. The series portrays him as a diminutive but fearless Gaulish warrior living in the
time of Julius Caesar's Gallic Wars",
"Abbert Underzo", R.drawable.albbert_uderzo));
cartoonListAdapter = newCartoonListAdapter(this,
R.layout.cartoon_list_item_view, cartoonList);
setListAdapter(cartoonListAdapter);
}
@Override
protectedvoidonListItemClick(ListView l, View v, intposition, longid) {
super.onListItemClick(l, v, position, id);
privatevoiddisplayIllustratorInDialog(Cartoon cartoon) {
finalDialog dialog = newDialog(this);
dialog.setTitle(cartoon.getName() + "'s "
+ getString(R.string.illustrator));
dialog.setContentView(R.layout.author_dialog);
TextView author = (TextView) dialog.findViewById(R.id.author_name);
author.setCompoundDrawablesWithIntrinsicBounds(0,
cartoon.getAuthorPicRes(), 0, 0);
69
Course Manual for Android App Development
author.setText(cartoon.getAuthorName());
finalButton closeButton = (Button) dialog
.findViewById(R.id.close_author_dialog_button);
closeButton.setOnClickListener(newOnClickListener() {
@Override
publicvoidonClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
int i =2;
switch(i){
case1:{
Toast.makeText(MainActivity.this,”press
1”,Toast.LENGTH_SHORT).show();
break;
}
case2:{
Toast.makeText(MainActivity.this,”press
2”,Toast.LENGTH_SHORT).show();
break;
}
case3:{
Toast.makeText(MainActivity.this,”press
3”,Toast.LENGTH_SHORT).show();
break;
}
default:{
Toast.makeText(MainActivity.this,”nothing
press”,Toast.LENGTH_SHORT).show();
}
}// END of switch
}
70
Course Manual for Android App Development
Android application components can connect to other Android applications. This connection is based on a
task description represented by an Intent object.
Intents are asynchronous messages which allow application components to request functionality from other
Android components. Intents allow you to interact with components from the same applications as well as
with components contributed by other applications. For example, an activity can start an external activity
for taking a picture.
Example:
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
71
Course Manual for Android App Development
import android.view.View;
import android.widget.Button;
publicclassMainActivityextendsAppCompatActivity{
Button b1,b2;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.button);
b1.setOnClickListener(newView.OnClickListener(){
@Override
Intent i =newIntent(android.content.Intent.ACTION_VIEW,
Uri.parse("http://www.example.com"));
startActivity(i);
});
b2=(Button)findViewById(R.id.button2);
b2.setOnClickListener(newView.OnClickListener(){
@Override
Intent i =newIntent(android.content.Intent.ACTION_VIEW,
72
Course Manual for Android App Development
Uri.parse("tel:9510300000"));
startActivity(i);
});
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Intent Example"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp"/>
73
Course Manual for Android App Development
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point"
android:textColor="#ff87ff09"
android:textSize="30dp"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true"/>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
android:src="@drawable/abc"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:layout_below="@+id/imageButton"
android:layout_alignRight="@+id/imageButton"
android:layout_alignEnd="@+id/imageButton"/>
74
Course Manual for Android App Development
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Browser"
android:id="@+id/button"
android:layout_alignTop="@+id/editText"
android:layout_alignRight="@+id/textView1"
android:layout_alignEnd="@+id/textView1"
android:layout_alignLeft="@+id/imageButton"
android:layout_alignStart="@+id/imageButton"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Phone"
android:id="@+id/button2"
android:layout_below="@+id/button"
android:layout_alignLeft="@+id/button"
android:layout_alignStart="@+id/button"
android:layout_alignRight="@+id/textView2"
android:layout_alignEnd="@+id/textView2"/>
</RelativeLayout>
<resources>
<stringname="app_name">My Applicaiton</string>
75
Course Manual for Android App Development
</resources>
<manifestxmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.saira_000.myapplication">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activityandroid:name=".MainActivity">
<intent-filter>
<actionandroid:name="android.intent.action.MAIN"/>
<categoryandroid:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
• LinearLayout – Positions child views in a single row or column depending on the orientation
selected. A weight value can be set on each child to specify how much of the layout space that child
should occupy relative to other children.
76
Course Manual for Android App Development
• TableLayout – Arranges child views into a grid format of rows and columns. Each row within a
table is represented by a TableRow object child, which, in turn, contains a view object for each cell.
• FrameLayout – The purpose of the FrameLayout is to allocate an area of screen, typically for the
purposes of displaying a single view. If multiple child views are added they will, by default, appear
on top of each other positioned in the top left hand corner of the layout area. Alternate positioning of
individual child views can be achieved by setting gravity values on each child. For example, setting a
center_vertical gravity on a child will cause it to be positioned in the vertical center of the containing
FrameLayout view.
• RelativeLayout – Probably the most powerful and flexible of the layout managers, this allows child
views to be positioned relative both to each other and the containing layout view through the
specification of alignments and margins on child views. For example, child View A may be
configured to be positioned in the vertical and horizontal center of the containing RelativeLayout
view. View B, on the other hand, might also be configured to be centered horizontally within the
layout view, but positioned 30 pixels above the top edge of View A, thereby making the vertical
position relative to that of View A. The RelativeLayout manager can be of particular use when
designing a user interface that must work on a variety of screen sizes and orientations.
• AbsoluteLayout – Allows child views to be positioned at specific X and Y coordinates within the
containing layout view. Use of this layout is discouraged since it lacks the flexibility to respond to
changes in screen size and orientation.
• GridLayout – The GridLayout is a relatively new layout manager that was introduced as part of
Android 4.0. A GridLayout instance is divided by invisible lines that form a grid containing rows and
columns of cells. Child views are then placed in cells and may be configured to cover multiple cells
both horizontally and vertically allowing a wide range of layout options to be quickly and easily
implemented. Gaps between components in a GridLayout may be implemented by placing a special
type of view called a Space view into adjacent cells, or by setting margin parameters.
Carefully follow my steps to work with the multiple activities and navigate the activities in an Android
Studio. I have included the source code below.
activity_first.xml code
77
Course Manual for Android App Development
Create the new activity_second.xml file. (XML File directory :App -> res-> layout). Put your activity
name, followed by clicking OK.
78
Course Manual for Android App Development
Go to activity_second.xml, followed by clicking the text bottom. This XML file contains the designing
code for an Android app. In activity_second.xml, copy and paste the code given below.
activity_second.xml code
Repeat the step 7and create an activity_third.xml. Go to activity_third.xml, followed by clicking text
bottom. This XML file contains designing the code for an Android app. In an activity_third.xml, copy and
paste the code given below.
activity_third.xml code
79
Course Manual for Android App Development
6. <TextView
7. android:layout_width="wrap_content"
8. android:layout_height="wrap_content"
9. android:layout_margin="20pt"
10. android:text="Third activity is working ........."
11. android:textAllCaps="true"
12. android:textColor="@color/colorPrimary"
13. />
14.
15. </LinearLayout>
In FirstActivity.java, copy and paste the code given below. Java programming is the backend language for
an Android. Do not replace your package name, else an app will not run. The code given below contains
my package name. FirstActivity.java code is given below.
1. package ganeshannt.frist;
2.
3. import android.content.Intent;
4. import android.os.Bundle;
5. import android.support.v7.app.AppCompatActivity;
6. import android.view.View;
7. import android.widget.Button;
8. import android.widget.TextView;
9.
10. public class FristActivity extends AppCompatActivity {
11. TextView textView;
12.
13. @Override
14. protected void onCreate(Bundle savedInstanceState) {
15. super.onCreate(savedInstanceState);
16. setContentView(R.layout.activity_frist);
17. textView = (TextView) findViewById(R.id.text);
18.
19. }
20.
21. public void Ganesh(View View)
22. {
23. String button_text;
24. button_text =((Button)View).getText().toString();
25. if(button_text.equals("click second activity"))
26. {
27. Intent ganesh = new Intent(this,SecondActivity.class);
28. startActivity(ganesh);
29. }
80
Course Manual for Android App Development
Create the new SecondActivity.java file. (Java file directory :App -> Java-> your package name). Put
your class name, followed by clicking OK.
81
Course Manual for Android App Development
In SecondActivity.java, copy and paste the code given below. Do not replace your package name, else an
app will not run. The code given below contains my package name.
SecondActivity.java code
1. package ganeshannt.frist;
2.
3. import android.app.Activity;
4. import android.os.Bundle;
5. import android.support.annotation.Nullable;
6.
7. /**
8. * Created by For on 4/14/2017.
9. */
10.
11. public class SecondActivity extends Activity {
12. @Override
13. protected void onCreate(@Nullable Bundle savedInstanceState) {
14. super.onCreate(savedInstanceState);
15. setContentView(R.layout.activity_second);
16.
17. }
18. }
Repeat the step 11and create ThirdActivity.java. Go to ThirdActivity.java, followed by copying and
pasting the code given below.
ThirdActivity.java
1. package ganeshannt.frist;
2.
3. import android.app.Activity;
4. import android.os.Bundle;
5. import android.support.annotation.Nullable;
6.
7. /**
8. * Created by For on 4/14/2017.
9. */
10.
11. public class ThirdActivity extends Activity {
12. @Override
13. protected void onCreate(@Nullable Bundle savedInstanceState) {
14. super.onCreate(savedInstanceState);
15. setContentView(R.layout.activity_third);
16.
17. }
18. }
82
Course Manual for Android App Development
Add the code given below into androidminifest.xml within the Application tab. Do not replace all the
code, just copy and paste the code given below.
Androidminifest.xml
1. <activity android:name=".SecondActivity"></activity>
2. <activity android:name=".ThirdActivity"></activity>
6.5- Simple app using the module taught. E.g.: Simple MediaPlayer
PRACTICE:
https://commonsware.com/Android/Android-4.7-CC.pdf
REFERENCE LINK:
http://www.vogella.com/tutorials/AndroidIntent/article.html
https://www.tutorialspoint.com/android/android_alert_dialoges.htm
83
Course Manual for Android App Development
CHAPTER OVERVIEW:
The Android multimedia framework includes support for playing variety of common media types, so
that you can easily integrate audio, video and images into your applications. You can play audio or
video from media files stored in your application's resources (raw resources), from standalone files in
the filesystem, or from a data stream arriving over a network connection, all using MediaPlayer APIs
OBJECTIVES:
LEARNING OUTCOME:
• Splash Screen
84
Course Manual for Android App Development
CORE DISCUSSION:
Simple MediaPlayer
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World by AbhiAndroid!"
android:textSize="20sp"
android:layout_centerInParent="true"/>
</RelativeLayout>
Step 3: Create a new XML file splashfile.xml for Splash screen and paste the following code in it.
This layout contains your app logo or other product logo that you want to show on splash screen.
85
Course Manual for Android App Development
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:background="@color/splashBackground">
<ImageView
android:id="@+id/logo_id"
android:layout_width="250dp"
android:layout_height="250dp"
android:layout_centerInParent="true"
android:src="@drawable/abhiandroid"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/logo_id"
android:layout_centerHorizontal="true"
android:text="Splash Screen"
android:textSize="30dp"
android:textColor="@color/blue"/>
</RelativeLayout>
Step 4: Now open app -> java -> package -> MainActivity.java and add the below code.
package abhiandroid.com.splashscreen;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
86
Course Manual for Android App Development
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Step 5: For Splash Screen we will create a separate splash activity. Create a new class in your java
package and name it as SplashActivity.java.
Step 6: Add this code in SplashActivity.java activity. In this code handler is used to hold the screen for
specific time and once the handler is out, our main Activity will be launched. We are going to hold the
Splash screen for three second’s. We will define the seconds in millisecond’s after Post Delayed(){}
method.
1 second =1000 milliseconds.
Post Delayed method will delay the time for 3 seconds. After the delay time is complete, then your main
activity will be launched.
SplashActivity.java
package abhiandroid.com.splashscreen;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
/**
* Created by AbhiAndroid
*/
Handler handler;
87
Course Manual for Android App Development
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splashfile);
handler=new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
Intent intent=new Intent(SplashActivity.this,MainActivity.class);
startActivity(intent);
finish();
}
},3000);
}
}
Step 7: Open AndroidManifest.xml file and make your splashactivity.java class as Launcher activity and
mention the Main Activity as another activity.
AndroidManifest.xml
<application
android:allowBackup="true"
android:icon="@drawable/abhiandroid"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name="abhiandroid.com.splashscreen.SplashActivity">
88
Course Manual for Android App Development
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
Example :
<?xml
version="1.0"encoding="utf-
8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFCDD2"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:id="@+id/contact_form_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="16dp"
android:layout_marginTop="5dp"
89
Course Manual for Android App Development
android:text="Viral Android"
android:textColor="#ce3232"
android:textSize="40sp"
android:typeface="serif" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:backgroundTint="@color/colorPrimaryDark"
android:hint="Name"
android:inputType="textPersonName" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:layout_marginTop="10dp"
android:backgroundTint="@color/colorPrimaryDark"
android:hint="Email"
android:inputType="textEmailAddress" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:backgroundTint="@color/colorPrimaryDark"
android:hint="Phone"
android:inputType="phone" />
<EditText
android:layout_width="fill_parent"
android:layout_height="150dp"
android:layout_marginBottom="10dp"
90
Course Manual for Android App Development
android:layout_marginTop="10dp"
android:backgroundTint="@color/colorPrimaryDark"
android:gravity="top"
android:hint="Your Message"
android:fitsSystemWindows="true"
android:breakStrategy="balanced"
android:inputType="textMultiLine"
android:singleLine="false"
android:padding="5dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:background="@color/colorPrimaryDark"
android:elevation="4dp"
android:paddingLeft="70dp"
android:paddingRight="70dp"
android:text="Submit"
android:textColor="#fff" />
</LinearLayout>
Colors.xml File
Here I have defined color value for status bar, ActionBar/AppBar/Toolbar and other color also.
res/values/colors.xml
<resources>
<colorname="colorPrimary">#F44336</color>
91
Course Manual for Android App Development
<colorname="colorPrimaryDark">#D32F2F</color>
<colorname="colorAccent">#FF4081</color>
<colorname="light_black">#504f4f</color>
<colorname="black">#000000</color>
</resources>
src/SimpleContactFormUIDesign.java
packageviralandroid.com.androidxmluserinterfacetutorial;
importandroid.os.Bundle;
importandroid.support.v7.app.AppCompatActivity;
importandroid.widget.LinearLayout;
publicclassSimpleContactFormUIDesignextendsAppCompatActivity {
@Override
protectedvoidonCreate(BundlesavedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.simple_android_contact_form_ui_design);
92
Course Manual for Android App Development
Adding audio clip to android application is a simple task as it also add some further functionality. Here is
a step by step on how to play music when App will start.
Step 4: Here we added a media file “ring.mp3” . Now open the Java File of desired activity, here we are
adding audio in MainActivity.
93
Course Manual for Android App Development
ring.start();
Step 6: Now run the App and your music will play when App will start.
Step 1: There is no pre featured option in Android for adding raw folder unlike Assets folder. Open App
folder and select res folder
Step 2: Right click on res folder, select New> Directory, then studio will open a dialog box and it will
ask you to enter the name.
Step 3: Write “raw” and click OK. Open res folder and you will find your raw folder under it.
Example
Here is an example demonstrating the use of MediaPlayer class. It creates a basic media player that
allows you to forward, backward, play and pause a song.
94
Course Manual for Android App Development
To experiment with this example, you need to run this on an actual device to hear the audio sound.
Steps Description
1 You will use Android studio IDE to create an Android application under a package
com.example.sairamkrishna.myapplication.
4 Create a new folder under MediaPlayer with name as raw and place an mp3 music file in it
with name as song.mp3
5 Run the application and choose a running android device and install the application on it
and verify the results
package com.example.sairamkrishna.myapplication;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
95
Course Manual for Android App Development
import android.widget.Toast;
import java.util.concurrent.TimeUnit;
publicclassMainActivityextendsActivity{
privateButton b1,b2,b3,b4;
privateImageView iv;
privateMediaPlayer mediaPlayer;
privateSeekBar seekbar;
privateTextView tx1,tx2,tx3;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 =(Button) findViewById(R.id.button);
b2 =(Button) findViewById(R.id.button2);
b3 =(Button)findViewById(R.id.button3);
96
Course Manual for Android App Development
b4 =(Button)findViewById(R.id.button4);
iv =(ImageView)findViewById(R.id.imageView);
tx1 =(TextView)findViewById(R.id.textView2);
tx2 =(TextView)findViewById(R.id.textView3);
tx3 =(TextView)findViewById(R.id.textView4);
tx3.setText("Song.mp3");
seekbar =(SeekBar)findViewById(R.id.seekBar);
seekbar.setClickable(false);
b2.setEnabled(false);
b3.setOnClickListener(newView.OnClickListener(){
@Override
Toast.makeText(getApplicationContext(),"Playing
sound",Toast.LENGTH_SHORT).show();
mediaPlayer.start();
finalTime = mediaPlayer.getDuration();
startTime = mediaPlayer.getCurrentPosition();
if(oneTimeOnly ==0){
seekbar.setMax((int) finalTime);
oneTimeOnly =1;
97
Course Manual for Android App Development
TimeUnit.MILLISECONDS.toMinutes((long) finalTime),
TimeUnit.MILLISECONDS.toSeconds((long) finalTime)-
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long)
finalTime)))
);
TimeUnit.MILLISECONDS.toMinutes((long) startTime),
TimeUnit.MILLISECONDS.toSeconds((long) startTime)-
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long)
startTime)))
);
seekbar.setProgress((int)startTime);
myHandler.postDelayed(UpdateSongTime,100);
b2.setEnabled(true);
b3.setEnabled(false);
});
b2.setOnClickListener(newView.OnClickListener(){
@Override
Toast.makeText(getApplicationContext(),"Pausing
sound",Toast.LENGTH_SHORT).show();
98
Course Manual for Android App Development
mediaPlayer.pause();
b2.setEnabled(false);
b3.setEnabled(true);
});
b1.setOnClickListener(newView.OnClickListener(){
@Override
if((temp+forwardTime)<=finalTime){
mediaPlayer.seekTo((int) startTime);
seconds",Toast.LENGTH_SHORT).show();
}else{
seconds",Toast.LENGTH_SHORT).show();
});
b4.setOnClickListener(newView.OnClickListener(){
@Override
99
Course Manual for Android App Development
if((temp-backwardTime)>0){
mediaPlayer.seekTo((int) startTime);
seconds",Toast.LENGTH_SHORT).show();
}else{
seconds",Toast.LENGTH_SHORT).show();
});
privateRunnableUpdateSongTime=newRunnable(){
publicvoid run(){
startTime = mediaPlayer.getCurrentPosition();
TimeUnit.MILLISECONDS.toMinutes((long) startTime),
TimeUnit.MILLISECONDS.toSeconds((long) startTime)-
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.
toMinutes((long) startTime)))
);
seekbar.setProgress((int)startTime);
myHandler.postDelayed(this,100);
};
100
Course Manual for Android App Development
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"tools:context=".MainActivity">
<TextViewandroid:text="Music Palyer"android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textview"
android:textSize="35dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point"
android:id="@+id/textView"
android:layout_below="@+id/textview"
android:layout_centerHorizontal="true"
android:textColor="#ff7aff24"
101
Course Manual for Android App Development
android:textSize="35dp"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:src="@drawable/abc"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/forward"
android:id="@+id/button"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/pause"
android:id="@+id/button2"
android:layout_alignParentBottom="true"
android:layout_alignLeft="@+id/imageView"
android:layout_alignStart="@+id/imageView"/>
102
Course Manual for Android App Development
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/back"
android:id="@+id/button3"
android:layout_alignTop="@+id/button2"
android:layout_toRightOf="@+id/button2"
android:layout_toEndOf="@+id/button2"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/rewind"
android:id="@+id/button4"
android:layout_alignTop="@+id/button3"
android:layout_toRightOf="@+id/button3"
android:layout_toEndOf="@+id/button3"/>
<SeekBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/seekBar"
android:layout_alignLeft="@+id/textview"
android:layout_alignStart="@+id/textview"
android:layout_alignRight="@+id/textview"
android:layout_alignEnd="@+id/textview"
103
Course Manual for Android App Development
android:layout_above="@+id/button"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Small Text"
android:id="@+id/textView2"
android:layout_above="@+id/seekBar"
android:layout_toLeftOf="@+id/textView"
android:layout_toStartOf="@+id/textView"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Small Text"
android:id="@+id/textView3"
android:layout_above="@+id/seekBar"
android:layout_alignRight="@+id/button4"
android:layout_alignEnd="@+id/button4"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
104
Course Manual for Android App Development
android:id="@+id/textView4"
android:layout_alignBaseline="@+id/textView2"
android:layout_alignBottom="@+id/textView2"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
<resources>
<stringname="app_name">My Application</string>
<stringname="back"><![CDATA[<]]></string>
<stringname="rewind"><![CDATA[<<]]></string>
<stringname="forward"><![CDATA[>>]]></string>
<stringname="pause">||</string>
</resources>
<manifestxmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication">
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<activity
105
Course Manual for Android App Development
android:name="com.example.sairamkrishna.myapplication.MainActivity"
android:label="@string/app_name">
<intent-filter>
<actionandroid:name="android.intent.action.MAIN"/>
<categoryandroid:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
7.5- Simple app using the module taught. E.g.: Simple MediaPlayer: Class work (Practical)
PRACTICE:
https://commonsware.com/Android/Android-4.7-CC.pdf
REFERENCE LINK:
https://developer.android.com/guide/
https://www.tutorialspoint.com/android/android_mediaplayer.htm /
106
Course Manual for Android App Development
CHAPTER OVERVIEW:
Android incorporates industry-leading security features and works with developers and device
implementers to keep the Android platform and ecosystem safe. A robust security model is essential to
enable a vigorous ecosystem of applications and devices built on and around the Android platform and
supported by cloud services. As a result, through its entire development lifecycle, Android has been
subject to a rigorous security program.
OBJECTIVES:
LEARNING OUTCOME:
CORE DISCUSSION:
• Historical approach
Android is designed to be open. Android applications use advanced hardware and software, as well
as local and served data, exposed through the platform to bring innovation and value to consumers.
To realize that value, the platform offers an application environment that protects the confidentiality,
integrity, and availability of users, data, applications, the device, and the network.
107
Course Manual for Android App Development
The Android system installs every Android application with a unique user and group ID. Each application
file is private to this generated user, e.g., other applications cannot access these files. In addition, each
Android application is started in its own process.
Therefore, by means of the underlying Linux kernel, every Android application is isolated from other
running applications.
If data should be shared, the application must do this explicitly via an Android component which handles
the sharing of the data, e.g., via a service or a content provider.
Android contains a permission system and predefined permissions for certain tasks. Every application can
request required permissions. For example, an application may declare that it requires network access. It
can also define new permissions.
The permission concept has changed since API 23. Before API level 23 the user was asked during
installation, after API level the user is asked during runtime.
An Android application declares the required permissions in its Android manifest. It can also define
additional permissions which it can use to restrict access to certain components.
Before API 23 the requested permissions are presented to the user before installing the application. The
user needs to decide if these permissions shall be given to the application.
If the user denies a required permission, the related application cannot be installed. The check of the
permission is only performed during installation. Permissions cannot be denied or granted after the
installation.
Runtime permissions
Android 6.0 Marshmallow (API 23) introduced a new runtime permission model. If your application
targets Android 6.0, you must use the new permissions model.
The two most important protection levels are normal and dangerous permissions:
• Normal permissions which are deemed harmless for the users privacy or the operation of other
applications. For example, the permission to set the time zone. Normal permission are automatically
granted to the application. See Normal permissions for a complete list.
• Dangerous permissions affect the users private information, or could potentially affect his data or the
operation of other application. For example, the ability to read the users contact data. Dangerous
permissions must be granted by the user at runtime to the app.
108
Course Manual for Android App Development
You can check, if you have the permission, via the checkSelfPermission method.
https://commonsware.com/Android/Android-4.7-CC.pdf
REFERENCE LINK:
https://source.android.com/security/
109
Course Manual for Android App Development
CHAPTER OVERVIEW:
One common task for most Android apps is connecting to the Internet. Most network-connected Android
apps use HTTP to send and receive data. This article shows you how to write a simple application that
connects to the Internet, send HTTP GET request & display the response
9.1- HttpURLConnection
9.3-Asynctask Vs Loaders
9.7- Simple app using the module taught. E.g.: Weather Forecasting (Practical)
OBJECTIVES:
LEARNING OUTCOME:
• Secure Communication with HTTPS
• Response Handling
• Posting Content
• Performance
• Handling Network Sign-On
• HTTP Authentication
• Sessions with Cookies
• HTTP Methods
• Proxies
• IPv6 Support
• Response Caching
• Avoiding Bugs In Earlier Releases
• Number Handling
• AsyncTask
• AsyncTask usage
110
Course Manual for Android App Development
• AsyncTask parameters
• Executing an AsyncTask
• Cancelling an AsyncTask
• Limitations of AsyncTask
• Handler
• HandlerThread
• Create Java Classes for Resources
• Creating the Retrofit instance
• Define the Endpoints
• RxJava
• Using Authentication Headers
• Email
• SMS
• Phone Call
CORE DISCUSSION:
• Fundamental technology
Retrofit Android
Retrofit is type-safe REST client for Android and Java which aims to make it easier to consume RESTful
web services. We’ll not go into the details of Retrofit 1.x versions and jump onto Retrofit 2 directly
which has a lot of new features and a changed internal API compared to the previous versions.
Retrofit 2 by default leverages OkHttp as the networking layer and is built on top of it.
111
Course Manual for Android App Development
• Alternative technology
Volley
Volley is an HTTP library that makes networking for Android apps easier and most importantly, faster.
Volley is available on GitHub.
Volley excels at RPC-type operations used to populate a UI, such as fetching a page of search results as
structured data. It integrates easily with any protocol and comes out of the box with support for raw
strings, images, and JSON. By providing built-in support for the features you need, Volley frees you from
writing boilerplate code and allows you to concentrate on the logic that is specific to your app.
9.1- HttpURLConnection:
we are going to learn about HTTP/HTTPS POST & GET Requests. Http is an underlying protocol used
by world wide web. POST and GET are two most commonly used HTTP methods for request and
response between the client and the server. GET method basically requests data from specified resource,
whereas Post method submits data to be processed to a specified resource.
A URLConnection with support for HTTP-specific features. See the spec for details.
Uses of this class follow a pattern:
1. Obtain a new HttpURLConnection by calling URL.openConnection() and casting the result
to HttpURLConnection.
2. Prepare the request. The primary property of a request is its URI. Request headers may also include
metadata such as credentials, preferred content types, and session cookies.
3. Optionally upload a request body. Instances must be configured with setDoOutput(true) if they include
a request body. Transmit data by writing to the stream returned by getOutputStream().
4. Read the response. Response headers typically include metadata such as the response body's content
type and length, modified dates and session cookies. The response body may be read from the stream
returned by getInputStream(). If the response has no body, that method returns an empty stream.
112
Course Manual for Android App Development
5. Disconnect. Once the response body has been read, the HttpURLConnection should be closed by
calling disconnect(). Disconnecting releases the resources held by a connection so they may be closed
or reused.
try {
readStream(in);
} finally {
urlConnection.disconnect();
Response Handling
HttpURLConnection will follow up to five HTTP redirects. It will follow redirects from one origin server
to another. This implementation doesn't follow redirects from HTTPS to HTTP or vice versa.
If the HTTP response indicates that an error occurred, getInputStream() will throw an IOException.
Use getErrorStream() to read the error response. The headers can be read in the normal way
using getHeaderFields(),
Posting Content
To upload data to a web server, configure the connection for output using setDoOutput(true).
113
Course Manual for Android App Development
For best performance, you should call either setFixedLengthStreamingMode(int) when the body length is
known in advance, or setChunkedStreamingMode(int) when it is not. Otherwise HttpURLConnection will
be forced to buffer the complete request body in memory before it is transmitted, wasting (and possibly
exhausting) heap and increasing latency.
For example, to perform an upload:
try {
urlConnection.setDoOutput(true);
urlConnection.setChunkedStreamingMode(0);
writeStream(out);
readStream(in);
} finally {
urlConnection.disconnect();
Performance
The input and output streams returned by this class are not buffered. Most callers should wrap the
returned streams with BufferedInputStream or BufferedOutputStream. Callers that do only bulk reads or
writes may omit buffering.
When transferring large amounts of data to or from a server, use streams to limit how much data is in
memory at once. Unless you need the entire body to be in memory at once, process it as a stream (rather
than storing the complete body as a single byte array or string).
To reduce latency, this class may reuse the same underlying Socket for multiple request/response pairs.
As a result, HTTP connections may be held open longer than necessary. Calls to disconnect() may return
the socket to a pool of connected sockets.
114
Course Manual for Android App Development
By default, this implementation of HttpURLConnection requests that servers use gzip compression and it
automatically decompresses the data for callers of getInputStream(). The Content-Encoding and Content-
Length response headers are cleared in this case. Gzip compression can be disabled by setting the
acceptable encodings in the request header:
urlConnection.setRequestProperty("Accept-Encoding", "identity");
Setting the Accept-Encoding request header explicitly disables automatic decompression and leaves the
response headers intact; callers must handle decompression as needed, according to the Content-Encoding
header of the response.
getContentLength() returns the number of bytes transmitted and cannot be used to predict how many
bytes can be read from getInputStream() for compressed streams. Instead, read that stream until it is
exhausted, i.e. when read() returns -1.
try {
if (!url.getHost().equals(urlConnection.getURL().getHost())) {
// we were redirected! Kick the user out to the browser to sign on?
...
} finally {
urlConnection.disconnect();
115
Course Manual for Android App Development
HTTP Authentication
HttpURLConnection supports HTTP basic authentication. Use Authenticator to set the VM-wide
authentication handler:
Authenticator.setDefault(new Authenticator() {
});
Unless paired with HTTPS, this is not a secure mechanism for user authentication. In particular, the
username, password, request and response are all transmitted over the network without encryption.
CookieHandler.setDefault(cookieManager);
By default, CookieManager accepts cookies from the origin server only. Two other policies are
included: ACCEPT_ALL and ACCEPT_NONE. ImplementCookiePolicy to define a custom policy.
The default CookieManager keeps all accepted cookies in memory. It will forget these cookies when the
VM exits. Implement CookieStore to define a custom cookie store.
In addition to the cookies set by HTTP responses, you may set cookies programmatically. To be included
in HTTP request headers, cookies must have the domain and path properties set.
By default, new instances of HttpCookie work only with servers that support RFC 2965 cookies. Many
web servers support only the older specification, RFC 2109. For compatibility with the most web servers,
set the cookie version to 0.
116
Course Manual for Android App Development
cookie.setDomain("twitter.com");
cookie.setPath("/");
cookie.setVersion(0);
HTTP Methods
HttpURLConnection uses the GET method by default. It will use POST if setDoOutput(true) has been
called. Other HTTP methods (OPTIONS, HEAD, PUT, DELETE and TRACE) can be used
with setRequestMethod(String).
Proxies
By default, this class will connect directly to the origin server. It can also connect via
an HTTP or SOCKS proxy. To use a proxy, use URL.openConnection(Proxy) when creating the
connection.
IPv6 Support
This class includes transparent support for IPv6. For hosts with both IPv4 and IPv6 addresses, it will
attempt to connect to each of a host's addresses until a connection is established.
Response Caching
Android 4.0 (Ice Cream Sandwich, API level 15) includes a response cache.
See android.net.http.HttpResponseCache for instructions on enabling HTTP caching in your application.
117
Course Manual for Android App Development
System.setProperty("http.keepAlive", "false");
Each instance of HttpURLConnection may be used for one request/response pair. Instances of this class
are not thread safe.
9.2- JSON Parsing:
To create a recursive descent parser for your own JSON streams, first create an entry point method that
creates a JsonReader.
Next, create handler methods for each structure in your JSON text. You'll need a method for each object
type and for each array type.
• Within array handling methods, first call beginArray() to consume the array's opening bracket. Then
create a while loop that accumulates values, terminating when hasNext() is false. Finally, read the
array's closing bracket by calling endArray().
• Within object handling methods, first call beginObject() to consume the object's opening brace. Then
create a while loop that assigns values to local variables based on their name. This loop should
terminate when hasNext() is false. Finally, read the object's closing brace by calling endObject().
When a nested object or array is encountered, delegate to the corresponding handler method.
When an unknown name is encountered, strict parsers should fail with an exception. Lenient parsers
should call skipValue() to recursively skip the value's nested tokens, which may otherwise conflict.
If a value may be null, you should first check using peek(). Null literals can be consumed using
either nextNull() or skipValue().
Example
Suppose we'd like to parse a stream of messages such as the following:
"id": 912345678901,
"geo": null,
"user": {
"name": "android_newb",
118
Course Manual for Android App Development
"followers_count": 41
},
"id": 912345678902,
"user": {
"name": "jesse",
"followers_count": 2
try {
return readMessagesArray(reader);
} finally {
reader.close();
119
Course Manual for Android App Development
reader.beginArray();
while (reader.hasNext()) {
messages.add(readMessage(reader));
reader.endArray();
return messages;
long id = -1;
reader.beginObject();
while (reader.hasNext()) {
if (name.equals("id")) {
id = reader.nextLong();
} else if (name.equals("text")) {
text = reader.nextString();
geo = readDoublesArray(reader);
120
Course Manual for Android App Development
} else if (name.equals("user")) {
user = readUser(reader);
} else {
reader.skipValue();
reader.endObject();
reader.beginArray();
while (reader.hasNext()) {
doubles.add(reader.nextDouble());
reader.endArray();
return doubles;
121
Course Manual for Android App Development
reader.beginObject();
while (reader.hasNext()) {
if (name.equals("name")) {
username = reader.nextString();
} else if (name.equals("followers_count")) {
followersCount = reader.nextInt();
} else {
reader.skipValue();
reader.endObject();
Number Handling
This reader permits numeric values to be read as strings and string values to be read as numbers. For
example, both elements of the JSON array [1, "1"] may be read using either nextInt() or nextString(). This
behavior is intended to prevent lossy numeric conversions: double is JavaScript's only numeric type and
very large values like 9007199254740993 cannot be represented exactly on that platform. To minimize
precision loss, extremely large values should be written and read as strings in JSON.
Each JsonReader may be used to read a single JSON stream. Instances of this class are not thread safe.
AsyncTask
Use the AsyncTask class to implement an asynchronous, long-running task on a worker thread.
(A worker thread is any thread which is not the main or UI thread.) AsyncTask allows you to perform
background operations and publish results on the UI thread without manipulating threads or handlers.
When AsyncTask is executed, it goes through four steps:
122
Course Manual for Android App Development
1. onPreExecute() is invoked on the UI thread before the task is executed. This step is normally used to
set up the task, for instance by showing a progress bar in the UI.
2. doInBackground(Params...) is invoked on the background thread immediately
after onPreExecute()finishes. This step performs a background computation, returns a result, and
passes the result to onPostExecute(). The doInBackground() method can also
call publishProgress(Progress...) to publish one or more units of progress.
3. onProgressUpdate(Progress...) runs on the UI thread after publishProgress(Progress...) is invoked.
Use onProgressUpdate() to report any form of progress to the UI thread while the background
computation is executing. For instance, you can use it to pass the data to animate a progress bar or
show logs in a text field.
4. onPostExecute(Result) runs on the UI thread after the background computation has finished.
For complete details on these methods, see the AsyncTask reference. Below is a diagram of their
calling order.
AsyncTask usage
AsyncTask parameters
In your subclass of AsyncTask, provide the data types for three kinds of parameters:
Specify a data type for each of these parameter types, or use Void if the parameter type will not be
used. For example:
public class MyAsyncTask extends AsyncTask <String, Void, Bitmap>{}
In this class declaration:
123
Course Manual for Android App Development
• The "Params" parameter type is String, which means that MyAsyncTask takes one or more strings as
parameters in doInBackground(), for example to use in a query.
• The "Progress" parameter type is Void, which means that MyAsyncTask won't use
the publishProgress() or onProgressUpdate() methods.
• The "Result" parameter type is Bitmap. MyAsyncTask returns a Bitmap in doInbackground(), which is
passed into onPostExecute().
Example of an AsyncTask
• URL for the "Params" parameter type. The URL type means you can pass any number of URLs into
the call, and the URLs are automatically passed into the doInBackground() method as an array.
• Integer for the "Progress" parameter type.
• Long for the "Result" parameter type.
Executing an AsyncTask
124
Course Manual for Android App Development
After you define a subclass of AsyncTask, instantiate it on the UI thread. Then call execute() on the
instance, passing in any number of parameters. (These parameters correspond to the "Params"
parameter type discussed above).
For example, to execute the DownloadFilesTask task defined above, use the following line of code:
Cancelling an AsyncTask
You can cancel a task at any time, from any thread, by invoking the cancel() method.
• The cancel() method returns false if the task could not be cancelled, typically because it has already
completed normally. Otherwise, cancel() returns true.
• To find out whether a task has been cancelled, check the return value of isCancelled() periodically
from doInBackground(Object[]), for example from inside a loop as shown in the example above.
The isCancelled() method returns true if the task was cancelled before it completed normally.
• After an AsyncTask task is cancelled, onPostExecute() will not be invoked
after doInBackground()returns. Instead, onCancelled(Object) is invoked. The default implementation
of onCancelled(Object) simply invokes onCancelled() and ignores the result.
• By default, in-process tasks are allowed to complete. To allow cancel() to interrupt the thread that's
executing the task, pass true for the value of mayInterruptIfRunning.
Limitations of AsyncTask
When device configuration changes while an AsyncTask is running, for example if the user changes
the screen orientation, the activity that created the AsyncTask is destroyed and re-created.
The AsyncTask is unable to access the newly created activity, and the results of the AsyncTask aren't
published.
• Old AsyncTask objects stay around, and your app may run out of memory or crash.
If the activity that created the AsyncTask is destroyed, the AsyncTask is not destroyed along with it.
For example, if your user exits the application after the AsyncTask has started, the AsyncTask keeps
using resources unless you call cancel().
When to use AsyncTask:
For all other situations, use AsyncTaskLoader, which is part of the Loader framework.
125
Course Manual for Android App Development
Looper
↳ android.os.Looper
Class used to run a message loop for a thread. Threads by default do not have a message loop associated
with them; to create one, call prepare() in the thread that is to run the loop, and then loop() to have it
process messages until the loop is stopped.
Most interaction with a message loop is through the Handler class.
This is a typical example of the implementation of a Looper thread, using the separation
of prepare() and loop() to create an initial Handler to communicate with the Looper.
Looper.prepare();
};
126
Course Manual for Android App Development
Looper.loop();
Handler
public class Handler
extends Object
java.lang.Object
↳ android.os.Handler
A Handler allows you to send and process Message and Runnable objects associated with a
thread's MessageQueue. Each Handler instance is associated with a single thread and that thread's
message queue. When you create a new Handler, it is bound to the thread / message queue of the thread
that is creating it -- from that point on, it will deliver messages and runnables to that message queue and
execute them as they come out of the message queue.
There are two main uses for a Handler: (1) to schedule messages and runnables to be executed as some
point in the future; and (2) to enqueue an action to be performed on a different thread than your own.
Scheduling messages is accomplished with the post(Runnable), postAtTime(Runnable,
long), postDelayed(Runnable, Object,
long), sendEmptyMessage(int), sendMessage(Message), sendMessageAtTime(Message, long),
and sendMessageDelayed(Message, long) methods. The postversions allow you to enqueue Runnable
objects to be called by the message queue when they are received; the sendMessage versions allow you to
enqueue a Message object containing a bundle of data that will be processed by the
Handler's handleMessage(Message) method (requiring that you implement a subclass of Handler).
When posting or sending to a Handler, you can either allow the item to be processed as soon as the
message queue is ready to do so, or specify a delay before it gets processed or absolute time for it to be
processed. The latter two allow you to implement timeouts, ticks, and other timing-based behavior.
When a process is created for your application, its main thread is dedicated to running a message queue
that takes care of managing the top-level application objects (activities, broadcast receivers, etc) and any
windows they create. You can create your own threads, and communicate back with the main application
thread through a Handler. This is done by calling the same post or sendMessage methods as before, but
from your new thread. The given Runnable or Message will then be scheduled in the Handler's message
queue and processed when appropriate.
127
Course Manual for Android App Development
HandlerThread
public class HandlerThread
extends Thread
java.lang.Object
↳ java.lang.Thread
↳ android.os.HandlerThread
1. Create a new HandlerThread, create a new Handler using this HandlerThread and post your tasks on
this handler.
Extend HandlerThread inside your CustomHandlerThread, create a Handler to process your task. You
would take this approach if you know the task you want to perform and just need to pass in parameters. An
example would be creating a HandlerThread to download images or perform networking operations.
Overview
Retrofit is a type-safe REST client for Android (or just Java) developed by Square. The library provides a
powerful framework for authenticating and interacting with APIs and sending network requests
with OkHttp.
This library makes downloading JSON or XML data from a web API fairly straightforward. Once the
data is downloaded then it is parsed into a Plain Old Java Object (POJO) which must be defined for each
"resource" in the response.
Setup
128
Course Manual for Android App Development
}
Note: if you are upgrading from Retrofit 2 beta 1 or beta2, your package imports will need to be changed
from import retrofit.XXXX to import retrofit2.XXXX. You will also need to update your OkHttp imports
from import okhttp.XXXX to import okhttp3.XXXX because of the new OkHttp3 dependency:
find . -name '*.java' -exec gsed -i 's/import retrofit\./import retrofit2./g'\{\} +
find . -name '*.java' -exec gsed -i 's/import com.squareup.okhttp/import okhttp3/g'\{\} +
If you intend to use RxJava with Retrofit 2, you will also need to include the RxJava adapter:
dependencies {
compile 'io.reactivex:rxjava:1.1.6'
compile 'io.reactivex:rxandroid:1.2.1'
compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
}
In the past, Retrofit relied on the Gson library to serialize and deserialize JSON data. Retrofit 2 now
supports many different parsers for processing network response data, including Moshi, a library build by
Square for efficient JSON parsing. However, there are a few limitations, so if you are not sure which one
to choose, use the Gson converter.
There are two approaches discussed in this guide. The first way is the manual approach, which requires
you to learn how to use the Gson library. The second approach is you can also auto-generate the Java
classes you need by capturing the JSON output and using jsonschema2pojo. We encourage you to follow
the manual way to best understand how the auto-generated code approach works.
Assuming you have the JSON response already, go to jsonschema2pojo.org . Make sure to select JSONas
the Source Type:
129
Course Manual for Android App Development
Click the Preview button. You should see the top section look sort of like the following:
130
Course Manual for Android App Development
Paste the generated class into your project under a models sub-package. Rename the class
name Example to reflect your model name. For this example, we will call this file and class
the Usermodel.
Note: Android does not come normally with many of the javax.annotation library by default. If you wish
to keep the @Generated annotation, you will need to add this dependency. See this Stack Overflow
discussion for more context. Otherwise, you can delete that annotation and use the rest of the generated
code.
dependencies {
provided 'org.glassfish:javax.annotation:10.0-b28'
}
To send out network requests to an API, we need to use the [Retrofit builder]
(http://square.github.io/retrofit/2.x/retrofit/retrofit2/Retrofit.Builder.html) class and specify the base URL
for the service.
131
Course Manual for Android App Development
as discussed in this video talk. If we wish to pass in a custom Gson parser instance, it can be specified
too:
With Retrofit 2, endpoints are defined inside of an interface using special retrofit annotations to encode
details about the parameters and request method. In addition, the return value is always a
parameterized Call<T> object such as Call<User>. If you do not need any type-specific response, you can
specify return value as simply Call<ResponseBody>.
For instance, the interface defines each endpoint in the following way:
publicinterfaceMyApiEndpointInterface {
// Request method and URL specified in the annotation
@GET("users/{username}")
Call<User>getUser(@Path("username") Stringusername);
@GET("group/{id}/users")
Call<List<User>>groupList(@Path("id") intgroupId, @Query("sort") Stringsort);
@POST("users/new")
Call<User>createUser(@BodyUseruser);
}
Notice that each endpoint specifies an annotation of the HTTP method (GET, POST, etc.) and method
that will be used to dispatch the network call. Note that the parameters of this method can also have
special annotations:
Annotation Description
variable substitution for the API endpoint (i.e. username will be swapped for {username} in the
@Path URL endpoint).
@Query specifies the query key name with the value of the annotated parameter.
@Body payload for the POST call (serialized from a Java object to a JSON string)
132
Course Manual for Android App Development
Annotation Description
@Header specifies the header with the value of the annotated parameter
Normally, the base URL is defined when you instantiated an Retrofit instance. Retrofit 2 allows you to
override the base URL specified by changing it in the annotation (i.e. if you need to keep one specific
endpoint using an older API endpoint)
@POST("https://api.github.com/api/v3")
There are also others that allow you to modify the base URL using relative paths (and not the fully
qualified URL) as discussed in this blog article.
Adding headers
Notice that there is a @Headers and @Header annotation. The Headers can be used to provide pre-
defined ones:
@Headers({"Cache-Control: max-age=640000", "User-Agent: My-App-Name"})
@GET("/some/endpoint")
We can also add headers as a parameter to the endpoint:
@Multipart
@POST("/some/endpoint")
Call<SomeResponse> someEndpoint(@Header("Cache-Control") int maxAge)
Form data
Multipart forms
If we need to upload images or files, we need to send by using Multipart forms. We will to mark the
endpoint with @Multipart, and label at least one parameter with @Part.
@Multipart
@POST("some/endpoint")
Call<Response> uploadImage(@Part("description") String description, @Part("image") RequestBody
image)
Assuming we have a reference to the file, we can create a RequestBody object:
MediaTypeMEDIA_TYPE_PNG=MediaType.parse("image/png");
file =newFile("/storage/emulated/0/Pictures/MyApp/test.png");
133
Course Manual for Android App Development
If we wish to POST form-encoded name/value pairs, we can use the @FormUrlEncoded and @FieldMap
annotations:
@FormUrlEncoded
@POST("some/endpoint")
Call<SomeResponse> someEndpoint(@FieldMapMap<String, String> names);
Retrofit 2 will use the converter library chosen to handle the deserialization of data from a Java object. If
you annotate the parameter with a @Body parameter, this work will be done automatically. If you are
using the Gson library for instance, any field belonging to the class will be serialized for you. You can
change this name using the @SerializedName decorator:
publicclassUser {
@SerializedName("id")
int mId;
@SerializedName("name")
String mName;
publicUser(intid, Stringname ) {
this.mId = id;
this.mName = name;
}
}
Our endpoint would look like the following:
@POST("/users/new")
Call<User> createUser(@BodyUser user);
We could invoke this API call as follows:
134
Course Manual for Android App Development
@Override
publicvoidonResponse(Call<User>call, Response<User>response) {
@Override
publicvoidonFailure(Call<User>call, Throwablet) {
}
The resulting network call would POST this data:
{"name":"John Doe","id":123}
If you are trying to upgrade from Retrofit 1, you may remember that the last parameter had to be
a Callback type if you wanted to define the API call to run asynchronously instead of synchronously:
publicinterfaceMyApiEndpointInterface {
// Request method and URL specified in the annotation
// Callback for the parsed response is the last parameter
@GET("users/{username}")
voidgetUser(@Path("username") Stringusername, Callback<User>cb);
@GET("group/{id}/users")
voidgroupList(@Path("id") intgroupId, @Query("sort") Stringsort, Callback<List<User>>cb);
@POST("users/new")
voidcreateUser(@BodyUseruser, Callback<User>cb);
}
Retrofit 1 relied on this Callback type as a last parameter to determine whether the API call would be
dispatched asynchronously instead of synchronously. To avoid having two different calling patterns, this
interface was consolidated in Retrofit 2. You now simply define the return value with a
parameterized Call<T>, as shown in the previous section.
We can bring this all together by constructing a service leveraging the MyApiEndpointInterfaceinterface
with the defined endpoints:
MyApiEndpointInterface apiService =
retrofit.create(MyApiEndpointInterface.class);
If we want to consume the API asynchronously, we call the service as follows:
135
Course Manual for Android App Development
@Override
publicvoidonFailure(Call<User>call, Throwablet) {
// Log error here since request failed
}
});
Shown above, Retrofit will download and parse the API data on a background thread, and then deliver the
results back to the UI thread via the onResponse or onFailure method.
Note also that OkHttp, which dispatches the callback on the worker thread, callbacks in Retrofit are
dispatched on the main thread. Because UI updates can only be done on the main thread, the approach
used by Retrofit can make it easier to make changes to your views.
If you are using Retrofit in a Background Service instead of an Activity or Fragment, you can run the
network call synchronously within the same thread by using the execute() method.
try {
Response<User> response = call.execute();
} catch (IOException e ){
// handle error
}
RxJava
Retrofit 2 also supports RxJava extensions. You will need to create an RxJava Adapter. By default, all
network calls are synchronous:
@GET("/users/{username}")
Observable<User>getUser(@Path("username") Stringusername);
@GET("/group/{id}/users")
Observable<List<User>>groupList(@Path("id") intgroupId, @Query("sort") Stringsort);
@POST("/users/new")
Observable<User>createUser(@BodyUseruser);
136
Course Manual for Android App Development
}
Consistent with the RxJava framework, we need to create a subscriber to handle the response. The
methods onCompleted(), onError(), and onNext() need to be added. Using the Android RxJava library, we
can also designate that we will handle this event on the UI main thread. Note: If you intend to override
the default network call behavior, you can specify subscribeOn(). Otherwise, it can omitted. Note: As the
RxJava rewrote their API, the term "Subscription" used here shall be replaced with "Disposable". As the
word "Subscription" had conflict intentions.
String username ="sarahjean";
Observable<User> call = apiService.getUser(username);
Disposable disposable = call
.subscribeOn(Schedulers.io()) // optional if you do not wish to override the default behavior
.observeOn(AndroidSchedulers.mainThread()).subscribeWith(newDisposable<User>() {
@Override
publicvoidonCompleted() {
@Override
publicvoidonError(Throwablee) {
// cast to retrofit.HttpException to get the response code
if (e instanceofHttpException) {
HttpException response = (HttpException)e;
int code = response.code();
}
}
@Override
publicvoidonNext(Useruser) {
}
});
Note that if you are running any API calls in an activity or fragment, you will need to unsubscribe on
the onDestroy() method. The reasons are explained in this Wiki article:
// MyActivity
privateDisposable disposable;
...
protectedvoid onDestroy() {
this.disposable.dispose();
super.onDestroy();
}
Note also that subscribing an observer to the observable is what triggers the network request. For more
information about how to attach multiple observers before dispatching the network requests, see this
section.
137
Course Manual for Android App Development
Headers can be added to a request using an Interceptor. To send requests to an authenticated API, add
headers to your requests using an interceptor as outlined below:
// Define the interceptor, add authentication headers
Interceptor interceptor =newInterceptor() {
@Override
publicokhttp3.Responseintercept(Chainchain) throwsIOException {
Request newRequest = chain.request().newBuilder().addHeader("User-Agent", "Retrofit-Sample-
App").build();
return chain.proceed(newRequest);
}
};
Before starting Email Activity, You must know Email functionality with intent, Intent is carrying data
from one component to another component with-in the application or outside the application.
To send an email from your application, you don’t have to implement an email client from the
beginning, but you can use an existing one like the default Email app provided from Android, Gmail,
Outlook, K-9 Mail etc. For this purpose, we need to write an Activity that launches an email client, using
an implicit Intent with the right action and data. In this example, we are going to send an email from our
app by using an Intent object that launches existing email clients.
Following section explains different parts of our Intent object required to send an email.
138
Course Manual for Android App Development
emailIntent.setData(Uri.parse("mailto:"));
emailIntent.setType("text/plain");
1 EXTRA_BCC
2
EXTRA_CC
3 EXTRA_EMAIL
4
EXTRA_HTML_TEXT
A constant String that is associated with the Intent, used with ACTION_SEND to
supply an alternative to EXTRA_TEXT as HTML formatted text.
5 EXTRA_SUBJECT
6 EXTRA_TEXT
A constant CharSequence that is associated with the Intent, used with ACTION_SEND
139
Course Manual for Android App Development
7 EXTRA_TITLE
Here is an example showing you how to assign extra data to your intent −
EMAIL EXAMPLE
140
Course Manual for Android App Development
Example
Following example shows you in practical how to use Intent object to launch Email client to send an
Email to the given recipients.
To Email experiment with this example, you will need actual Mobile device equipped with latest Android
OS, otherwise you might get struggle with emulator which may not work properly. Second you will need
to have an Email client like GMail(By default every android version having Gmail client App) or K9mail
installed on your device.
Step Description
1 You will use Android studio to create an Android application and name it
as Ictdevition under a package com.example.ictdevition.
2 Modify src/MainActivity.java file and add required code to take care of sending email.
3 Modify layout XML file res/layout/activity_main.xml add any GUI component if required.
I'm adding a simple button to launch Email Client.
6 Run the application to launch Android emulator and verify the result of the changes done in
the application.
package com.example.ictdevition;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
141
Course Manual for Android App Development
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
publicclassMainActivityextendsActivity{
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startBtn.setOnClickListener(newView.OnClickListener(){
sendEmail();
});
protectedvoid sendEmail(){
Log.i("Send email","");
String[] TO ={""};
String[] CC ={""};
142
Course Manual for Android App Development
emailIntent.setData(Uri.parse("mailto:"));
emailIntent.setType("text/plain");
emailIntent.putExtra(Intent.EXTRA_EMAIL, TO);
emailIntent.putExtra(Intent.EXTRA_CC, CC);
emailIntent.putExtra(Intent.EXTRA_SUBJECT,"Your subject");
try{
startActivity(Intent.createChooser(emailIntent,"Send mail..."));
finish();
}catch(android.content.ActivityNotFoundException ex){
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
143
Course Manual for Android App Development
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp"/>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ff87ff09"
android:textSize="30dp"
android:layout_above="@+id/imageButton"
android:layout_alignRight="@+id/imageButton"
android:layout_alignEnd="@+id/imageButton"/>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
android:src="@drawable/abc"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"/>
<Button
android:id="@+id/sendEmail"
android:layout_width="fill_parent"
144
Course Manual for Android App Development
android:layout_height="wrap_content"
android:text="@string/compose_email"/>
</LinearLayout>
<resources>
<stringname="app_name">Ictdevition</string>
<stringname="compose_email">Compose Email</string>
</resources>
<manifestxmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.Ictdevition">
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<activity
android:name="com.example.ictdevition.MainActivity"
android:label="@string/app_name">
<intent-filter>
145
Course Manual for Android App Development
<actionandroid:name="android.intent.action.MAIN"/>
<categoryandroid:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your ICT Division application. I assume you have connected your actual Android
Mobile device with your computer. To run the app from Android Studio, open one of your project's
activity files and click Run icon from the toolbar. Before starting your application, Android studio
installer will display following window to select an option where you want to run your Android
application.
SMS
In Android, you can use SmsManager API or devices Built-in SMS application to send SMS's. In this
tutorial, we shows you two basic examples to send SMS message −
SmsManager API
Apart from the above method, there are few other important functions available in SmsManager class.
These methods are listed below −
146
Course Manual for Android App Development
This method divides a message text into several fragments, none bigger than the
maximum SMS message size.
3
void sendDataMessage(String destinationAddress, String scAddress, short
destinationPort, byte[] data, PendingIntent sentIntent, PendingIntent
deliveryIntent)
This method is used to send a data based SMS to a specific application port.
4
void sendMultipartTextMessage(String destinationAddress, String scAddress,
ArrayList<String> parts, ArrayList<PendingIntent> sentIntents,
ArrayList<PendingIntent> deliveryIntents)
5
void sendTextMessage(String destinationAddress, String scAddress, String text,
PendingIntent sentIntent, PendingIntent deliveryIntent)
147
Course Manual for Android App Development
Phone Call
Android provides Built-in applications for phone calls, in some occasions we may need to make a phone
call through our application. This could easily be done by using implicit Intent with appropriate actions.
Also, we can use PhoneStateListener and TelephonyManager classes, in order to monitor the changes in
some telephony states on the device.
This chapter lists down all the simple steps to create an application which can be used to make a Phone
Call. You can use Android Intent to make phone call by calling built-in Phone Call functionality of the
Android. Following section explains different parts of our Intent object required to make a call.
You can use ACTION_DIAL action instead of ACTION_CALL, in that case you will have option to
modify hardcoded phone number before making a call instead of making a direct call.
phoneIntent.setData(Uri.parse("tel:91-000-000-0000"));
The interesting point is that, to make a phone call, you do not need to specify any extra data or data type.
Example
Following example shows you in practical how to use Android Intent to make phone call to the given
mobile number.
148
Course Manual for Android App Development
To experiment with this example, you will need actual Mobile device equipped with latest Android OS,
otherwise you will have to struggle with emulator which may not work.
Step Description
1 You will use Android studio IDE to create an Android application and name it as My
Application under a package com.example.saira_000.myapplication.
2 Modify src/MainActivity.java file and add required code to take care of making a call.
3 Modify layout XML file res/layout/activity_main.xml add any GUI component if required.
I'm adding a simple button to Call 91-000-000-0000 number
4 No need to define default string constants.Android studio takes care of default constants.
6 Run the application to launch Android emulator and verify the result of the changes done in
the application.
package com.example.saira_000.myapplication;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
149
Course Manual for Android App Development
import android.view.View;
import android.widget.Button;
publicclassMainActivityextendsAppCompatActivity{
privateButton button;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button.setOnClickListener(newView.OnClickListener(){
callIntent.setData(Uri.parse("tel:0377778888"));
if(ActivityCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.CALL_PHONE)!=PackageManager.PERMISSION_GRANTED){
return;
startActivity(callIntent);
});
150
Course Manual for Android App Development
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<Button
android:id="@+id/buttonCall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="call 0377778888"/>
</LinearLayout>
<resources>
<stringname="app_name">My Application</string>
</resources>
<manifestxmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.saira_000.myapplication">
<uses-permissionandroid:name="android.permission.CALL_PHONE"/>
151
Course Manual for Android App Development
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<activity
android:name="com.example.saira_000.myapplication.MainActivity"
android:label="@string/app_name">
<intent-filter>
<actionandroid:name="android.intent.action.MAIN"/>
<categoryandroid:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your My Application application. I assume you have connected your actual Android
Mobile device with your computer. To run the app from Android studio, open one of your project's
activity files and click Run icon from the toolbar.Select your mobile device as an option and then
check your mobile device which will display following screen −
152
Course Manual for Android App Development
153
Course Manual for Android App Development
9.7- Simple app using the module taught. E.g.: Weather Forecasting (Practical)
154
Course Manual for Android App Development
PRACTICE:
https://commonsware.com/Android/Android-4.7-CC.pdf
REFERENCE LINK:
https://www.androidhive.info/2012/01/android-json-parsing-tutorial/
https://www.journaldev.com/13639/retrofit-android-example-tutorial
https://developer.android.com/training/volley/
155
Course Manual for Android App Development
CHAPTER OVERVIEW:
A content provider manages access to a central repository of data. A provider is part of an Android
application, which often provides its own UI for working with the data. However, content providers
are primarily intended to be used by other applications, which access the provider using a provider
client object. Together, providers and provider clients offer a consistent, standard interface to data
that also handles inter-process communication and secure data access.
10.3- Loaders
10.7- Simple app using the module taught. Ex: Quiz app using Firebase
OBJECTIVES:
• Saving data to a database is ideal for repeating or structured data, such as contact information
• Cloud Storage is built for app developers who need to store and serve user-generated content,
such as photos or videos.
• AdMob Integration
LEARNING OUTCOME:
• Save Data using SQLite
• What is SQLite?
• Why SQLite?
• How to manage SQLite database
• Accessing a provider
• Content URIs
• Cloud Storage
• Firebase Real-time Database
• Firebase Authentication
• Firebase Cloud Messaging and Notification
• Google Analytics for Firebase
• Import the Mobile Ads SDK
156
Course Manual for Android App Development
CORE DISCUSSION:
• Fundamental technology
This page assumes that you are familiar with SQL databases in general and helps you get started with
SQLite databases on Android. The APIs you'll need to use a database on Android are available in
the android.database.sqlite package.
What is SQLite?
SQLite is an in-process library that implements a self-contained, serverless, zero-configuration,
transactional SQL database engine. It is a database, which is zero-configured, which means like other
databases you do not need to configure it in your system.
SQLite engine is not a standalone process like other databases, you can link it statically or dynamically
as per your requirement with your application. SQLite accesses its storage files directly.
Why SQLite?
• SQLite does not require a separate server process or system to operate (serverless).
• SQLite is very small and light weight, less than 400KiB fully configured or less than 250KiB
with optional features omitted.
157
Course Manual for Android App Development
• SQLite transactions are fully ACID-compliant, allowing safe access from multiple processes or
threads.
• SQLite supports most of the query language features found in SQL92 (SQL2) standard.
• SQLite is available on UNIX (Linux, Mac OS-X, Android, iOS) and Windows (Win32, WinCE,
WinRT).
There are few unsupported features of SQL92 in SQLite which are listed in the following table.
ALTER TABLE
3 The RENAME TABLE and ADD COLUMN variants of the ALTER TABLE command
are supported. The DROP COLUMN, ALTER COLUMN, ADD CONSTRAINT are not
supported.
Trigger support
4
FOR EACH ROW triggers are supported but not FOR EACH STATEMENT triggers.
VIEWs
5
VIEWs in SQLite are read-only. You may not execute a DELETE, INSERT, or
UPDATE statement on a view.
158
Course Manual for Android App Development
SQLite Commands
The standard SQLite commands to interact with relational databases are similar to SQL. They are
CREATE, SELECT, INSERT, UPDATE, DELETE and DROP. These commands can be classified into
groups based on their operational nature −
1 CREATE
ALTER
2
Modifies an existing database object, such as a table.
DROP
3
Deletes an entire table, a view of a table or other object in the database.
159
Course Manual for Android App Development
1 SELECT
SQLiteManager is a database manager for SQLite databases. You can manage any SQLite database
created on any platform with SQLiteManager. SQLiteManager displays an entire database in one
window.
Many operations do display dialog boxes to complete, but the main browsing and manipulation functions
all happen in one window. The main window has a tab panel that takes you to Design, Manage, and SQL
panels. From here, the Design panel lets you browse the objects in your database.
160
Course Manual for Android App Development
A content provider manages access to a central repository of data. A provider is part of an Android
application, which often provides its own UI for working with the data. However, content providers are
primarily intended to be used by other applications, which access the provider using a provider client
object. Together, providers and provider clients offer a consistent, standard interface to data that also
handles inter-process communication and secure data access.
Typically you work with content providers in one of two scenarios; you may want to implement code to
access an existing content provider in another application, or you may want to create a new content
provider in your application to share data with other applications. This topic covers the basics of working
with existing content providers.
• Overview
A content provider presents data to external applications as one or more tables that are similar to the
tables found in a relational database. A row represents an instance of some type of data the provider
collects, and each column in the row represents an individual piece of data collected for an instance.
A content provider coordinates access to the data storage layer in your application for a number of
different APIs and components as illustrated in figure 1, these include:
Figure: 1
161
Course Manual for Android App Development
• Accessing a provider
When you want to access data in a content provider, you use the ContentResolver object in your
application's Context to communicate with the provider as a client. The ContentResolver object
communicates with the provider object, an instance of a class that implements ContentProvider. The
provider object receives data requests from clients, performs the requested action, and returns the results.
This object has methods that call identically-named methods in the provider object, an instance of one of
the concrete subclasses of ContentProvider. The ContentResolver methods provide the basic "CRUD"
(create, retrieve, update, and delete) functions of persistent storage.
Figure: 2
162
Course Manual for Android App Development
A common pattern for accessing a ContentProvider from your UI uses a CursorLoader to run an
asynchronous query in the background. The Activityor Fragment in your UI call a CursorLoader to the
query, which in turn gets the ContentProvider using the ContentResolver. This allows the UI to continue
to be available to the user while the query is running. This pattern involves the interaction of a number of
different objects, as well as the underlying storage mechanism, as illustrated in figure 2.
• Content URIs
163
Course Manual for Android App Development
• Content URIs
A content URI is a URI that identifies data in a provider. Content URIs include the symbolic name of the
entire provider (its authority) and a name that points to a table (a path). When you call a client method to
access a table in a provider, the content URI for the table is one of the arguments.
In the preceding lines of code, the constant CONTENT_URI contains the content URI of the user
dictionary's "words" table. The ContentResolver object parses out the URI's authority, and uses it to
"resolve" the provider by comparing the authority to a system table of known providers.
TheContentResolver can then dispatch the query arguments to the correct provider.
The ContentProvider uses the path part of the content URI to choose the table to access. A provider
usually has a path for each table it exposes.
In the previous lines of code, the full URI for the "words" table is:
content://user_dictionary/words
where the user_dictionary string is the provider's authority, and the words string is the table's path. The
string content:// (the scheme) is always present, and identifies this as a content URI.
164
Course Manual for Android App Development
Many providers allow you to access a single row in a table by appending an ID value to the end of the
URI. For example, to retrieve a row whose _ID is 4from user dictionary, you can use this content URI:
10.3- Loaders:
The Loader API lets you load data from a content provider or other data source for display in
an FragmentActivity or Fragment. If you don't understand why you need the Loader API to perform this
seemingly trivial operation, then first consider some of the problems you might encounter without
loaders:
• If you fetch the data directly in the activity or fragment, your users will suffer from lack of
responsiveness due to performing potentially slow queries from the UI thread.
• If you fetch the data from another thread, perhaps with AsyncTask, then you're responsible for
managing both the thread and the UI thread through various activity or fragment lifecycle events, such
asonDestroy() and configurations changes.
Loaders solve these problems and includes other benefits. For example:
• Loaders run on separate threads to prevent janky or unresponsive UI.
• Loaders simplify thread management by providing callback methods when events occur.
• Loaders persist and cache results across configuration changes to prevent duplicate queries.
• Loaders can implement an observer to monitor for changes in the underlying data source. For
example, CursorLoader automatically registers a ContentObserver to trigger a reload when data
changes.
165
Course Manual for Android App Development
• Cloud Storage
Cloud Storage for Firebase is a powerful, simple, and cost-effective object storage service built for
Google scale. The Firebase SDKs for Cloud Storage add Google security to file uploads and downloads
for your Firebase apps, regardless of network quality. You can use our SDKs to store images, audio,
video, or other user-generated content. On the server, you can use Google Cloud Storage, to access the
same files.
• Firebase Authentication
Most apps need to know the identity of a user. Knowing a user's identity allows an app to securely save
user data in the cloud and provide the same personalized experience across all of the user's devices.
Firebase Authentication provides backend services, easy-to-use SDKs, and ready-made UI libraries to
authenticate users to your app. It supports authentication using passwords, phone numbers, popular
federated identity providers like Google, Facebook and Twitter, and more.
166
Course Manual for Android App Development
Using FCM, you can notify a client app that new email or other data is available to sync. You can send
notification messages to drive user re-engagement and retention. For use cases such as instant messaging,
a message can transfer a payload of up to 4KB to a client app.
At the heart of Firebase is Google Analytics for Firebase, a free and unlimited analytics solution.
Analytics integrates across Firebase features and provides you with unlimited reporting for up to 500
distinct events that you can define using the Firebase SDK. Analytics reports help you understand clearly
how your users behave, which enables you to make informed decisions regarding app marketing and
performance optimizations.
AdMob by Google helps you monetize your mobile app through in-app advertising. Ads can be
displayed as banner ads, interstitial ads, video ads, or native ads—which are seamlessly added to
platform native UI components. On Android, you can additionally display in-app purchase ads,
which allow users to purchase advertised products from within your app.
Before you can display ads within your app, you'll need to create an AdMob account and activate
one or more Ad Unit IDs. This is a unique identifier for the places in your app where ads are
displayed.
AdMob uses the Google Mobile Ads SDK. The Google Mobile Ads SDK helps app developers
gain insights about their users, drive more in-app purchases, and maximize ad revenue. In order to
do so, the default integration of the Mobile Ads SDK collects information such as device
information, publisher-provided location information, and general in-app purchase information
such as item purchase price and currency.
167
Course Manual for Android App Development
Apps can import the Google Mobile Ads SDK with a Gradle dependency that points to Google's Maven
repository. In order to use that repository, you need to reference it in the app's project-
level build.gradle file. Open yours and look for an allprojects section:
allprojects {
repositories {
jcenter()
maven {
url "https://maven.google.com"
}
}
}
Next, open the app-level build.gradle file for your app, and look for a "dependencies" section.
dependencies {
compile fileTree(dir:'libs', include:['*.jar'])
compile 'com.android.support:appcompat-v7:26.1.0'
compile 'com.google.android.gms:play-services-ads:12.0.1'
}
Add the line in bold above, which instructs Gradle to pull in the latest version of the Mobile Ads SDK.
Once that's done, save the file and perform a Gradle sync.
168
Course Manual for Android App Development
10.7- Simple app using the module taught. Ex: Quiz app using Firebase:
PRACTICE:
https://commonsware.com/Android/Android-4.7-CC.pdf
REFERENCE LINK:
https://firebase.google.com/docs/analytics/
https://www.androidhive.info/2016/02/android-how-to-integrate-google-admob-in-your-app/
https://www.androidhive.info/2011/11/android-sqlite-database-tutorial/
169
Course Manual for Android App Development
CHAPTER OVERVIEW:
At the heart of Firebase is Google Analytics for Firebase, a free and unlimited analytics solution.
Analytics integrates across Firebase features and provides you with unlimited reporting for up to 500
distinct events that you can define using the Firebase SDK. Analytics reports help you understand clearly
how your users behave, which enables you to make informed decisions regarding app marketing and
performance optimizations.
OBJECTIVES:
LEARNING OUTCOME:
170
Course Manual for Android App Development
CORE DISCUSSION:
• Fundamental technology
A Service is an application component that can perform long-running operations in the background, and it
does not provide a user interface. Another application component can start a service, and it continues to
run in the background even if the user switches to another application. Additionally, a component can
bind to a service to interact with it and even perform interprocess communication (IPC). For example, a
service can handle network transactions, play music, perform file I/O, or interact with a content provider,
all from the background.
Foreground
A foreground service performs some operation that is noticeable to the user. For example, an
audio app would use a foreground service to play an audio track. Foreground services must
display a Notification. Foreground services continue running even when the user isn't interacting
with the app.
Background
A background service performs an operation that isn't directly noticed by the user. For example, if
an app used a service to compact its storage, that would usually be a background service.
Note: If your app targets API level 26 or higher, the system imposes restrictions on running
background services when the app itself is not in the foreground. In most cases like this, your app
should use a scheduled job instead.
Bound
A service is bound when an application component binds to it by calling bindService(). A bound
service offers a client-server interface that allows components to interact with the service, send
requests, receive results, and even do so across processes with interprocess communication (IPC).
A bound service runs only as long as another application component is bound to it. Multiple
components can bind to the service at once, but when all of them unbind, the service is destroyed.
Although this documentation generally discusses started and bound services separately,
your service can work both ways—it can be started (to run indefinitely) and also allow
binding. It's simply a matter of whether you implement a couple of callback
methods: onStartCommand() to allow components to start it and onBind() to allow
binding.
Regardless of whether your application is started, bound, or both, any application
component can use the service (even from a separate application) in the same way that
any component can use an activity—by starting it with an Intent. However, you can
declare the service as private in the manifest file and block access from other
171
Course Manual for Android App Development
applications. This is discussed more in the section about Declaring the service in the
manifest.
There can be two forms of a service.The lifecycle of service can follow two different paths:
started or bound.
1. Started
2. Bound
1) Started Service
2) Bound Service
172
Course Manual for Android App Development
API overview
Help your customers explore where they are and what’s around them:
• Place Add adds a place to Google's Places database, for immediate retrieval from within your own app
and for visibility with other apps after moderation.
• Place Report creates a report indicating the current location of the device, helping Google build a local
model of the world.
• Place IDs stores the unique ID for one or more places for retrieval of place information on demand.
With the Google Maps Android API, you can add maps based on Google Maps data to your application.
The API automatically handles access to Google Maps servers, data downloading, map display, and
response to map gestures. You can also use API calls to add markers, polygons, and overlays to a basic
map, and to change the user's view of a particular map area. These objects provide additional information
for map locations, and allow user interaction with the map. The API allows you to add these graphics to a
map:
173
Course Manual for Android App Development
Markers identify locations on the map. The default marker uses a standard icon, common to the Google
Maps look and feel. It's possible to change the icon's color, image or anchor point via the API. Markers
are objects of type Marker, and are added to the map with
the GoogleMap.addMarker(markerOptions) method.
Markers are designed to be interactive. They receive click events by default, and are often used with event
listeners to bring up info windows. Setting a marker's draggable property to true allows the user to change
the position of the marker. Use a long press to activate the ability to move the marker.
By default, when a user taps a marker, the map toolbar appears at the bottom right of the map, giving the
user quick access to the Google Maps mobile app. You can disable the toolbar. For more information, see
the guide to controls.
Add a marker
The following example demonstrates how to add a marker to a map. The marker is created at
coordinates 10,10, and displays the string 'Hello world' in an info window when clicked.
@Override
publicvoid onMapReady(GoogleMap map){
map.addMarker(newMarkerOptions()
.position(newLatLng(10,10))
.title("Hello world"));
}
Customize a marker
174
Course Manual for Android App Development
The marker clustering utility helps you manage multiple markers at different zoom levels. To be precise,
the 'markers' are actually 'items' at this point, and only become 'Markers' when they're rendered. But for
the sake of clarity, this document will name them 'markers' throughout.
When a user views the map at a high zoom level, the individual markers show on the map. When the user
zooms out, the markers gather together into clusters, to make viewing the map easier.
The API returns the most efficient routes when calculating directions. Travel time is the primary factor
optimized, but the API may also take into account other factors such as distance, number of turns and
many more when deciding which route is the most efficient. Calculating directions is a time and resource
intensive task. Whenever possible, use the service described here to calculate known addresses ahead of
time and store the results in a temporary cache of your own design.
Geocoding is the process of converting addresses (like a street address) into geographic coordinates (like
latitude and longitude), which you can use to place markers on a map, or position the map.
Reverse geocoding is the process of converting geographic coordinates into a human-readable address.
You can also use the Google Maps Geocoding API to find the address for a given place ID. Geocoding
request and response (latitude/longitude lookup). The following example requests the latitude and
longitude of "1600 Amphitheatre Parkway, Mountain View, CA", and specifies that the output must be in
JSON format.
https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+
View,+CA&key= YOUR_API_KEY
175
Course Manual for Android App Development
"types":["street_number"]
},
{
"long_name":"Amphitheatre Pkwy",
"short_name":"Amphitheatre Pkwy",
"types":["route"]
}, ………….
Geofencing
Geofencing combines awareness of the user's current location with awareness of the user's proximity to
locations that may be of interest. To mark a location of interest, you specify its latitude and longitude. To
adjust the proximity for the location, you add a radius. The latitude, longitude, and radius define a
geofence, creating a circular area, or fence, around the location of interest.
PRACTICE:
https://commonsware.com/Android/Android-4.7-CC.pdf
REFERENCE LINK:
https://developers.google.com/maps/documentation/directions/intro
https://developer.android.com/training/location/geofencing.html
176
Course Manual for Android App Development
CHAPTER OVERVIEW:
The Canvas class holds the "draw" calls. To draw something, you need 4 basic components: A Bitmap
to hold the pixels, a Canvas to host the draw calls (writing into the bitmap), a drawing primitive (e.g.
Rect, Path, text, Bitmap), and a paint (to describe the colors and styles for the drawing).
OBJECTIVES:
• Android offers a sophisticated and powerful componentized model for building your UI.
• Android Canvas API
LEARNING OUTCOME:
• Canvas API
• Persisting view data
177
Course Manual for Android App Development
CORE DISCUSSION:
• Fundamental technology
Sometimes you want to show a certain type of data and there is already a suitable view in the basic widget
set. But if you want UI customization or a different user interaction, you may need to extend a widget.
Suppose that there were no Button widget in the basic widget set in the Android SDK and you want to
make one. You would extend the TextView class to get all the capabilities related to the text like setting
text, text color, text size, and text style and so on. Then you will start your customization work, to give
your new widget the look and feel of a button. This is what happens in the Android SDK the Button class
extends the TextView class. Or you could in theory extend the View class to start from scratch.
Android offers a sophisticated and powerful componentized model for building your UI, based on the
fundamental layout classes: View and ViewGroup. To start with, the platform includes a variety of
prebuilt View and ViewGroup subclasses — called widgets and layouts, respectively — that you can use
to construct your UI.
The Android framework provides several default views. The base class a view is the View. Views are
responsible for measuring, layouting and drawing themselves and their child elements (in case of
a ViewGroup). Views are also responsible for saving their UI state and handling touch events. Developers
can also create custom views and use them in their application.
178
Course Manual for Android App Development
View are typically created to provide a user interface experience with is not possible with the default
views. Using custom view allows the developer allow to do certain performance optimization, i.e., in case
of a custom layout the development can optimize the layout manager for his use case.
Combound views also allow you to add custom API to update and query the state of the combound view.
For such a control you define a layout file and assign it to your compound view. In the implementation of
your compound view you predefine the view interaction. You would define a layout file and extend the
corresponding ViewGroup class. In this class you inflate the layout file and implement
the View connection logic.
179
Course Manual for Android App Development
The Canvas API allows to create complex graphical effects. You paint on a Bitmap surface.
The Canvas class provides the drawing methods to draw on a bitmap. The Paint class specifies how you
draw on the bitmap.
The Canvas object contains the bitmap on which you draw. It also provides methods for drawing
operations:
For drawing on the Canvas object you use an object of type Paint.
The Paint class allows to specify the color, font and certain effects for the drawing operation.
The setStyle() method allows to specify how it should be drawn. Option are to paint: * Only the outline
(Paint.Style.STROKE) * the filled part (Paint.Style.FILL) * both the outline and the filled part
(Paint.Style.STROKE_AND_FILL)
You can set the alpha channel of the Paint via the setAlpha() method.
Via Shaders you can define that the Paint is filled with more than one color.
180
Course Manual for Android App Development
Most standard views can save there state so that it can be persisted by the system. The Android system
calls the onSaveInstanceState() method and theonRestoreInstanceState(Parcable) to save and restore the
view state.
The convention is to extend View.BasedSavedState as a static inner class in the view for persisting the
data.
Android searches based on the ID of the view in the layout for the view and pass a Bundle to the view
which the view can use to restore its state.
You should save and restore the user interface state as the user left it, e.g. the scroll position or the active
selection.
PRACTICE:
https://commonsware.com/Android/Android-4.7-CC.pdf
REFERENCE LINK:
https://developer.android.com/guide/topics/ui/custom-components.html
181
Course Manual for Android App Development
CHAPTER OVERVIEW:
Advanced Android Development is an instructor-led course created by the Google Developers Training
team. Developers taking the course learn advanced Android programming concepts and build a variety of
apps.
OBJECTIVES:
LEARNING OUTCOME:
• Alternative layouts
• Avoid hard-coded layout sizes
• Use the smallest width qualifier
• Meaningful motions
• - Espresso (Android Testing Support Library)
182
Course Manual for Android App Development
CORE DISCUSSION:
• Fundamental technology
When your UI changes in response to user action, you should animate the layout transitions. These
animations give users feedback on their actions and help keep them oriented to the UI.
Android includes the transitions framework, which enables you to easily animate changes between two
view hierarchies. The framework animates the views at runtime by changing some of their property
values over time. The framework includes built-in animations for common effects and lets you create
custom animations and transition lifecycle callbacks.
Animations can add visual cues that notify users about what's going on in your app. They are especially
useful when the UI changes state, such as when new content loads or new actions become available.
Animations also add a polished look to your app, which gives it a higher quality look and feel.
1. Property Animations — They are used to alter property of objects (Views or non view objects). We
specify certain properties(like translateX, TextScaleX) of the objects to change. Various
characteristics of animation which can be manipulated are animation duration, whether to reverse it
and for how many times we want to repeat the animation etc. They were introduced in Android 3.0
(API level 11).
2. View Animations — They are used to do simple animations like changing size, position, rotation,
control transparency. They are easy to build and are very fast but have their own constraints. For
eg — Their state changes but their property does not change. View animations will be covered in part
2.
The superclass of the animation API is the Animator class. The ObjectAnimator class can be used to
modify attributes of an object.
You can also add an AnimatorListener class to your Animator class. This listener is called in the different
phases of the animation. You can use this listener to perform actions before or after a certain animation,
e.g. add or remove a View from a ViewGroup.
The animate() method on a View object returns an ViewPropertyAnimator object for the view. It provides
a fluent API to typical animations which can be performed on views.
myView.animate().translationX(400);
183
Course Manual for Android App Development
myView.animate().translationX(400).withLayer();
You can also register action, which are executed before the start or after the end of the animation.
// StartAction
myView.animate().translationX(100).withStartAction(newRunnable(){
publicvoid run(){
viewer.setTranslationX(100-myView.getWidth());
// do something
}
});
// EndAction
myView.animate().alpha(0).withEndAction(newRunnable(){
publicvoid run(){
// rRemove the view from the parent layout
parent.removeView(myView);
}
});
Gradle is an open source build automation system. Gradle can automate the building, testing,
publishing, deployment and more of software packages or other types of projects such as generated
static websites, generated documentation and anything else
Gradle is an automated build toolkit that allows the way in which projects are built to be configured and
managed through a set of build configuration files. This includes defining how aproject is to be built,
what dependencies need to be fulfilled for the project to build successfully and what the end result (or
results) of the build process should be.
The strength of Gradle lies in the flexibility that it provides to the developer. The Gradle system is a self-
contained, command-line based environment that can be integrated into other environments through the
use of plug-ins. In the case of Android Studio, Gradle integration is provided through the appropriately
named Android Studio Plug-in.
184
Course Manual for Android App Development
Although the Android Studio Plug-in allows Gradle tasks to be initiated and managed from within
Android Studio, the Gradle command-line wrapper can still be used to build Android Studio based
projects, including on systems on which Android Studio is not installed.
The configuration rules to build a project are declared in Gradle build files and scripts based on the
Groovy programming language.
Gradle brings a number of powerful features to building Android application projects. Some of the key
features are as follows:
Sensible Defaults, Dependencies, Build Variants, Manifest Entries, APK Signing, ProGuard Support.
A completed Android Studio project contains everything needed to build an Android application and
consists of modules, libraries, manifest files and Gradle build files. Each project contains one top-level
Gradle build file. This file is listed as build.gradle (Project: <project name>) and can be found in the
project tool window as highlighted in below figure:
185
Course Manual for Android App Development
Espresso is a testing framework for Android to make it easy to write reliable user interface tests.
The framework also ensures that your activity is started before the tests run. It also let the test wait until all
observed background activities have finished.
It is intended to test a single application but can also be used to test across applications. If used for testing
outside your application, you can only perform black box testing, as you cannot access the classes outside
of your application.
To use Espresso for your tests, add the following dependency to the Gradle build file of your app.
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
// Espresso support
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
186
Course Manual for Android App Development
})
android {
compileSdkVersion 22
buildToolsVersion '22.0.1'
defaultConfig {
applicationId "com.example.android.testing.espresso.BasicSample"
minSdkVersion 10
targetSdkVersion 22
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
packagingOptions {
exclude 'LICENSE.txt'
}
lintOptions {
abortOnError false
}
}
dependencies {
// as before.......
}
Flexible layouts
By default, Android resizes your app layout to fit the current screen. To ensure your layout resizes well
for even small variations in screen size, you need to implement your layout with flexibility in mind. The
core principle you must follow is to avoid hard-coding the position and size of your UI components.
Instead, allow view sizes to stretch and specify view positions relative to the parent view or other sibling
views so your intended order and relative sizes remain the same as the layout grows.
187
Course Manual for Android App Development
Alternative layouts
A flexible layout is very important, but you should also design different layouts that optimize the user
experience for the available space on different devices such as phones and tablets. So Android allows you
to provide alternative layout files that the system applies at runtime based on the current device's screen
size.
Android devices come in all shapes and sizes, so your app's layout needs to be flexible. That is, instead of
defining your layout with rigid dimensions that assume a certain screen size and aspect ratio, your layout
should gracefully respond to different screen sizes and orientations.
By supporting as many screens as possible, your app can be made available to the greatest number of
users with different devices, using a single APK. Additionally, making your app flexible for different
screen sizes ensures that your app can handle window configuration changes on the device, such as when
the user enables multi-window mode.
This page shows you how to support different screen sizes with the following techniques:
• Use view dimensions that allow the layout to resize
• Create alternative UI layouts according to the screen configuration
• Provide bitmaps that can stretch with the views
188
Course Manual for Android App Development
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/lorem_ipsum"/>
The smallest width qualifier specifies the smallest of the screen's two sides, regardless of the device's
current orientation, so it's a simple way to specify the overall screen size available for your layout.
Here's how other smallest width values correspond to typical screen sizes:
• 320dp: a typical phone screen (240x320 ldpi, 320x480 mdpi, 480x800 hdpi, etc).
• 480dp: a large phone screen ~5" (480x800 mdpi).
• 600dp: a 7” tablet (600x1024 mdpi).
• 720dp: a 10” tablet (720x1280 mdpi, 800x1280 mdpi, etc).
•
189
Course Manual for Android App Development
•
• res/drawable-mdpi/my_icon.png // bitmap for medium density
• res/drawable-hdpi/my_icon.png // bitmap for high density
• res/drawable-xhdpi/my_icon.png // bitmap for extra high density
1. Flexible layouts
PRACTICE:
https://commonsware.com/Android/Android-4.7-CC.pdf
REFERENCE LINK:
http://www.techotopia.com/index.php/An_Overview_of_Gradle_in_Android_Studio
https://developers.google.com/training/courses/android-advanced
190
Course Manual for Android App Development
CHAPTER OVERVIEW:
Whether you're new to programming or an experienced developer, we have a range of courses to teach
you Android app development, from your first app to advanced topics such as localization, media,
advanced graphics, and performance.
OBJECTIVES:
LEARNING OUTCOME:
CORE DISCUSSION:
• Historical approach :
Android software development is the process by which new applications are created for devices running
the Android operating system. Officially, apps can be written using Java, C++ or Kotlin using the
Android software development kit (SDK). Third party tools, development environments and language
support have also continued to evolve and expand since the initial SDK was released in 2008.
• Fundamental technology
Android Studio : Android Studio is the officialintegrated development environment (IDE) for Google's
Androidoperating system, built on JetBrains' IntelliJ IDEA software and designed specifically for
Android development. It is available for download on Windows, macOS and Linux based operating
systemsIt is a replacement for the Eclipse Android Development Tools (ADT) as primary IDE for native
Android application development.
191
Course Manual for Android App Development
Eclipse IDE: Eclipse IDE (integrated development environment). Included in the Android SDK
download, the Eclipse IDE provides the “hands-on” controls you need for writing your app using Java,
the Android SDK and the Android ADT. Android ADT (Android Development.Apr 25, 2013
There are so many technologies, tools, platforms and languages available to contemporary software
developers and programmers, that it's certainly impossible to find someone in the industry who at the
same time: works on a single platform, speaks a single programming dialect and is worth enough their
salt to be paid for their bacon, coffee and beers. The world is harsh; the race is tough. Starting with
Android doesn't mean to abandon any previous source of income, joy, enlightenment or whatever.
192
Course Manual for Android App Development
Google’s developer program for its Google Play app store, previously called the Android App Market,
has only a few simple requirements for you to register and start testing and selling your apps.
Requirements don’t include any proof of prior coding experience or existing apps, because Google offers
some app testing and does not have strict governance for app approval.
Publishing is the general process that makes your Android applications available to users. When you
publish an Android application you perform two main tasks:
193
Course Manual for Android App Development
Usually, you release your application through an application marketplace, such as Google Play. However,
you can also release applications by sending them directly to users or by letting users download them
from your own website.
The publishing process is typically performed after you finish testing your application in a debug
environment. Also, as a best practice, your application should meet all of your release criteria for
functionality, performance, and stability before you begin the publishing process.
Preparing your application for release is a multi-step process that involves the following tasks:
• Configuring your application for release.
At a minimum you need to remove Log calls and remove the android:debuggable attribute from your
manifest file. You should also provide values for
the android:versionCode and android:versionName attributes, which are located in
the <manifest> element. You may also have to configure several other settings to meet Google Play
requirements or accomodate whatever method you're using to release your application.
If you are using Gradle build files, you can use the release build type to set your build settings for the
published version of your app.
• Building and signing a release version of your application.
You can use the Gradle build files with the release build type to build and sign a release version of
your application. See Building and Running from Android Studio.
• Testing the release version of your application.
Before you distribute your application, you should thoroughly test the release version on at least one
target handset device and one target tablet device.
• Updating application resources for release.
You need to be sure that all application resources such as multimedia files and graphics are updated
and included with your application or staged on the proper production servers.
• Preparing remote servers and services that your application depends on.
If your application depends on external servers or services, you need to be sure they are secure and
production ready.
You may have to perform several other tasks as part of the preparation process. For example, you will
need to get a private key for signing your application. You will also need to create an icon for your
application, and you may want to prepare an End User License Agreement (EULA) to protect your
person, organization, and intellectual property.
When you are finished preparing your application for release you will have a signed .apk file that you can
distribute to users.
To learn how to prepare your application for release, see Preparing for Release in the Dev Guide. This
topic provides step-by-step instructions for configuring and building a release version of your application.
194
Course Manual for Android App Development
You can release your Android applications several ways. Usually, you release applications through an
application marketplace such as Google Play, but you can also release applications on your own website
or by sending an application directly to a user.
You've just written a great Android app and you're ready to make some money from
it. The most common route is probably to pay $25 to get it listed on Google Play. However, there are
many alternatives to Google Play, each with their own audience that can drive more downloads.
195
Course Manual for Android App Development
Some of these app stores are catered to a smaller audience while others are more localized. Most of them
don't charge you for listing your app on their store. It can therefore pay off to publish your app in several
app stores.
https://commonsware.com/Android/Android-4.7-CC.pdf
REFERENCE LINK:
https://developers.google.com/training/android/
196
Course Manual for Android App Development
2 Completed projects have to be completed and delivered for every student (First one is a group
project and the last one is the individual project) (26 hrs.)
In this stage of training we will make few real life project that will give the student a hands on experience
to work with real life requirement of projects following every steps of software development life cycle.
Projects in the phase of training will contain mail portion of this training and their implementation.
Projects will at least cover the following training modules and implementation of them:
• MVC
• Auto Layout
• Concept of JAVA
• Storyboards (Scene, segue, Navigation Controller)
• TableView & CollectionView
• Local Storage (SQLite, Core Data)
• Networking (XML. JSON Parsing)
• Animation, Location Framework (MapKit)
197