0% found this document useful (0 votes)
16 views

MAD altra Lecture Notes

The document outlines the planning and structure for lecture notes submission in the Computer Engineering department, specifically for the Mobile App Development subject. It includes a detailed syllabus covering topics such as OOP concepts, software engineering, Android OS, UI components, database connectivity, and advanced application development. Additionally, it describes the Software Development Life Cycle (SDLC) and the importance of Data Flow Diagrams (DFDs) in representing information flows within a system.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

MAD altra Lecture Notes

The document outlines the planning and structure for lecture notes submission in the Computer Engineering department, specifically for the Mobile App Development subject. It includes a detailed syllabus covering topics such as OOP concepts, software engineering, Android OS, UI components, database connectivity, and advanced application development. Additionally, it describes the Software Development Life Cycle (SDLC) and the importance of Data Flow Diagrams (DFDs) in representing information flows within a system.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 90

Planning for lecture notes submission in the library

SRPEC Department : Computer


Engineering

Cover page of Lecture Notes


Faculty Name: Amanat Ansari

Branch:Computer Engineering Semester:7th Name of Subject:Mobile App. Development

Chapter/ Chapter name (as per GTU syllabus)


Unit No.

Topics: ( as per the lesson planning)

1. Basic Knowledge of OOPS concept and Core java

2. Fundamental

Software Engineering with SDLC, Flow chart, DFD, SQL database

3. Android OS

Android, Android System with Architecture, Android Architecture,


Development with Android – Platforms, Tools, Versions, Setup Android
Environment, Say Hello to Android Application, Building Blocks of Android
Application, Work with Activity, Activity Lifecycle, Intents Fragments,
Fragment Lifecycle

4. Android UI And Component using Fragments

Create Android UI, Working with Layout, Create Custom Layouts, Work with
UI Components and Events, Material Design Toolbar, Tab Layout, Recycler
View and Card View, Android Menus
5. Database Connectivity

Storage in Android, Shared Preferences, Shared Preferences Layout, Android


Requesting Permission at run time (Android 6.0), Work with SD Card and Files,
Database in Android, Realm-No SQL Database

6. Applicability to Industrial Projects

Web services and Parsing, JSON Parsing, Access web data with JSON, Connect
to Web Services, Using Async Task & Third Party Library : Retrofit

7. Advanced Application Development

Google Map, Location Service and GPS, Creating Google Map, Work with
Location, Location service with Location Manager, Find Current Location, Geo
coding ,
Graphics and Animation, Work with 2D Graphics, Bitmap, Animation, Frame
Animation, Tween Animation, View Animation, Multimedia in Android, Play
Audio Files, Play Video Files
Work in Background, Services, Notification Services, Broadcast Receiver
Introduction to Firebase with simple CRUID Operation

8. Development and Deployment Work with android system

Text to Speech, Camera, Taking Picture with Camera, Manage Bluetooth


Connection, Monitor and Manage Wi-Fi, Accelerometer Sensor & Gyroscope.
Delvik Debug Tool, Logcat, Emulator Control, Device Control, Work with ADB,
Connect Real Devices, Execute Application on Real Device, Publish your
Application
Unit -1 : Basic Knowledge of OOPS concept and Core java

Object-Oriented Programming or OOPs refers to languages that uses objects in programming.


Object-oriented programming aims to implement real-world entities like inheritance, hiding,
polymorphism etc in programming. The main aim of OOP is to bind together the data and the
functions that operate on them so that no other part of the code can access this data except that
function.
Let us do discuss pre-requisite by polishing concepts of methods declaration and passing. Starting off
with the method declaration, it consists of six components:
 Access Modifier: Defines access type of the method i.e. from where it can be accessed in your
application. In Java, there 4 type of the access specifiers.
 public: accessible in all class in your application.
 protected: accessible within the package in which it is defined and in
its subclass(es)(including subclasses declared outside the package)
 private: accessible only within the class in which it is defined.
 default (declared/defined without using any modifier): accessible within same class
and package within which its class is defined.
 The return type: The data type of the value returned by the method or void if does not return a
value.
 Method Name: the rules for field names apply to method names as well, but the convention is a
little different.
 Parameter list: Comma separated list of the input parameters are defined, preceded with their
data type, within the enclosed parenthesis. If there are no parameters, you must use empty
parentheses ().
 Exception list: The exceptions you expect by the method can throw, you can specify these
exception(s).
 Method body: it is enclosed between braces. The code you need to be executed to perform your
intended operations.
Message Passing: Objects communicate with one another by sending and receiving information to
each other. A message for an object is a request for execution of a procedure and therefore will invoke
a function in the receiving object that generates the desired results. Message passing involves
specifying the name of the object, the name of the function and the information to be sent.
Now with basic prerequisite to step learning 4 pillar of OOPS is as follows. Let us start with learning
about the different characteristics of an Object-Oriented Programming language
OOPs Concepts are as follows:
1. Class
2. Object
3. Method and method passing
4. Pillars of OOPS
 Abstraction
 Encapsulation
 Inheritance
 Polymorphism
 Compile-time polymorphism
 Run-time polymorphism

A class is a user defined blueprint or prototype from which objects are created. It represents the set of
properties or methods that are common to all objects of one type. In general, class declarations can
include these components, in order:
1. Modifiers: A class can be public or has default access (Refer this for details).
2. Class name: The name should begin with a initial letter (capitalized by convention).
3. Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the keyword
extends. A class can only extend (subclass) one parent.
4. Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any,
preceded by the keyword implements. A class can implement more than one interface.
5. Body: The class body surrounded by braces, { }.
Object is a basic unit of Object Oriented Programming and represents the real life entities. A typical
Java program creates many objects, which as you know, interact by invoking methods. An object
consists of:
1. State : It is represented by attributes of an object. It also reflects the properties of an object.
2. Behavior : It is represented by methods of an object. It also reflects the response of an object with
other objects.
3. Identity : It gives a unique name to an object and enables one object to interact with other objects.
4. Method: A method is a collection of statements that perform some specific task and return result
to the caller. A method can perform some specific task without returning anything. Methods allow
us to reuse the code without retyping the code. In Java, every method must be part of some class
which is different from languages like C, C++ and Python.
Methods are time savers and help us to reuse the code without retyping the code.
Let us now discuss 4 pillars of OOPS:
Pillar 1: Abstraction
Data Abstraction is the property by virtue of which only the essential details are displayed to the
user.The trivial or the non-essentials units are not displayed to the user. Ex: A car is viewed as a car
rather than its individual components.
Data Abstraction may also be defined as the process of identifying only the required characteristics of
an object ignoring the irrelevant details. The properties and behaviours of an object differentiate it
from other objects of similar type and also help in classifying/grouping the objects.
Consider a real-life example of a man driving a car. The man only knows that pressing the
accelerators will increase the speed of car or applying brakes will stop the car but he does not know
about how on pressing the accelerator the speed is actually increasing, he does not know about the
inner mechanism of the car or the implementation of accelerator, brakes etc in the car. This is what
abstraction is.
In java, abstraction is achieved by interfaces and abstract classes. We can achieve 100% abstraction
using interfaces.
Pillar 2: Encapsulation
It is defined as the wrapping up of data under a single unit. It is the mechanism that binds together
code and the data it manipulates. Another way to think about encapsulation is, it is a protective shield
that prevents the data from being accessed by the code outside this shield.
 Technically in encapsulation, the variables or data of a class is hidden from any other class and
can be accessed only through any member function of own class in which they are declared.
 As in encapsulation, the data in a class is hidden from other classes, so it is also known as data-
hiding.
 Encapsulation can be achieved by Declaring all the variables in the class as private and writing
public methods in the class to set and get the values of variables.
Pillar 3: Inheritence
Inheritance is an important pillar of OOP(Object Oriented Programming). It is the mechanism in java
by which one class is allow to inherit the features(fields and methods) of another class.
Let us discuss some of frequent used important terminologies:
 Super Class: The class whose features are inherited is known as superclass(or a base class or a
parent class).
 Sub Class: The class that inherits the other class is known as subclass(or a derived class, extended
class, or child class). The subclass can add its own fields and methods in addition to the superclass
fields and methods.
 Reusability: Inheritance supports the concept of ―reusability‖, i.e. when we want to create a new
class and there is already a class that includes some of the code that we want, we can derive our
new class from the existing class. By doing this, we are reusing the fields and methods of the
existing class.
Pillar 4: Polymorphism
It refers to the ability of OOPs programming languages to differentiate between entities with the same
name efficiently. This is done by Java with the help of the signature and declaration of these entities.
Note:
Polymorphism in Java are mainly of 2 types:
1. Overloading
2. Overriding
Unit-2: Software Engineering with SDLC, Flow chart, DFD, SQL database

Software Development Life Cycle (SDLC)

A software life cycle model (also termed process model) is a pictorial and diagrammatic representation
of the software life cycle. A life cycle model represents all the methods required to make a software
product transit through its life cycle stages. It also captures the structure in which these methods are to
be undertaken.

In other words, a life cycle model maps the various activities performed on a software product from its
inception to retirement. Different life cycle models may plan the necessary development activities to
phases in different ways. Thus, no element which life cycle model is followed, the essential activities
are contained in all life cycle models though the action may be carried out in distinct orders in different
life cycle models. During any life cycle stage, more than one activity may also be carried out.

Need of SDLC

The development team must determine a suitable life cycle model for a particular plan and then observe
to it.

Without using an exact life cycle model, the development of a software product would not be in a
systematic and disciplined manner. When a team is developing a software product, there must be a clear
understanding among team representative about when and what to do. Otherwise, it would point to
chaos and project failure. This problem can be defined by using an example. Suppose a software
development issue is divided into various parts and the parts are assigned to the team members. From
then on, suppose the team representative is allowed the freedom to develop the roles assigned to them in
whatever way they like. It is possible that one representative might start writing the code for his part,
another might choose to prepare the test documents first, and some other engineer might begin with the
design phase of the roles assigned to him. This would be one of the perfect methods for project failure.

A software life cycle model describes entry and exit criteria for each phase. A phase can begin only if its
stage-entry criteria have been fulfilled. So without a software life cycle model, the entry and exit criteria
for a stage cannot be recognized. Without software life cycle models, it becomes tough for software
project managers to monitor the progress of the project.
SDLC Cycle

SDLC Cycle represents the process of developing software. SDLC framework includes the following
steps:

The stages of SDLC are as follows:

Stage1: Planning and requirement analysis

Requirement Analysis is the most important and necessary stage in SDLC.

The senior members of the team perform it with inputs from all the stakeholders and domain experts or
SMEs in the industry.

Planning for the quality assurance requirements and identifications of the risks associated with the
projects is also done at this stage.

Business analyst and Project organizer set up a meeting with the client to gather all the data like what
the customer wants to build, who will be the end user, what is the objective of the product. Before
creating a product, a core understanding or knowledge of the product is very necessary.

For Example, A client wants to have an application which concerns money transactions. In this
method, the requirement has to be precise like what kind of operations will be done, how it will be done,
in which currency it will be done, etc.
Once the required function is done, an analysis is complete with auditing the feasibility of the growth of
a product. In case of any ambiguity, a signal is set up for further discussion.

Once the requirement is understood, the SRS (Software Requirement Specification) document is
created. The developers should thoroughly follow this document and also should be reviewed by the
customer for future reference.

Stage2: Defining Requirements

Once the requirement analysis is done, the next stage is to certainly represent and document the software
requirements and get them accepted from the project stakeholders.

This is accomplished through "SRS"- Software Requirement Specification document which contains all
the product requirements to be constructed and developed during the project life cycle.

Stage3: Designing the Software

The next phase is about to bring down all the knowledge of requirements, analysis, and design of the
software project. This phase is the product of the last two, like inputs from the customer and
requirement gathering.

Stage4: Developing the project

In this phase of SDLC, the actual development begins, and the programming is built. The
implementation of design begins concerning writing code. Developers have to follow the coding
guidelines described by their management and programming tools like compilers, interpreters,
debuggers, etc. are used to develop and implement the code.

Stage5: Testing

After the code is generated, it is tested against the requirements to make sure that the products are
solving the needs addressed and gathered during the requirements stage.

During this stage, unit testing, integration testing, system testing, acceptance testing are done.

Stage6: Deployment

Once the software is certified, and no bugs or errors are stated, then it is deployed.

Then based on the assessment, the software may be released as it is or with suggested enhancement in
the object segment.
After the software is deployed, then its maintenance begins.

Stage7: Maintenance

Once when the client starts using the developed systems, then the real issues come up and requirements
to be solved from time to time.

This procedure where the care is taken for the developed product is known as maintenance.

Data Flow Diagrams

A Data Flow Diagram (DFD) is a traditional visual representation of the information flows within a
system. A neat and clear DFD can depict the right amount of the system requirement graphically. It can
be manual, automated, or a combination of both.

It shows how data enters and leaves the system, what changes the information, and where data is stored.

The objective of a DFD is to show the scope and boundaries of a system as a whole. It may be used as a
communication tool between a system analyst and any person who plays a part in the order that acts as a
starting point for redesigning a system. The DFD is also called as a data flow graph or bubble chart.

The following observations about DFDs are essential:

1. All names should be unique. This makes it easier to refer to elements in the DFD.
2. Remember that DFD is not a flow chart. Arrows is a flow chart that represents the order of
events; arrows in DFD represents flowing data. A DFD does not involve any order of events.
3. Suppress logical decisions. If we ever have the urge to draw a diamond-shaped box in a DFD,
suppress that urge! A diamond-shaped box is used in flow charts to represents decision points
with multiple exists paths of which the only one is taken. This implies an ordering of events,
which makes no sense in a DFD.
4. Do not become bogged down with details. Defer error conditions and error handling until the
end of the analysis.

Standard symbols for DFDs are derived from the electric circuit diagram analysis and are shown in fig:
Circle: A circle (bubble) shows a process that transforms data inputs into data outputs.

Data Flow: A curved line shows the flow of data into or out of a process or data store.

Data Store: A set of parallel lines shows a place for the collection of data items. A data store indicates
that the data is stored which can be used at a later stage or by the other processes in a different order.
The data store can have an element or group of elements.

Source or Sink: Source or Sink is an external entity and acts as a source of system inputs or sink of
system outputs.

Levels in Data Flow Diagrams (DFD)

The DFD may be used to perform a system or software at any level of abstraction. Infact, DFDs may be
partitioned into levels that represent increasing information flow and functional detail. Levels in DFD
are numbered 0, 1, 2 or beyond. Here, we will see primarily three levels in the data flow diagram, which
are: 0-level DFD, 1-level DFD, and 2-level DFD.

0-level DFDM

It is also known as fundamental system model, or context diagram represents the entire software
requirement as a single bubble with input and output data denoted by incoming and outgoing arrows.
Then the system is decomposed and described as a DFD with multiple bubbles. Parts of the system
represented by each of these bubbles are then decomposed and documented as more and more detailed
DFDs. This process may be repeated at as many levels as necessary until the program at hand is well
understood. It is essential to preserve the number of inputs and outputs between levels, this concept is
called leveling by DeMacro. Thus, if bubble "A" has two inputs x1 and x2 and one output y, then the
expanded DFD, that represents "A" should have exactly two external inputs and one external output as
shown in fig:

The Level-0 DFD, also called context diagram of the result management system is shown in fig. As the
bubbles are decomposed into less and less abstract bubbles, the corresponding data flow may also be
needed to be decomposed.

1-level DFD

In 1-level DFD, a context diagram is decomposed into multiple bubbles/processes. In this level, we
highlight the main objectives of the system and breakdown the high-level process of 0-level DFD into
subprocesses.
2-Level DFD

2-level DFD goes one process deeper into parts of 1-level DFD. It can be used to project or record the
specific/necessary detail about the system's functioning.
What is SQLite database? Write code for adding, updating and removing data from SQLite
database.

SQLite is a opensource SQL database that stores data to a text file on a device.
Android comes in with built in SQLite database implementation.

SQLite supports all the relational database features. In order to access this database, you don't
need to establish any kind of connections for it like JDBC,ODBC, etc.
The main package is android.database.sqlite that contains the classes to manage your own
databases.

Database - Creation

In order to create a database you just need to call this method open OrCreateDatabase with your
database name and mode as a parameter. It returns an instance of SQLite database which you have
to receive in your own object. Its syntax is given below:

SQLiteDatabase mydatabase = openOrCreateDatabase("your database


name",MODE_PRIVATE,null);

Put Information into a Database

Insert data into the database by passing a ContentValues object to the insert()method:
// Gets the data repository in write mode
SQLiteDatabase db = mDbHelper.getWritableDatabase();

// Create a new map of values, where column names are the keys
ContentValues values = new ContentValues();
values.put(FeedEntry.COLUMN_NAME_TITLE, title);
values.put(FeedEntry.COLUMN_NAME_SUBTITLE, subtitle);

// Insert the new row, returning the primary key value of the new row
long newRowId = db.insert(TABLE_NAME, null, values);

The first argument for insert() is simply the table name.


The second argument tells the framework what to do in the event that the ContentValues is
empty (i.e., you did not put any values). If you specify the name of a column, the framework
inserts a row and sets the value of that column to null. If you specify null, like in this code
sample, the framework does not insert a row when there are no values.

Update Rows

public void updateRecord(ContactModel contact) { database =


this.getReadableDatabase(); ContentValues contentValues =
new ContentValues();
contentValues.put(COLUMN_FIRST_NAME, contact.getFirstName());
contentValues.put(COLUMN_LAST_NAME, contact.getLastName());
database.update(TABLE_NAME, contentValues, COLUMN_ID + " = ?",
new String[]{contact.getID()});
database.close();
}

public int update (String table, ContentValues values, String whereClause,


String[] whereArgs)

update()is the convenient method for updating rows in the database.


Returns:
The number of rows affected.
Delete Records

public void deleteRecord(ContactModel contact) { database =


this.getReadableDatabase();
database.delete(TABLE_NAME, COLUMN_ID + " = ?",
new String[]{contact.getID()});
database.close();
}

public int delete (String table, String whereClause, String[] whereArgs) database.delete() is
convenient method for deleting rows in the database
Returns
The number of rows affected if a whereClause is passed in, 0 otherwise. To remove all rows
and get a count pass 1 as the whereClause.
Unit-3: Android OS

Explain Android Architecture with diagram

Android is an open source, Linux-based software stack created for a wide array of devices and
form factors.
The major components of the Android platform are:

The Linux Kernel


The foundation of the Android platform is the Linux kernel.
For example, the Android Runtime (ART) relies on the Linux kernel for underlying
functionalities such as threading and low-level memory management.
Using a Linux kernel allows Android to take advantage of key security features and allows
device manufacturers to develop hardware drivers for a well-known kernel.

Hardware Abstraction Layer (HAL)


The hardware abstraction layer (HAL) provides standard interfaces that expose device hardware
capabilities to the higher-level Java API framework.
The HAL consists of multiple library modules, each of which implements an interface for a
specific type of hardware component, such as the camera or bluetooth module.
When a framework API makes a call to access device hardware, the Android system loads the
library module for that hardware component.

Android Runtime
For devices running Android version 5.0 (API level 21) or higher, each app runs in its own
process and with its own instance of the Android Runtime (ART).
ART is written to run multiple virtual machines on low-memory devices by executing DEX
files, a bytecode format designed specially for Android that's optimized for minimal memory
footprint.
Build toolchains, such as Jack, compile Java sources into DEX bytecode, which can run on the
Android platform.
Some of the major features of ART include the following:
o Ahead-of-time (AOT) and just-in-time (JIT) compilation
o Optimized garbage collection (GC)
o Better debugging support

Android
Architecture
Native C/C++ Libraries
Many core Android system components and services, such as ART and HAL, are built from
native code that require native libraries written in C and C++.
The Android platform provides Java framework APIs to expose the functionality of some of these
native libraries to apps.
For example, you can access OpenGL ES through the Android framework's Java OpenGL
API to add support for drawing and manipulating 2D and 3D graphics in your app.
If you are developing an app that requires C or C++ code, you can use the Android NDK to
access some of these native platform libraries directly from your native code.

Java API Framework


The entire feature-set of the Android OS is available to you through APIs written in the Java
language.
These APIs form the building blocks you need to create Android apps by simplifying the
reuse of core, modular system components and services, which include the following:
o A rich and extensible View System you can use to build an app’s UI, including lists, grids,
text boxes, buttons, and even an embeddable web browser
o A Resource Manager, providing access to non-code resources such as localized strings,
graphics, and layout files
o A Notification Manager that enables all apps to display custom alerts in the status bar
o An Activity Manager that manages the lifecycle of apps and provides a common navigation
back stack
o Content Providers that enable apps to access data from other apps, such as the Contacts app,
or to share their own data

System Apps
Android comes with a set of core apps for email, SMS messaging, calendars, internet browsing,
contacts, and more.
Apps included with the platform have no special status among the apps the user chooses to
install.
So a third-party app can become the user's default web browser, SMS messenger, or even the
default keyboard.
The system apps function both as apps for users and to provide key capabilities that
developers can access from their own app.
E.g., if your app would like to deliver an SMS message, you don't need to build that
functionality yourself - you can instead invoke whichever SMS app is already installed to
deliver a message to the recipient you specify.
What is view? Create a simple Grid View application.

A View occupies a rectangular area on the screen and is responsible for drawing and event
handling.
View is the base class for widgets, which are used to create interactive UI components (buttons,
text fields, etc.).
The ViewGroupsubclass is the base class for layouts, which are invisible containers that hold
other Views and define their layout properties.
All of the views in a window are arranged in a single tree.
You can add views either from code or by specifying a tree of views in one or more XML
layout files.
There are many specialized subclasses of views that act as controls or are capable of
displaying text, images, or other content.

Grid View

Grid View is a ViewGroupthat displays items in a two-dimensional, scrollable grid.


The grid items are automatically inserted to the layout using a ListAdapter.
For an introduction to how you can dynamically insert views using an adapter, read Building
Layouts with an Adapter.

Following steps will create a grid of image thumbnails.


When an item is selected, a toast message will display the position of the image.

Steps to create GridView are as follows:

Start a new project named HelloGridView.


Find some photos you'd like to use. Save the image files into the project's res/drawable/
directory.
Open the res/layout/main.xml file and insert the following:

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


<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnWidth="90dp"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth" android:gravity="center"
/>

This GridView will fill the entire screen.

Open HelloGridView.java and insert the following code for the onCreate()method:

public void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
setContentView(R.layout.main);

GridView gridview = (GridView) findViewById(R.id.gridview); gridview.setAdapter(new


ImageAdapter(this));

gridview.setOnItemClickListener(newOnItemClickListener(){ public void


onItemClick(AdapterView<?> parent, View v,
int position, long id) { Toast.makeText(HelloGridView.this, "" +
position,
Toast.LENGTH_SHORT).show();
}
});
}

After the main.xml layout is set for the content view, the GridView is captured from the layout with
findViewById(int). The setAdapter() method then sets a custom adapter (ImageAdapter) as the
source for all items to be displayed in the grid.
To do something when an item in the grid is clicked, the setOnItemClickListener() method is
passed a new AdapterView.OnItemClickListener. This anonymous instance defines the
onItemClick() callback method to show a Toast that displays the index position (zero-based) of
the selected item (in a real world scenario, the position could be used to get the full sized image
for some other task).

Create a new class called ImageAdapter that extends BaseAdapter:

public class ImageAdapter extends BaseAdapter { private


Context mContext;

public ImageAdapter(Context c){


mContext = c;
}

public int getCount() { return


mThumbIds.length;
}

public Object getItem(int position){ return null;


}

public long getItemId(int position){ return 0;


}

// create a new ImageView for each item referenced by the Adapter


public View getView(int position, View convertView, ViewGroup parent) { ImageView
imageView;
if (convertView == null) {
// if it's not recycled, initialize some attributes imageView = new
ImageView(mContext);
imageView.setLayoutParams(newGridView.LayoutParams(85,85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {

imageView = (ImageView) convertView;


}
imageView.setImageResource(mThumbIds[position]); return
imageView;
}

// references to our images


private Integer[] mThumbIds = { R.drawable.sample_2,
R.drawable.sample_3, R.drawable.sample_4,
R.drawable.sample_5, R.drawable.sample_6,
R.drawable.sample_7, R.drawable.sample_0,
R.drawable.sample_1, R.drawable.sample_2,
R.drawable.sample_3, R.drawable.sample_4,
R.drawable.sample_5, R.drawable.sample_6,
R.drawable.sample_7, R.drawable.sample_0,
R.drawable.sample_1, R.drawable.sample_2,
R.drawable.sample_3, R.drawable.sample_4,
R.drawable.sample_5, R.drawable.sample_6,
R.drawable.sample_7
};
}

First, this implements some required methods inherited from BaseAdapter.


getItem(int) should return the actual object at the specified position in the adapter.
getItemId(int)should return the row id of the item, but it's not needed here.

The first method necessary is getView(). This method creates a new View for each image
added to the ImageAdapter.
When this is called, a View is passed in, which is normally a recycled object, so there's a check
to see if the object is null.
If it is null, an ImageView is instantiated and configured with desired properties for the image
presentation:
o setLayoutParams(ViewGroup.LayoutParams) sets the height and width for the View - this
ensures that, no matter the size of the drawable, each image is resized and cropped to fit in
these dimensions, as appropriate.
o setScaleType(ImageView.ScaleType) declares that images should be cropped toward the
center (if necessary).
o setPadding(int, int, int, int)defines the padding for all sides.
If the View passed to getView()is not null, then the local ImageView is initialized with the
recycled View object.
At the end of the getView()method, the position integer passed into the method is used to
select an image from the mThumbIds array, which is set as the image resource for the
ImageView.
All that's left is to define the mThumbIds array of drawable resources.
Run the application.

What is fragment and how we can create it in android application?

A Fragment represents a behavior or a portion of user interface in an Activity.


You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a
fragment in multiple activities.
You can think of a fragment as a modular section of an activity, which has its own lifecycle,
receives its own input events, and which you can add or remove while the activity is running.
A fragment must always be embedded in an activity and the fragment's lifecycle is directly
affected by the host activity's lifecycle.
However, while an activity is running (it is in the resumed lifecycle state), you can
manipulate each fragment independently, such as add or remove them.
When you perform such a fragment transaction, you can also add it to a back stack that's
managed by the activity— each back stack entry in the activity is a record of the fragment
transaction that occurred.
The back stack allows the user to reverse a fragment transaction (navigate backwards), by
pressing the Back button.

Adding a fragment to an activity

Usually, a fragment contributes a portion of UI to the host activity, which is embedded as a


part of the activity's overall view hierarchy.
There are two ways you can add a fragment to the activity layout:

Declare the fragment inside the activity's layout file.

In this case, you can specify layout properties for the fragment as if it were a view. For
example, here's the layout file for an activity with two fragments:

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment android:name="com.example.news.ArticleListFragment" android:id="@+id/list"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent"/>
<fragment android:name="com.example.news.ArticleReaderFragment"
android:id="@+id/viewer"
android:layout_weight="2"
android:layout_width="0dp"
android:layout_height="match_parent"/>
</LinearLayout>

The android:name attribute in the <fragment> specifies the Fragment class to instantiate in the
layout.
When the system creates this activity layout, it instantiates each fragment specified in the
layout and calls the onCreateView() method for each one, to retrieve each fragment's layout.
The system inserts the View returned by the fragment directly in place of the <fragment>
element.

Programmatically add the fragment to an existing ViewGroup

At any time while your activity is running, you can add fragments to your activity layout. You
simply need to specify a ViewGroup in which to place the fragment.

To make fragment transactions in your activity (such as add, remove, or replace a fragment),
you must use APIs from FragmentTransaction.
You can get an instance of FragmentTransaction from your Activity like this:

FragmentManager fragmentManager = getFragmentManager();


FragmentTransaction fragmentTransaction =fragmentManager.beginTransaction();

You can then add a fragment using the add() method, specifying the fragment to add and the
view in which to insert it. For example:

ExampleFragment fragment = new ExampleFragment();


fragmentTransaction.add(R.id.fragment_container, fragment); fragmentTransaction.commit();
The first argument passed to add() is the ViewGroup in which the fragment should be placed,
specified by resource ID, and the second parameter is the fragment to add.
Once you've made your changes with FragmentTransaction, you must call commit() for the
changes to take effect.

What is Listview. Write a java class to add any 10 items within Listview.

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


The list items are automatically inserted to the list using an Adapter that pulls content from a
source such as an array or database query and converts each item result into a view that's
placed into the list.

Example to list Planet names in List View:

Basically we create a ListView class and use TextView objects for each row. Each planet name is
rendered in a
TextView.

Main Layout File

Our ListView is defined in the main layout file (res/layout/main.xml) within a LinearLayout.

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/mainListView">
</ListView>
</LinearLayout>

The resource ID of the ListViewis mainListView, which we will use to get a reference to the
ListViewin our Activity class.

// Find the ListView resource.


mainListView = (ListView) findViewById( R.id.mainListView );

Row Layout File

Each row in the ListView will be a TextView. The TextView is defined in another file
(res/layout/simplerow.xml).
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/rowTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:textSize="16sp" >
</TextView>

Activity

Our main activity (SimpleListViewActivity) creates an ArrayAdapter, which holds the objects
to be displayed in the ListView.
The ArrayAdapter constructor is passed the resource ID of the TextView layout
file (R.layout.simplerow).
The ArrayAdapterwill use it to instantiate a TextViewfor each row.

We then set the ArrayAdapter as our ListView's adapter.

package com.example.android;

importjava.util.ArrayList; import
java.util.Arrays;
importandroid.app.Activity;
import android.os.Bundle;
importandroid.widget.ArrayAdapter;
import android.widget.ListView;
public class SimpleListViewActivity extends Activity { private
ListView mainListView ;
private ArrayAdapter<String> listAdapter ;

/** Called when the activity is first created. */ @Override


public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.main);

// Find the ListViewresource.


mainListView = (ListView) findViewById( R.id.mainListView );

// Create and populate a List of planet names.


String[] planets = new String[] { "Mercury", "Venus", "Earth", "Mars",
"Jupiter","Saturn","Uranus","Neptune"};
ArrayList<String> planetList = new ArrayList<String>();
planetList.addAll( Arrays.asList(planets) );

// Create ArrayAdapter using the planet list.


listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow,
planetList);

// Add more planets. If you passed a String[] instead of a List<String>


// into the ArrayAdapter constructor, you must not add more items.
// Otherwise an exception willoccur.
listAdapter.add( "Ceres" ); listAdapter.add( "Pluto"
); listAdapter.add( "Haumea" ); listAdapter.add(
"Makemake" ); listAdapter.add( "Eris" );

// Set the ArrayAdapter as the ListView's adapter.


mainListView.setAdapter( listAdapter );
}
}
Draw a diagram for activity life cycle and explain it.

To navigate transitions between stages of the activity lifecycle, the Activity class provides a core
set of six callbacks:
onCreate(), onStart(), onResume(), onPause(), onStop(), and onDestroy().
The system invokes each of these callbacks as an activity enters a new state.

As the user begins to leave the activity, the system calls methods to dismantle the activity.
In some cases, this dismantlement is only partial; the activity still resides in memory (such as
when the user switches to another app), and can still come back to the foreground.
If the user returns to that activity, the activity resumes from where the user left off.
The system’s likelihood of killing a given process—along with the activities in it—depends
on the state of the activity at the time.
Activity state and ejection from memory provides more information on the relationship
between state and vulnerability to ejection.
Depending on the complexity of your activity, you probably don't need to implement all the
lifecycle methods.

Lifecycle Methods

onCreate()

You must implement this callback, which fires when the system first creates the activity.
On activity creation, the activity enters the Created state.
In the onCreate()method, you perform basic application startup logic that should happen only
once for the entire life of the activity.
For example, your implementation of onCreate()might bind data to lists, initialize background
threads, and instantiate some class-scope variables.
This method receives the parameter savedInstanceState, which is a Bundle object containing
the activity's previously saved state.
If the activity has never existed before, the value of the Bundle object is null.

Your activity does not reside in the Created state. After the onCreate() method finishes execution,
the activity enters the Started state, and the system calls the onStart()and onResume()methods in
quick succession.

onStart()

When the activity enters the Started state, the system invokes this callback.
The onStart() call makes the activity visible to the user, as the app prepares for the activity to
enter the foreground and become interactive.
For example, this method is where the app initializes the code that maintains the UI.
The onStart()method completes very quickly and, as with the Created state, the activity does not
stay resident in the Started state.
Once this callback finishes, the activity enters the Resumed state, and the system invokes the
onResume()
method.
onResume()

When the activity enters the Resumed state, it comes to the foreground, and then the system
invokes the
onResume()callback.
This is the state in which the app interacts with the user.
The app stays in this state until something happens to take focus away from the app.
Such an event might be, for instance, receiving a phone call, the user’s navigating to another
activity, or the device screen’s turning off.
When an interruptive event occurs, the activity enters the Paused state, and the system invokes
the onPause()
callback.
If the activity returns to the Resumed state from the Paused state, the system once again calls
onResume()
method.
For this reason, you should implement onResume() to initialize components that you release
during
onPause().

onPause()

The system calls this method as the first indication that the user is leaving your activity (though
it does not always mean the activity is being destroyed).
Use the onPause() method to pause operations such animations and music playback that should
not continue while the Activity is in the Paused state, and that you expect to resume shortly.
You can use the onPause() method to release system resources, such as broadcast receivers,
handles to sensors (like GPS), or any resources that may affect battery life while your activity
is paused and the user does not need them.
onPause() execution is very brief, and does not necessarily afford enough time to perform save
operations.
For this reason, you should not use onPause()to save application or user data, make network
calls, or execute database transactions; such work may not complete before the method
completes.
Instead, you should perform heavy-load shutdown operations during onStop().
If the activity resumes, the system once again invokes the onResume()callback.
If the activity returns from the Paused state to the Resumed state, the system keeps the Activity
instance resident in memory, recalling that instance when it the system invokes onResume().
onStop()

When your activity is no longer visible to the user, it has entered the Stopped state, and the
system invokes the
onStop()callback.
This may occur, for example, when a newly launched activity covers the entire screen.
The system may also call onStop()when the activity has finished running, and is about to be
terminated.
In the onStop()method, the app should release almost all resources that aren't needed while
the user is not using it.
When your activity enters the Stopped state, the Activity object is kept resident in memory: It
maintains all state and member information, but is not attached to the window manager.
When the activity resumes, the activity recalls this information.
You don’t need to re-initialize components that were created during any of the callback methods
leading up to the Resumed state.
The system also keeps track of the current state for each View object in the layout, so if the user
entered text into an EditText widget, that content is retained so you don't need to save and
restore it.

onDestroy()

Called before the activity is destroyed.


This is the final call that the activity receives.
The system either invokes this callback because the activity is finishing due to someone's
calling finish(), or because the system is temporarily destroying the process containing the
activity to save space.
You can distinguish between these two scenarios with the isFinishing() method.
The system may also call this method when an orientation change occurs, and then
immediately call
onCreate()to recreate the process (and the components that it contains) in the new orientation.
The onDestroy() callback releases all resources that have not yet been released by earlier
callbacks such as
onStop().
What is Android Runtime? Also explain Android Virtual Device. OR What is virtual device and
SDK manager? Explain.

Android runtime (ART)

Android runtime (ART) is the managed runtime used by applications and some system services
on Android.
ART and its predecessor Dalvik were originally created specifically for the Android project.
ART as the runtime executes the Dalvik Executable format and Dex bytecode specification.
ART and Dalvik are compatible runtimes running Dex bytecode, so apps developed for
Dalvik should work when running with ART.

ART Features

Here are some of the major features implemented by ART.


Ahead-of-time (AOT) compilation - ART introduces ahead-of-time (AOT) compilation, which
can improve app performance. ART also has tighter install-time verification than Dalvik.
Improved garbage collection - ART improves garbage collection in several ways:
o One GC pause instead of two
o Parallelized processing during the remaining GC pause
o Lower total GC time
o Improved garbage collection ergonomics
o Compacting GC to reduce background memory usage and fragmentation
Development and debugging improvements
o Support for sampling profiler
o Support for more debugging features
o Improved diagnostic detail in exceptions and crash reports

Android Virtual Device (AVD)

An Android Virtual Device (AVD) definition lets you define the characteristics of an Android
phone, tablet, Android Wear, or Android TV device that you want to simulate in the Android
Emulator.
The AVD Manager helps you easily create and manage AVDs.
An AVD contains a hardware profile, system image, storage area, skin, and other properties.

Hardware profile
The hardware profile defines the characteristics of a device as shipped from the factory. The
AVD Manager comes preloaded with certain hardware profiles, such as Nexus phone devices,
and you can define and import hardware profiles as needed. You can override some of the
settings in your AVD, if needed.
System image
The AVD Manager helps you choose a system image for your AVD by providing
recommendations. It also lets you download system images, some with add-on libraries, like
Google APIs.
Storage area
The AVD has a dedicated storage area on your development machine. It stores the device user
data, such as installed apps and settings, as well as an emulated SD card. If needed, you can use
the AVD Manager to wipe user data, so the device has the same data as if it were new.
Skin
An emulator skin specifies the appearance of a device. The AVD Manager provides some
predefined skins. You can also define your own, or use skins provided by third parties.

AVD and app features


Just as with a real device, for apps to use certain features defined in an AVD, such as the
camera, it must have the corresponding <uses-feature> setting in the app manifest.

Android SDK Manager

The Android Development Toolkit (ADT) Bundle provides the Software Development Kit
(SDK) and the emulator system image from the latest platform.
However, you will need other platforms to test your apps on earlier versions of Android.
You can get components for each platform using the Android SDK Manager.
It is a set of development tools used to develop applications for Android platform.
Every time Google releases a new version of Android, a corresponding SDK is also released.
To be able to write programs with the latest features, developers must download and install
each version’s SDK for the particular phone.
The Android SDK includes the following:
o Required libraries
o Debugger
o An emulator
o Relevant documentation for the Android application program interfaces (APIs)
o Sample source code
o Tutorials for the Android OS
Explain the various types of Android Application. OR Explain types of android application. And
create any small application in android? Explain.

Mobile apps are basically little, self-contained programs, used to enhance existing
functionality, hopefully in a simple, more user-friendly way.
They all come with powerful web browsers, meaning you can do pretty much anything you
can do on a desktop computer in a phone’s browser. Normally, when people talk about apps
they are almost always referring to programs that run on mobile devices, such as Smartphones
or Tablet Computers.
Each app provides limited and isolated functionality such as game, calculator or mobile web
browsing. Although apps may have avoided multitasking because of the limited hardware
resources of the early mobile devices, their specificity is now part of their desirability because
they allow consumers to hand-pick what their device are able to do.
Different types of Apps:
1) Native App
2) Web App
3) Hybrid App
Native App

Native App has been developed for use on a particular platform or device.
A native mobile app is a Smartphone application that is coded in a specific programming
language, Java for Android operating systems.
Native mobile apps provide fast performance and a high degree of reliability.
They also have access to a phone’s various devices, such as its camera and address book.
In addition, users can use some apps without an Internet connection.
However, this type of app is expensive to develop because it is tied to one type of operating
system, forcing the company that creates the app to make duplicate versions that work on
other platforms.
A Native app can only be ―Native‖ to one type of mobile operating system.
Most video games are native mobile apps.

Web App

Web App stored on a remote server and delivered over the internet through a browser.
Web apps are not real apps; they are really websites that, in many ways, look and feel like
native applications.
They are run by a browser and typically written in HTML5.
Users first access them as they would access any web page: they navigate to a special URL
and then have the option of ―installing‖ them on their home screen by creating a bookmark to
that page.
In contrast, a mobile web app is software that uses technologies such as JavaScript or
HTML5 to provide interaction, navigation, or customization capabilities.
These programs run within a mobile device’s web browser.
This means that they’re delivered wholly on the fly, as needed, via the internet; they are not
separate programs that get stored on the user’s mobile device.
Web apps became really popular when HTML5 came around and people realized that they can
obtain native-like– functionality in the browser.

Hybrid App

This type of application has cross-platform compatibility but can still access a phone’s
hardware.
It is developed using platforms such as Sencha, PhoneGap and Mosync.
Hybrid Apps are like native apps, run on the device, and are written with web technologies
(HTML5, CSS and JavaScript).
Hybrid apps run inside a native container, and leverage the device’s browser engine to render
the HTML and process the JavaScript locally.
A web-to-native abstraction layer enables access to device capabilities that are not accessible
in Mobile Web applications, such as the accelerometer, camera and local storage.
Hybrid apps are also popular because they allow cross-platform development: that is, the
same HTML code components can be reused on different mobile operating systems, reducing
significantly the development costs.

Creating an Android Project

The steps below shows you how to create a new Android project with Android Studio:
1) In Android Studio, create a new project:
 If you don't have a project opened, in the Welcome to Android Studio window, click
Start a new Android Studio project.
 If you have a project opened, select File > New Project.

2) In the New Project screen, enter the following values:


Application Name: "My First App"

Company Domain: "example.com"

3) Click Next.

4) In the Target Android Devices screen, keep the default values and click Next.
The Minimum Required SDK is the earliest version of Android that your app supports, which
is indicated by the API level. To support as many devices as possible, you should set this to
the lowest version available that allows your app to provide its core feature set.

5) In the Add an Activity to Mobile screen, select Empty Activity and click Next.

6) In the Customize the Activity screen, keep the default values and click Finish.

After some processing, Android Studio opens and displays a "Hello World" app with default
files. Following files will be created after successful processing
app > java > com.example.myfirstapp > MainActivity.java
app > res > layout > activity_main.xml
app > manifests > AndroidManifest.xml
Gradle Scripts > build.gradle
What is the role of DVM in android? Explain it.

The Dalvik Virtual Machine (DVM) is an android virtual machine optimized for mobile
devices.
It optimizes the virtual machine for memory, battery life and performance.
The Dex compiler converts the class files into the .dex file that run on the Dalvik VM.
Multiple class files are converted into one dex file.

Role of DVM in
Android

The javac tool compiles the java source file into the class file.
The dx tool takes all the class files of your application and generates a single .dex file.
It is a platform-specific tool.
The Android Assets Packaging Tool (aapt) handles the packaging process.
Dalvik virtual machine uses register based architecture. With this architecture, Dalvik Virtual
Machine has few advantages over JAVA virtual machine such as:
● Dalvik uses its own 16 bit instruction set than java 8 bit stack instructions, which reduce the
dalvik instruction count and raised its interpreter speed.
● Dalvik use less space, which means an uncompressed .dex file is smaller in size(few bytes)
than compressed java archive file(.jar file).
Unit-4: Android UI And Component using Fragments

List out different types of layouts in android. Explain any two layouts.

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:
o 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.
o Instantiate layout elements at runtime. Your application can create View and ViewGroup
objects (and manipulate their properties) programmatically.

Common layouts in Android are:

1) Linear Layout
2) Relative Layout
3) Web View
4) Table Layout
5) Frame Layout

Linear Layout

LinearLayout is a view group that aligns all children in a single direction, vertically or
horizontally. You can specify the layout direction with the android:orientationattribute.
All children of a Linear Layout are stacked one after the other, so a vertical list will only have
one child per row, no matter how wide they are, and a horizontal list will only be one row
high (the height of the tallest child, plus padding).
A Linear Layout respects margins between children and the gravity (right, center, or left
alignment) of each child.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:orientation="vertical">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/to" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/subject" />
<EditText
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="top"
android:hint="@string/message" />
<Button
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="@string/send" />
</LinearLayout>

Relative Layout

Relative Layout is a view group that displays child views in relative positions.
The position of each view can be specified as relative to sibling elements (such as to the left-of
or below another view) or in positions relative to the parent Relative Layout area (such as
aligned to the bottom, left or center).
Relative Layout lets child views specify their position relative to the parent view or to each other
(specified by ID).
So you can align two elements by right border, or make one below another, centered in the
screen, centered left, and so on.
By default, all child views are drawn at the top-left of the layout, so you must define the
position of each view using the various layout properties available from
RelativeLayout.LayoutParams.

Some of the many layout properties available to views in a RelativeLayout include:


2) android:layout_alignParentTop
If "true", makes the top edge of this view match the top edge of the parent.
3) android:layout_centerVertical
If "true", centers this child vertically within its parent.

4) android:layout_below
Positions the top edge of this view below the view specified with a resource ID.

5) android:layout_toRightOf
Positions the left edge of this view to the right of the view specified with a resource ID.

Sample code illustrating Relative Layout is as follows:

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


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp">
<EditText
android:id="@+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/reminder" />
<Spinner
android:id="@+id/dates"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_below="@id/name"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="@+id/times"/>
<Spinner
android:id="@id/times" android:layout_width="96dp"
android:layout_height="wrap_content"
android:layout_below="@id/name"
android:layout_alignParentRight="true" />
<Button
android:layout_width="96dp"
android:layout_height="wrap_content"
android:layout_below="@id/times"
android:layout_alignParentRight="true"
android:text="@string/done" />

</RelativeLayout>

Frame Layout

Frame Layout is designed to block out an area on the screen to display a single item.
Generally, Frame Layout should be used to hold a single child view, because it can be
difficult to organize child views in a way that's scalable to different screen sizes without the
children overlapping each other.
You can, however, add multiple children to a Frame Layout and control their position within
the Frame Layout by assigning gravity to each child, using the android:layout_gravity
attribute.
Child views are drawn in a stack, with the most recently added child on top.
The size of the Frame Layout is the size of its largest child (plus padding), visible or not (if the
Frame Layout's parent permits). Sample code showing use of FrameLayout has been shown
below:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/framelayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center" android:foregroundGravity="fill"
android:foreground="#0f0"><!--foreground color for a FrameLayout-->

<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
>

<!-- Imageview will not be shown because of foreground color which is drawn over it-->

<ImageView
android:layout_width="200dp"
android:layout_height="200dp"

android:layout_marginBottom="10dp"
android:src="@mipmap/ic_launcher"
android:scaleType="centerCrop"
/>

<!--Textview will not be shown because of foreground color is drawn over it-->

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="AndroidSample"/>
</LinearLayout>

</FrameLayout>

Table Layout
A layout that arranges its children into rows and columns.
A Table Layout consists of a number of TableRow objects, each defining a row (actually, you
can have other children, which will be explained below).
Table Layout containers do not display border lines for their rows, columns, or cells.
Each row has zero or more cells; each cell can hold one View object.
The table has as many columns as the row with the most cells.
A table can leave cells empty.
Cells can span columns, as they can in HTML.
The width of a column is defined by the row with the widest cell in that column.
However, a Table Layout can specify certain columns as shrinkable or stretchable by
calling
setColumnShrinkable()or setColumnStretchable().
If marked as shrinkable, the column width can be shrunk to fit the table into its parent object.
If marked as stretchable, it can expand in width to fit any extra space.
The total width of the table is defined by its parent container.
It is important to remember that a column can be both shrinkable and stretchable.
In such a situation, the column will change its size to always use up the available space, but
never more.
You can hide a column by calling setColumnCollapsed().
The children of a Table Layout cannot specify the layout_widthattribute.
Width is always MATCH_PARENT.
However, the layout_heightattribute can be defined by a child; default value is
WRAP_CONTENT.
If the child is a TableRow, then the height is always WRAP_CONTENT.
Cells must be added to a row in increasing column order, both in code and XML.
Column numbers are zero-based.
If you don't specify a column number for a child cell, it will autoincrement to the next
available column.
If you skip a column number, it will be considered an empty cell in that row.
Although the typical child of a Table Layout is a TableRow, you can actually use
any View subclass as a direct child of Table Layout.
The View will be displayed as a single row that spans all the table columns. Sample
code showing use of TableLayout has been shown below:

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


<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:stretchColumns="1">
<TableRow>
<TextView
android:text="@string/table_layout_4_open"
android:padding="3dip" />
<TextView
android:text="@string/table_layout_4_open_shortcut"
android:gravity="right"
android:padding="3dip" />
</TableRow>

<TableRow>
<TextView
android:text="@string/table_layout_4_save"
android:padding="3dip" />
<TextView
android:text="@string/table_layout_4_save_shortcut"
android:gravity="right"
android:padding="3dip" />
</TableRow></TableLayout>
Unit 5: Database Connectivity
Android provides several options for you to save your app data. The solution you choose
depends on your specific needs, such as how much space your data requires, what kind of data
you need to store, and whether the data should be private to your app or accessible to other
apps and the user.

There are 4 type of storage that android provide.

 Internal file storage: Store app-private files on the device file system.

 External file storage: Store files on the shared external file system. This is usually for
shared user files, such as photos.

 Shared preferences: Store private primitive data in key-value pairs.

 Databases: Store structured data in a private database.

 FileProvide : If you want to share files with other apps

Shared Preferences

The SharedPreferences API is commonly used to permanently save small collections of key-
value pairs. Data stored in a SharedPreferences object is written to a plain-text XML file. The
SharedPreferences object can be declared world-readable (accessible to all apps) or private.
Misuse of the SharedPreferences API can often lead to exposure of sensitive data. Consider
the following example:

Example for Java:

SharedPreferences sharedPref = getSharedPreferences("key",


MODE_WORLD_READABLE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("username", "administrator");
editor.putString("password", "supersecret");
editor.commit();

Once the activity has been called, the file key.xml will be created with the provided data.
This code violates several best practices.

 The username and password are stored in clear text in /data/data/<package-


name>/shared_prefs/key.xml.

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>


<map>
<string name="username">administrator</string>
<string name="password">supersecret</string>
</map>

SQLite Database (Unencrypted)

SQLite is an SQL database engine that stores data in .db files. The Android SDK has built-in
support for SQLite databases. The main package used to manage the databases is
android.database.sqlite. For example, you may use the following code to store sensitive
information within an activity:

Example in Java:

SQLiteDatabase notSoSecure = openOrCreateDatabase("privateNotSoSecure",


MODE_PRIVATE, null);
notSoSecure.execSQL("CREATE TABLE IF NOT EXISTS Accounts(Username
VARCHAR, Password VARCHAR);");
notSoSecure.execSQL("INSERT INTO Accounts VALUES('admin','AdminPass');");
notSoSecure.close();

Once the activity has been called, the database file privateNotSoSecure will be created with
the provided data and stored in the clear text file /data/data/<package-
name>/databases/privateNotSoSecure.

The database's directory may contain several files besides the SQLite database:

 Journal files: These are temporary files used to implement atomic commit and
rollback.
 Lock files: The lock files are part of the locking and journaling feature, which was
designed to improve SQLite concurrency and reduce the writer starvation problem.

Sensitive information should not be stored in unencrypted SQLite databases.

SQLite Databases (Encrypted)

With the library SQLCipher, SQLite databases can be password-encrypted.

Example in Java:

SQLiteDatabase secureDB = SQLiteDatabase.openOrCreateDatabase(database,


"password123", null);
secureDB.execSQL("CREATE TABLE IF NOT EXISTS Accounts(Username
VARCHAR,Password VARCHAR);");
secureDB.execSQL("INSERT INTO Accounts VALUES('admin','AdminPassEnc');");
secureDB.close();

Databases

Android provides full support for SQLite databases. Any database you create is accessible
only by your app. However, instead of using SQLite APIs directly, we recommend that you
create and interact with your databases with the Room persistence library.

The Room library provides an object-mapping abstraction layer that allows fluent database
access while harnessing the full power of SQLite.

Although you can still save data directly with SQLite, the SQLite APIs are fairly low-level
and require a great deal of time and effort to use. For example:

 There is no compile-time verification of raw SQL queries.

 As your schema changes, you need to update the affected SQL queries manually. This
process can be time consuming and error prone.

 You need to write lots of boilerplate code to convert between SQL queries and Java data
objects.

The Room persistence library takes care of these concerns for you while providing an
abstraction layer over SQLite.

Realm Databases

The Realm Database for Java is becoming more and more popular among developers. The
database and its contents can be encrypted with a key stored in the configuration file.

//the getKey() method either gets the key from the server or from a KeyStore, or is derived
from a password.
RealmConfiguration config = new RealmConfiguration.Builder()
.encryptionKey(getKey())
.build();

Realm realm = Realm.getInstance(config);


If the database is not encrypted, you should be able to obtain the data. If the database is
encrypted, determine whether the key is hard-coded in the source or resources and whether it
is stored unprotected in shared preferences or some other location.

Internal Storage

You can save files to the device's internal storage. Files saved to internal storage are
containerized by default and cannot be accessed by other apps on the device. When the user
uninstalls your app, these files are removed. The following code snippets would persistently
store sensitive data to internal storage.

Example for Java:

FileOutputStream fos = null;


try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(test.getBytes());
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

External Storage

Every Android-compatible device supports shared external storage. This storage may be
removable (such as an SD card) or internal (non-removable). Files saved to external storage
are world-readable. The user can modify them when USB mass storage is enabled. You can
use the following code snippets to persistently store sensitive information to external storage
as the contents of the file password.txt.

Example for Java:

File file = new File (Environment.getExternalFilesDir(), "password.txt");


String password = "SecretPassword";
FileOutputStream fos;
fos = new FileOutputStream(file);
fos.write(password.getBytes());
fos.close();
Starting from Android 6.0 (API 23), users are not asked for permissions at the time of
installation rather developers need to request the permissions at the run time. Only the
permissions that are defined in the manifest file can be requested at run time.
Types of Permissions
1. Install-Time Permissions: If the Android 5.1.1 (API 22) or lower, the permission is
requested at the installation time at the Google Play Store.

If the user Accepts the permissions, the app is installed. Else the app installation is
canceled.

2. Run-Time Permissions: If the Android 6 (API 23) or higher, the permission is


requested at the run time during the running of the app.

If the user Accepts the permissions, then that feature of the app can be used. Else to use the
feature, the app requests permission again.
Unit 6: Application of Industrial Projects

What is parsing? Explain JSON parsing with example.

Extensible Markup Language (XML) is a set of rules for encoding documents in


machine-readable form.
XML is a popular format for sharing data on the internet.
Websites that frequently update their content, such as news sites or blogs, often
provide an XML feed so that external programs can keep abreast of content
changes.
Uploading and parsing XML data is a common task for network-connected apps.
We will see how to parse XML documents and use their data.

XmlPullParser, which is an efficient and maintainable way to parse XML on


Android. Historically Android has had two implementations of this interface:

KXmlParser via XmlPullParserFactory.newPullParser()

ExpatPullParser via Xml.newPullParser()

JSON Parsing

JSON stands for JavaScript Object Notation.


It is an independent data exchange format and is the best alternative for XML.
Android provides four different classes to manipulate JSON data.
These classes are JSONArray, JSONObject, JSONStringerand JSONTokenizer.

The first step is to identify the fields in the JSON data in which you are interested
in. For example. In the JSON given below we interested in getting temperature
only.

{
"sys":
{
"country":"GB",
"sunrise":1381107633,
"sunset":1381149604
},
"weather":[
{
"id":711,
"main":"Smoke",
"description":"smoke",
"icon":"50n"
}
],

"main":
{
"temp":304.15,
"pressure":1009,
}
}

JSON - Elements

An JSON file consist of many components. Here is the table defining the components of
an JSON file and their description −
Array([) - In a JSON file , square bracket ([) represents a JSON array
Objects({) - In a JSON file, curly bracket ({) represents a JSON object
Key - A JSON object contains a key that is just a string. Pairs of key/value make up a
JSON object
Value - Each key has a value that could be string, integer or double etc.,

JSON - Parsing

For parsing a JSON object, we will create an object of class JSONObject and specify a
string containing JSON data to it. Its syntax is −

String in:
JSONObject reader = new JSONObject(in);
The last step is to parse the JSON. A JSON file consist of different object with different
key/value pair e.t.c. So JSONObject has a separate function for parsing each of the
component of JSON file. Its syntax is given below −

JSONObject sys =
reader.getJSONObject("sys"); country =
sys.getString("country");

JSONObject main =
reader.getJSONObject("main"); temperature =
main.getString("temp");
The method getJSONObject returns the JSON object. The method getStringreturns the
string value of the specified key.

Sample JSON Parsing

@Override

protected Void doInBackground(Void... arg0) {


HttpHandler sh = new HttpHandler();

// Making a request to url and getting response


String url ="http://api.twitteruser.info/contacts/";
String jsonStr = sh.makeServiceCall(url);

Log.e(TAG, "Response from url: " +


jsonStr); if (jsonStr != null) {

try {

JSONObject jsonObj = new JSONObject(jsonStr);

// Getting JSON Array node

JSONArray contacts = jsonObj.getJSONArray("contacts");

// looping through All Contacts

for (int i = 0; i < contacts.length(); i++) {


JSONObject c =
contacts.getJSONObject(i); String id
= c.getString("id");

String name =
c.getString("name"); String email
= c.getString("email"); String
address = c.getString("address");
String gender =
c.getString("gender");

// Phone node is JSON Object

JSONObject phone =
c.getJSONObject("phone"); String
mobile = phone.getString("mobile");
String home =
phone.getString("home"); String office
= phone.getString("office");

// tmp hash map for single contact

HashMap<String, String> contact = new HashMap<>();

// adding each child node to HashMap key => value


contact.put("id", id);

contact.put("name", name);
contact.put("email", email);
contact.put("mobile", mobile);

// adding contact to contact list


contactList.add(contact);

} catch (final JSONException e) {

Log.e(TAG, "Json parsing error: " +e.getMessage());


runOnUiThread(new Runnable() {

@Override

public void run() {


Toast.makeText(getApplicationCo
ntext(), "Json parsing error: " +
e.getMessage(),

Toast.LENGTH_LONG).show();

});

} else {

Log.e(TAG, "Couldn't get json from


server."); runOnUiThread(new Runnable() {
@Override

public void run() {


Toast.makeText(getApplicationContext
(),

"Couldn't get json from server.",


Toast.LENGTH_LONG).show();

});

return null;

What is Parsing? Explain XML Parsing with suitable example.

Extensible Markup Language (XML) is a set of rules for encoding documents in


machine-readable form.
XML is a popular format for sharing data on the internet.
Websites that frequently update their content, such as news sites or blogs, often
provide an XML feed so that external programs can keep abreast of content
changes.
Uploading and parsing XML data is a common task for network-connected apps.
We will see how to parse XML documents and use their data.

XmlPullParser, which is an efficient and maintainable way to parse XML on Android.


Historically Android has had two implementations of this interface:

KXmlParserviaXmlPullParserFactory.newPullParser()
ExpatPullParser, via Xml.newPullParser()

XML Parsing

XML stands for Extensible Mark-up Language.


XML is a very popular format and commonly used for sharing data on the internet.
This chapter explains how to parse the XML file and extract necessary information
from it.
Android provides three types of XML parsers which are DOM,SAX and
XMLPullParser.
Among all of them android recommend XMLPullParser because it is efficient and
easy to use.
So we are going to use XMLPullParser for parsing XML.
The first step is to identify the fields in the XML data in which you are interested in.
E.g., in the XML given below we interested in getting temperature only.

<?xml version="1.0"?>
<current>

<city id="2643743" name="London">


<coord lon="-0.12574" lat="51.50853"/>
<country>GB</country>
<sun rise="2013-10-08T06:13:56" set="2013-10-08T17:21:45"/>
</city>

<temperature value="289.54" min="289.15" max="290.15"unit="kelvin"/>

What is web services? How it integrates and implements in industrial projects?

A web service is a standard used for exchanging information between applications


or systems of heterogeneous type.
Software applications written in various programming languages and running on
various platforms can use web services to exchange information over Internet using
http protocol.

Why Web Service?

Expose method as a service over network:

Web service is a chunk of code written in some programming language (Say C# or


Java) that can be invoked remotely through http protocol.
Once the Web methods are exposed publically, any applications can invoke it and
use the functionality of the web methods.
Application Inter-operability – Connect heterogeneous applications:

With the help of web service, heterogeneous applications (Java and PHP application)
can communicate with each other.
Web service written in Java can be invoked from PHP by passing the required
parameters to web methods.
This makes the applications platform and technology independent.
Standardized protocol:

Web Services uses standardized industry standard protocol for the communication
which must be adhered and followed by the applications creating Web Service.
Cost effective communication:

Web service is using SOAP over HTTP protocol for communication which is much
cheaper than systems like B2B.

RESTFul Webservice Request and Response – Drill down

Fist step in designing RESTFul webservice is choosing the right domain name –
say weatherinfo.org to retrieve weather information of cities.
Let us take the first example (weatherinfo.org) which takes city name as input,
composes weather information of the city and respond back to the browser.
Assume the response is in XML format, this can be in other formats like JSON as
well.
Here is the structure of Request and Response:

HTTP Request

The client request from the browser will look like:


GET http://weatherinfo.org/getweather/mumbai HTTP/1.1

HTTP Response

The server response will look like


HTTP/1.1 200 Ok
Date: Mon, 14 Apr 2014 10:20:58 GMT
Content-Type:
text/xml
Content-length:
139

<City name="Mumbai" datetime="2014-04-14 10:20:58 GMT" >


<Condition>Scattered Clouds</Condition>
<Temp>33</Temp>
</City>

Line 1 is the initial line which has the HTTP response code – 200 OK, lines 2
through 4 are the HTTP headers, line 5 is the mandatory blank line separating
header and body, and lines 6 through 10 constitute the ―HTTP Body (or content)‖ –
this part is the data that the response carries and can be in any format, not
necessarily XML.
Advantages of using RESTful webservice

RESTful Web services are designed with less dependence on proprietary middleware
(for example, an application server) than the SOAP- and WSDL-based kind.
As per the RESTful interface design, XML or JSON over HTTP is a powerful
interface that allows internal applications, such as Asynchronous JavaScript +
XML/JSON (Ajax) - based custom user interfaces, to easily connect, address, and
consume resources.
The great fit between Ajax and REST has increased the amount of attention REST is
getting these days.
Exposing a system’s resources through a RESTful API is a flexible way to provide
different kinds of applications with data formatted in a standard way. It helps to
meet integration requirements that are critical to building systems where data can be
easily combined (mashups) and to extend or build on a set of base, RESTful
services into something much bigger.

<humidity value="77" unit="%"/>


<pressure value="1025" unit="hPa"/>
</current>

XML - Elements

An xml file consist of many components. Here is the table defining the components of an
XML file and their description.
Prolog - An XML file starts with a prolog. The first line that contains the information
about a file is prolog
Events - An XML file has many events. Event could be like this. Document starts,
Document ends, Tag start, Tag end and Text
Text - Apart from tags and events, and xml file also contains simple text. Such as GB
is a text in the country tag.
Attributes - Attributes are the additional properties of a tag such as value.

We will create XMLPullParser object , but in order to create that we will first
create XmlPullParserFactory object and then call its newPullParser() method to
create XMLPullParser. Its syntax is given below −

private XmlPullParserFactory xmlFactoryObject = XmlP


private XmlPullParser myparser = xmlFactoryObject.newPullParser();

The next step involves specifying the file for XmlPullParser that contains XML. It
could be a file or could be a Stream. In our case it is a stream.
Its syntax is given below:
myparser.setInput(stream, null);
The last step is to parse the XML. An XML file consist of events, Name, Text,
AttributesValue etc., So XMLPullParser has a separate function for parsing each of the
component of XML file. Its syntax is given below −

int event = myParser.getEventType();


while (event!=
XmlPullParser.END_DOCUMENT) { String name=myParser.getName();
switch (event){
case XmlPullParser.START_TAG:
break;

case XmlPullParser.END_TAG:
if(name.equals("temperature")){
temperature = myParser.getAttributeValue(null,"value");
}
break;
}
event = myParser.next();
}

The method getEventType returns the type of event that happens. e.g: Document start,
tag start. The method getName returns the name of the tag and since we are only
interested in temperature, so we just check in conditional statement that if we got a
temperature tag, we call the method getAttributeValue to return us the value of
temperature tag.
Sample XML Parsing

import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;

import
javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;

import
org.w3c.dom.Element;
import
org.w3c.dom.Node;
import
org.w3c.dom.NodeLis
t; import
android.app.Activity;
import
android.os.Bundle;

import android.widget.TextView;

public class MainActivity extends Activity {


TextView tv1;

@Override

public void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1=(TextView)findViewById(R.id.textView1);

try {

InputStream is = getAssets().open("file.xml");

DocumentBuilderFactory dbFactory =
DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder =
dbFactory.newDocumentBuilder();

Document doc = dBuilder.parse(is);

Element element=doc.getDocumentElement();
element.normalize();

NodeList nList =
doc.getElementsByTagName("employee"); for (int
i=0; i<nList.getLength(); i++) {

Node node = nList.item(i);

if (node.getNodeType() ==
Node.ELEMENT_NODE) { Element
element2 = (Element) node;

tv1.setText(tv1.getText()+"\nName : " +getValue("name",


element2)+"\n");
tv1.setText(tv1.getText()+"Surname : " +getValue("surname",
element2)+"\n");

tv1.setText(tv1.getText()+" --------------------------------- ");

} catch (Exception e) {e.printStackTrace();}

private static String getValue(String tag, Element element) {

NodeList nodeList =
element.getElementsByTagName(tag).item(0).getChildNodes(); Node node =
nodeList.item(0);

return node.getNodeValue();

In Android, Retrofit is a REST Client for Java and Android by Square inc under Apache 2.0
license. Its a simple network library that used for network transactions. By using this library
we can seamlessly capture JSON response from web service/web API. It’s easy and fast
library to retrieve and upload the data(JSON or any other structured data) via a REST based
web service.

Difference Between Retrofit and other libraries:


In Android, retrofit library is different from other network libraries because it gives us an
easy to use platform through which we don’t need to parse JSON responses as they are done
by library itself. It used GSON library in the background to parser the response data. What
we need to do is define a POJO (Plain Old Java Object) to parse the response.
Difference Between Retrofit and other libraries:
In Android, retrofit library is different from other network libraries because it gives us an
easy to use platform through which we don’t need to parse JSON responses as they are done
by library itself. It used GSON library in the background to parser the response data. What
we need to do is define a POJO (Plain Old Java Object) to parse the response.
Performance benchmarks for Android AsyncTask, Volley and Retrofit (in milliseconds,
lower value is better):
Here is the main difference between our three mainly used techniques for implementing
API’s is our android app. You can see the difference in performance that for one discussion
means for one network request and response they will take how much time.
1. AsyncTask: one(1) discussion: 941 ms
Seven(7) discussions: 4539 ms
Twenty Five(25) discussions: 13957 ms
2. Volley/3rd party:
one(1) discussion: 560 ms
Seven(7) discussions: 2202 ms
Twenty Five(25) discussions: 4275 ms
3. Retrofit:
one(1) discussion: 312 ms
Seven(7) discussions: 889 ms
Twenty Five(25) discussions: 1059 ms
Unit 7: Advanced Android Development

Map and Location


Location and maps can be very useful in some apps. A device’s location is acquired by
listening
to either the network or the GPS sensor. You can code the capability to acquire the device’s
location whether you use maps or not. However, if you use maps, the code for determining
your location is much simpler.
Icons can be placed on a map based on their GPS coordinates. The map object has a large
number of classes that facilitate the manipulation of maps. Icons on a map are called markers.
Markers can use the standard pin icon or a custom item supplied by the developer. Icons can
also be made to display information about the location through the use of a title and snippets.
Using Google Maps in an Android requires significantly more setup than other code you have
explored in this book. However, after you have set it up, you do not have to redo it for other
apps you want to develop.

Maps
Maps are implemented using the GoogleMap object in the source code file and a
MapFragment in the layout file. These objects are not a part of the standard Android SDK but
rather the Google Play Services SDK. This SDK must be installed on your development
machine to implement maps in your app. Using Google Maps requires an API key. This key
associates your app with an attempt to access the GoogleMap API. This is how you, and
Google, can track how often your users access the map portion of your app. The API key is
free. Maps are implemented as a MapFragment widget in a layout. The Activity that
implements the code to provide the map’s behavior must be a FragmentActivity .

Location Sensors

Android devices typically have two location sensors. One sensor (network sensor) is based
on the cell towers and/or the Wi-Fi access points your device is connected to. This sensor
provides the approximate location of the device. The other sensor is based on a built-in
Global
Positioning System (GPS) receiver. This sensor can provide position information accurate to
within a few meters, depending on conditions. However, the GPS sensor is much slower in
acquiring its position information than the network sensor. Additionally, not all devices have
a

GPS sensor.

Location information is accessed within an app through the use of the LocationManager
object. A LocationManager is not directly instantiated. It exists as an Android system service,
and is accessed through the method getSystemService . The LocationManager object
can request updates from either or both sensors. To get the updates, an app has to
instantiate a LocationListener . A LocationListener implements the method
onLocationChanged . Whenever the sensor reports a location change, that change is
captured by the LocationListener , which is passed a Location object, and the
onLocationChanged method is executed. A Location object contains information on the
new location, including GPS coordinates and altitude, which sensor provided the location, a
measure of the accuracy of the coordinate estimate (usually in meters), as well as other
information.
The onLocationChanged method uses this object to perform operations based on
the code the developer provided in the method. To begin receiving location information from
the sensors, the LocationManager requests the updates from a specific provider and tells it
what LocationListener to use to handle the updates. When the LocationManager requests
updates from the GPS, the GPS is activated. However, the GPS must also be enabled by the
user
to be activated. If it has not been enabled, the code cannot turn it on. It is recommended that
the developer test whether the GPS is enabled and inform the user if it is not.

Geocoding:
Get Coordinates from an Address.In this first approach to getting location, the
ContactMapActivity will take an entered address and look up and display the GPS
coordinates of the address. This process is called geocoding .
The first step is to create the layout in activity_contact_map.xml. For now, this layout will
not use a map object. Refer to Figure 7.5 to code this layout. The exact layout is up to you—
you’ve done all this before. However, to match to the code, use the following IDs for the
widgets:
Get Coordinates Button–@+id/buttonGetLocation
Latitude output TextView–@+id/textLatitude
Longitude output TextView–@+id/textLongitude
Accuracy output TextView–@+id/textAccuracy
Obviously, the easiest way to code the address portion of the layout is to copy the relevant
XML from activity_contact.xml. Some minor changes need to be made to get the Address
TextView to appear at the top left of the layout. The code for this section uses the same
widget
IDs for the address EditTexts as was used in activity_contact.xml.

After the layout has been created, open the ContactMapActivity.java file to write the code
that provides the behavior for the Get Location button. The button will respond to a user tap
by retrieving the data entered into the EditTexts and format them into the form required by
address look-up service. It will then be sent to the service and the resulting location will be
displayed onscreen.

Maps activity file

The maps activity file is the main activity for the app, and contains the code to manage and
display the map. By default, the file that defines the activity is named MapsActivity.java

The main elements of the maps activity:

 The SupportMapFragment object manages the life cycle of the map and is the parent element
of the app's UI.
 The GoogleMap object provides access to the map data and view. This is the main class of
the Maps SDK for Android. The Map Objects guide describes
the SupportMapFragment and GoogleMap objects in more detail.
 The moveCamera function centers the map at the LatLng coordinates for Sydney Australia.
The first settings to configure when adding a map are usually the map location and camera
settings; such as viewing angle, map orientation, and zoom level. See the Camera and
View guide for details.
 The addMarker function adds a marker to the coordinates for Sydney

Google Map - Layout file


Now you have to add the map fragment into xml layout file. Its syntax is given below −

<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>

Google Map - AndroidManifest file


The next thing you need to do is to add some permissions along with the Google Map API
key in the AndroidManifest.XML file. Its syntax is given below −

<!--Permissions-->

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />


<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.google.android.providers.gsf.permission.
READ_GSERVICES" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<!--Google MAP API key-->

<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyDKymeBXNeiFWY5jRUejv6zItpmr2MVyQ0" />

Customizing Google Map

You can easily customize google map from its default view , and change it according to your
demand.

Adding Marker
You can place a maker with some text over it displaying your location on the map. It can be
done by via addMarker() method. Its syntax is given below −

final LatLng TutorialsPoint = new LatLng(21 , 57);


Marker TP = googleMap.addMarker(new MarkerOptions()
.position(TutorialsPoint).title("TutorialsPoint"));

Changing Map Type


You can also change the type of the MAP. There are four different types of map and each
give a different view of the map. These types are Normal,Hybrid,Satellite and terrain. You
can use them as below

googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);

Enable/Disable zoom
You can also enable or disable the zoom gestures in the map by calling
the setZoomControlsEnabled(boolean) method. Its syntax is given below −

googleMap.getUiSettings().setZoomGesturesEnabled(true);

Code to get Location from Map Object

public class ContactMapActivity extends FragmentActivity {


GoogleMap googleMap ;
@Override
public void onCreate(Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
setContentView(R.layout. activity_contact_map );
googleMap = ((SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id. map )).getMap();
googleMap .setMapType(GoogleMap. MAP_TYPE_NORMAL );
googleMap .setMyLocationEnabled( true );
googleMap .setOnMyLocationChangeListener( new
➥OnMyLocationChangeListener() {
@Override
public void onMyLocationChange(Location location) {
LatLng point = new LatLng(location.getLatitude(),
➥location.getLongitude());
googleMap .animateCamera(CameraUpdateFactory.
➥ newLatLngZoom (point, 11));
Toast. makeText (getBaseContext(), "Lat: " +location.getLatitude()+
➥ "Long: " +location.getLongitude()+ " Accuracy: " +
➥location.getAccuracy(), Toast. LENGTH_LONG ).show();
}
});
}

Geocoder

A class for handling geocoding and reverse geocoding. Geocoding is the process of
transforming a street address or other description of a location into a (latitude, longitude)
coordinate. Reverse geocoding is the process of transforming a (latitude, longitude)
coordinate into a (partial) address. The amount of detail in a reverse geocoded location
description may vary, for example one might contain the full street address of the closest
building, while another might contain only a city name and postal code. The Geocoder class
requires a backend service that is not included in the core android framework. The Geocoder
query methods will return an empty list if there no backend service in the platform. Use the
isPresent() method to determine whether a Geocoder implementation exists.

public final class Geocoder


extends Object
java.lang.Object
↳ android.location.Geocoder

2d Graphics

Android offers a custom 2D graphics library for drawing and animating shapes and images.
The android.graphics.drawable and android.view.animation packages are where you'll find
the common classes used for drawing and animating in two-dimensions.

This document offers an introduction to drawing graphics in your Android application. We'll
discuss the basics of using Drawable objects to draw graphics, how to use a couple subclasses
of the Drawable class, and how to create animations that either tween (move, stretch, rotate) a
single graphic or animate a series of graphics (like a roll of film).

LinearLayout mLinearLayout;

protected void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);

// Create a LinearLayout in which to add the ImageView


mLinearLayout = new LinearLayout(this);

// Instantiate an ImageView and define its properties


ImageView i = new ImageView(this);
i.setImageResource(R.drawable.my_image);
i.setAdjustViewBounds(true); // set the ImageView bounds to match the Drawable's
dimensions
i.setLayoutParams(new Gallery.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));

// Add the ImageView to the layout and set the layout as the content view
mLinearLayout.addView(i);
setContentView(mLinearLayout);
}

Create if not:

Resources res = mContext.getResources();


Drawable myImage = res.getDrawable(R.drawable.my_image);

A Bitmap is a representation of a bitmap image (something like java.awt.Image). A Drawable


is an abstraction of "something that can be drawn". It could be a Bitmap (wrapped up as
a BitmapDrawable), but it could also be a solid color, a collection of other Drawable objects,
or any number of other structures.

Most of the Android UI framework likes to work with Drawable objects, not Bitmap objects.
A View can accept any Drawable as a background. An ImageView can display a foreground
Drawable. Images stored as resources are loaded as Drawable objects.
The animation is the process of adding a motion effect to any view, image, or text. With the
help of an animation, you can add motion or can change the shape of a specific view.
Animation in Android is generally used to give your UI a rich look and feel. The
animations are basically of three types as follows:
1. Property Animation
2. View Animation
3. Drawable Animation
1. Property Animation
Property Animation is one of the robust frameworks which allows animating almost
everything. This is one of the powerful and flexible animations which was introduced in
Android 3.0. Property animation can be used to add any animation in
the CheckBox, RadioButtons, and widgets other than any view.
2. View Animation
View Animation can be used to add animation to a specific view to perform tweened
animation on views. Tweened animation calculates animation information such as size,
rotation, start point, and endpoint. These animations are slower and less flexible. An
example of View animation can be used if we want to expand a specific layout in that place
we can use View Animation. The example of View Animation can be seen in Expandable
RecyclerView.

3. Drawable Animation
Drawable Animation is used if you want to animate one image over another. The simple
way to understand is to animate drawable is to load the series of drawable one after another
to create an animation. A simple example of drawable animation can be seen in many apps
Splash screen on apps logo animation.
Important Methods of Animation

Methods Description

startAnimation() This method will start the animation.

clearAnimation() This method will clear the animation running on a specific view.

Android Media Player


Android provides many ways to control playback of audio/video files and streams. One of
this way is through a class called MediaPlayer.
Android is providing MediaPlayer class to access built-in mediaplayer services like playing
audio,video e.t.c. In order to use MediaPlayer, we have to call a static Method create() of
this class. This method returns an instance of MediaPlayer class. Its syntax is as follows −
MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.song);
The second parameter is the name of the song that you want to play. You have to make a
new folder under your project with name raw and place the music file into it.
Once you have created the Mediaplayer object you can call some methods to start or stop the
music. These methods are listed below.

mediaPlayer.start();
mediaPlayer.pause();

On call to start() method, the music will start playing from the beginning. If this method is
called again after the pause() method, the music would start playing from where it is left and
not from the beginning.
In order to start music from the beginning, you have to call reset() method. Its syntax is
given below.
mediaPlayer.reset();

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;
import android.widget.Toast;
import java.util.concurrent.TimeUnit;

public class MainActivity extends Activity {


private Button b1,b2,b3,b4;
private ImageView iv;
private MediaPlayer mediaPlayer;

private double startTime = 0;


private double finalTime = 0;

private Handler myHandler = new Handler();;


private int forwardTime = 5000;
private int backwardTime = 5000;
private SeekBar seekbar;
private TextView tx1,tx2,tx3;

public static int oneTimeOnly = 0;


@Override
protected void onCreate(Bundle savedInstanceState) {
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);
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");

mediaPlayer = MediaPlayer.create(this, R.raw.song);


seekbar = (SeekBar)findViewById(R.id.seekBar);
seekbar.setClickable(false);
b2.setEnabled(false);
b3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
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;
}

tx2.setText(String.format("%d min, %d sec",


TimeUnit.MILLISECONDS.toMinutes((long) finalTime),
TimeUnit.MILLISECONDS.toSeconds((long) finalTime) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long)
finalTime)))
);

tx1.setText(String.format("%d min, %d sec",


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(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Pausing
sound",Toast.LENGTH_SHORT).show();
mediaPlayer.pause();
b2.setEnabled(false);
b3.setEnabled(true);
}
});

b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int temp = (int)startTime;

if((temp+forwardTime)<=finalTime){
startTime = startTime + forwardTime;
mediaPlayer.seekTo((int) startTime);
Toast.makeText(getApplicationContext(),"You have Jumped forward 5
seconds",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(),"Cannot jump forward 5
seconds",Toast.LENGTH_SHORT).show();
}
}
});

b4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int temp = (int)startTime;

if((temp-backwardTime)>0){
startTime = startTime - backwardTime;
mediaPlayer.seekTo((int) startTime);
Toast.makeText(getApplicationContext(),"You have Jumped backward 5
seconds",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(),"Cannot jump backward 5
seconds",Toast.LENGTH_SHORT).show();
}
}
});
}

private Runnable UpdateSongTime = new Runnable() {


public void run() {
startTime = mediaPlayer.getCurrentPosition();
tx1.setText(String.format("%d min, %d sec",
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);
}
};
}

Background Services

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.

Foreground Services

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.

When you use a foreground service, you must display a notification so that users are
actively aware that the service is running. This notification cannot be dismissed unless
the service is either stopped or removed from the foreground.

Bound Services

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.
Firebase:
It is a mobile platform that helps you quickly develop high-quality apps, grow your
user base, and earn more money. Firebase is made up of complementary features that
you can mix-and-match to fit your needs, with Google Analytics for Firebase at the core.

Implementation of CRUD operations in Android

We will see the implementation of CRUD one by one. Just open your DatabaseHandler.kt
and the following.

 CREATE, UPDATE, DELETE – should have written permission.


 READ – should have readable permission and cursor is used to read data from
SQLite.

CREATE/INSERT Data

1. fun addTask(tasks: Tasks): Boolean {


2. val db = this.writableDatabase
3. val values = ContentValues()
4. values.put(NAME, tasks.name)
5. values.put(DESC, tasks.desc)
6. values.put(COMPLETED, tasks.completed)
7. val _success = db.insert(TABLE_NAME, null, values)
8. db.close()
9. return (Integer.parseInt("$_success") != -1)
10. }

READ ALL/ONE Data


Cursor is used to read the SQLite database in Android.

1. fun getTask(_id: Int): Tasks {


2. val tasks = Tasks()
3. val db = writableDatabase
4. val selectQuery = "SELECT * FROM $TABLE_NAME WHERE $ID = $_id"
5. val cursor = db.rawQuery(selectQuery, null)
6. if (cursor != null) {
7. cursor.moveToFirst()
8. while (cursor.moveToNext()) {
9. tasks.id = Integer.parseInt(cursor.getString(cursor.getColumnIndex(ID)))
10. tasks.name = cursor.getString(cursor.getColumnIndex(NAME))
11. tasks.desc = cursor.getString(cursor.getColumnIndex(DESC))
12. tasks.completed = cursor.getString(cursor.getColumnIndex(COMPLETED))
13. }
14. }
15. cursor.close()
16. return tasks

UPDATE Data

1. fun updateTask(tasks: Tasks): Boolean {


2. val db = this.writableDatabase
3. val values = ContentValues()
4. values.put(NAME, tasks.name)
5. values.put(DESC, tasks.desc)
6. values.put(COMPLETED, tasks.completed)
7. val _success = db.update(TABLE_NAME, values, ID + "=?", arrayOf(tasks.id.toSt
ring())).toLong()
8. db.close()
9. return Integer.parseInt("$_success") != -1
10. }

DELETE Data

1. fun deleteTask(_id: Int): Boolean {


2. val db = this.writableDatabase
3. val _success = db.delete(TABLE_NAME, ID + "=?", arrayOf(_id.toString())).toLo
ng()
4. db.close()
5. return Integer.parseInt("$_success") != -1
6. }
Unit 8: Work with android system Development and Deployment

What Does Dalvik Debug Monitor Service (DDMS) Mean?

The Dalvik Debug Monitor Service (DDMS) is a debugging tool used in the Android
platform. The Dalvik Debug Monitor Service is downloaded as part of the Android SDK.
Some of the services provided by the DDMS are port forwarding, on-device screen capture,
on-device thread and heap monitoring, and radio state information.

Explains Dalvik Debug Monitor Service (DDMS)

The Dalvik Debug Monitor Service allows developers to spot bugs in applications running on
either an emulator or an actual Android device.

For example, by using the DDMS’ LogCat feature, developers can view log messages
regarding the state of the application and the device. LogCat can pinpoint the exact line
number on which an error occurred.

Another DDMS feature, known as the Emulator Control, allows developers to simulate phone
states and activities. For example, it can simulate different types of networks such as GPRS,
EDGE, and UTMS, which can have different network characteristics such as speed and
latency.

Aside from the features mentioned earlier, the Dalvik Debug Monitor Service also provides
LogCat, process, and radio state information as well as incoming call, SMS, and location data
spoofing.

Logcat

Logcat is a command-line tool that dumps a log of system messages, including stack traces
when the device throws an error and messages that you have written from your app with
the Log class.

This debugging tool can be integrated into the Eclipse IDE by adding the ADT (Android
Development Tools) plug-in. Otherwise, it can be accessed from the command line and will
automatically connect to any running emulator.

Device control

The features in this guide describe device management capabilities you can implement in
your device policy controller (DPC) app. You can also use the Test DPC app as a source of
sample code for Android's enterprise features.

A DPC app can run in profile owner mode on personal devices or in device owner mode on
fully managed devices. This table indicates which features are available when the DPC runs
in profile owner mode or device owner mode:

Feature Profile owner Device owner

Create a custom lock screen message ✓

Disable data roaming ✓

Give users a customized message if a setting is blocked ✓ ✓

Lock down the wallpaper ✓ ✓

Lock down a customer user icon ✓ ✓

Remotely monitor device health and status ✓ ✓

Remotely reboot an Android device ✓


Work with ADB

ADB is an important tool for developers because it allows you to interact with Android
emulators, and also with connected devices. There are many features covered in the ADB
documentation but here are some useful commands:

 adb kill-server and adb start-server – stop and start the ADB service if needed
 adb devices – list the devices available (including emulators and phones or tablets
attached to your computer)
 adb install – install APK files
 adb shell – execute commands on the Android system, for example:
o adb shell pm list packages – list all the packages installed
o adb shell pm path com.example.someapp – gets the file system path of the
package specified
 adb pull – extract files from the emulator or device
 Another use for ADB is simulating input commands, such as automating spanning of
an app on Surface Duo. These screenshots illustrate the process of spanning by
grabbing the handle at the bottom of the window, and dragging it towards the hinge
until the span indicator covers both screens:

Run on a real device

Set up your device as follows:

1. Connect your device to your development machine with a USB cable. If you developed on
Windows, you might need to install the appropriate USB driver for your device.

2. Perform the following steps to enable USB debugging in the Developer options window:
a. Open the Settings app.

b. If your device uses Android v8.0 or higher, select System. Otherwise, proceed to the next
step.

c. Scroll to the bottom and select About phone.

d. Scroll to the bottom and tap Build number seven times.

e. Return to the previous screen, scroll to the bottom, and tap Developer options.

f. In the Developer options window, scroll down to find and enable USB debugging.

Run the app on your device as follows:

1. In Android Studio, select your app from the run/debug configurations drop-down menu in the
toolbar.

2. In the toolbar, select the device that you want to run your app on from the target device drop-
down menu.

Figure . Target device drop-down menu

1. Click Run .

Android Studio installs your app on your connected device and starts it. You now see "Hello,
World!" displayed in the app on your device.

Publishing is the general process that makes your Android applications available to users.
When you publish an Android application you perform two main tasks:

 You prepare the application for release.


During the preparation step you build a release version of your application, which users can
download and install on their Android-powered devices.

 You release the application to users.

During the release step you publicize, sell, and distribute the release version of your
application to users.

This page provides an overview of the process you should follow as you prepare to publish
your app. If you plan to publish on Google Play, you should also read the Google Play launch
checklist.

Preparing your app for release

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

Releasing your app to users

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.

Releasing through an app marketplace

If you want to distribute your apps to the broadest possible audience, releasing through an
app marketplace such as Google Play is ideal.

Google Play is the premier marketplace for Android apps and is particularly useful if you
want to distribute your applications to a large global audience. However, you can distribute
your apps through any app marketplace you want or you can use multiple marketplaces.

Releasing your apps on Google Play

Google Play is a robust publishing platform that helps you publicize, sell, and distribute your
Android applications to users around the world. When you release your applications through
Google Play you have access to a suite of developer tools that let you analyze your sales,
identify market trends, and control who your applications are being distributed to. You also
have access to several revenue-enhancing features such as in-app billing and application
licensing. The rich array of tools and features, coupled with numerous end-user community
features, makes Google Play the premier marketplace for selling and buying Android
applications.

Releasing your application on Google Play is a simple process that involves three basic steps:

 Preparing promotional materials.

To fully leverage the marketing and publicity capabilities of Google Play, you need to create
promotional materials for your application, such as screenshots, videos, graphics, and
promotional text.
 Configuring options and uploading assets.

Google Play lets you target your application to a worldwide pool of users and devices. By
configuring various Google Play settings, you can choose the countries you want to reach, the
listing languages you want to use, and the price you want to charge in each country. You can
also configure listing details such as the application type, category, and content rating. When
you are done configuring options you can upload your promotional materials and your
application as a draft (unpublished) application.

 Publishing the release version of your application.

If you are satisfied that your publishing settings are correctly configured and your uploaded
application is ready to be released to the public, you can simply click Publish in the Play
Console and within minutes your application will be live and available for download around
the world.

Releasing through a website

If you do not want to release your app on a marketplace like Google Play, you can make the
app available for download on your own website or server, including on a private or
enterprise server. To do this, you must first prepare your application for release in the normal
way. Then all you need to do is host the release-ready APK file on your website and provide
a download link to users.

When users browse to the download link from their Android-powered devices, the file is
downloaded and Android system automatically starts installing it on the device. However, the
installation process will start automatically only if the user has configured their Settings to
allow the installation of apps from unknown sources.

Although it is relatively easy to release your application on your own website, it can be
inefficient. For example, if you want to monetize your application you will have to process
and track all financial transactions yourself and you will not be able to use Google Play's In-
app Billing service to sell in-app products. In addition, you will not be able to use
the Licensing service to help prevent unauthorized installation and use of your application.

Open the Camera Object

Getting an instance of the Camera object is the first step in the process of directly controlling
the camera. As Android's own Camera application does, the recommended way to access the
camera is to open Camera on a separate thread that's launched from onCreate(). This
approach is a good idea since it can take a while and might bog down the UI thread. In a
more basic implementation, opening the camera can be deferred to the onResume() method to
facilitate code reuse and keep the flow of control simple.
Calling Camera.open() throws an exception if the camera is already in use by another
application, so we wrap it in a try block.

private boolean safeCameraOpen(int id) {


boolean qOpened = false;

try {
releaseCameraAndPreview();
camera = Camera.open(id);
qOpened = (camera != null);
} catch (Exception e) {
Log.e(getString(R.string.app_name), "failed to open Camera");
e.printStackTrace();
}

return qOpened;
}

private void releaseCameraAndPreview() {


preview.setCamera(null);
if (camera != null) {
camera.release();
camera = null;
}
}

Capturing pictures

Once you have built a preview class and a view layout in which to display it, you are ready to
start capturing images with your application. In your application code, you must set up
listeners for your user interface controls to respond to a user action by taking a picture.

In order to retrieve a picture, use the Camera.takePicture() method. This method takes three
parameters which receive data from the camera. In order to receive data in a JPEG format,
you must implement an Camera.PictureCallback interface to receive the image data and write
it to a file. The following code shows a basic implementation of
the Camera.PictureCallback interface to save an image received from the camera.

private PictureCallback mPicture = new PictureCallback() {

@Override
public void onPictureTaken(byte[] data, Camera camera) {

File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);


if (pictureFile == null){
Log.d(TAG, "Error creating media file, check storage permissions");
return;
}

try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
};

Trigger capturing an image by calling the Camera.takePicture() method.

Connect as a Bluetooth

When you want to connect two devices, one must act as a server by holding an
open BluetoothServerSocket. The purpose of the server socket is to listen for incoming
connection requests and provide a connected BluetoothSocket after a request is accepted.
When the BluetoothSocket is acquired from the BluetoothServerSocket,
the BluetoothServerSocket can—and should—be discarded, unless you want the device to
accept more connections.

To set up a server socket and accept a connection, complete the following sequence of steps:

1. Get a BluetoothServerSocket by calling listenUsingRfcommWithServiceRecord().

The string is an identifiable name of your service, which the system automatically writes to a
new Service Discovery Protocol (SDP) database entry on the device. The name is arbitrary
and can simply be your app name. The Universally Unique Identifier (UUID) is also included
in the SDP entry and forms the basis for the connection agreement with the client device.
That is, when the client attempts to connect with this device, it carries a UUID that uniquely
identifies the service with which it wants to connect. These UUIDs must match in order for
the connection to be accepted.

A UUID is a standardized 128-bit format for a string ID used to uniquely identify


information. The point of a UUID is that it's big enough that you can select any random ID
and it doesn't clash with any other ID. In this case, it's used to uniquely identify your app's
Bluetooth service. To get a UUID to use with your app, you can use one of the many
random UUID generators on the web, then initialize a UUID with fromString(String).
2. Start listening for connection requests by calling accept().

This is a blocking call. It returns when either a connection has been accepted or an exception
has occurred. A connection is accepted only when a remote device has sent a connection
request containing a UUID that matches the one registered with this listening server socket.
When successful, accept() returns a connected BluetoothSocket.
3. Unless you want to accept additional connections, call close().

This method call releases the server socket and all its resources, but doesn't close the
connected BluetoothSocket that's been returned by accept(). Unlike TCP/IP, RFCOMM
allows only one connected client per channel at a time, so in most cases it makes sense to
call close() on the BluetoothServerSocket immediately after accepting a connected socket.

Because the accept() call is a blocking call, do not execute it in the main activity UI thread.
Executing it in another thread ensures that your app can still respond to other user
interactions. It usually makes sense to do all work that involves
a BluetoothServerSocket or BluetoothSocket in a new thread managed by your app. To abort
a blocked call such as accept(), call close() on
the BluetoothServerSocket or BluetoothSocket from another thread. Note that all methods on
a BluetoothServerSocket or BluetoothSocket are thread-safe.

Android Wifi Working

Android allows applications to access to view the access the state of the wireless
connections at very low level. Application can access almost all the information of a wifi
connection.
The information that an application can access includes connected network's link speed,IP
address, negotiation state, other networks information. Applications can also scan, add, save,
terminate and initiate Wi-Fi connections.
Android provides WifiManager API to manage all aspects of WIFI connectivity. We can
instantiate this class by calling getSystemService method. Its syntax is given below −

WifiManager mainWifiObj;
mainWifiObj = (WifiManager) getSystemService(Context.WIFI_SERVICE);

In order to scan a list of wireless networks, you also need to register your
BroadcastReceiver. It can be registered using registerReceiver method with argument of
your receiver class object. Its syntax is given below −

class WifiScanReceiver extends BroadcastReceiver {


public void onReceive(Context c, Intent intent) {
}
}
WifiScanReceiver wifiReciever = new WifiScanReceiver();
registerReceiver(wifiReciever, new
IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));

The wifi scan can be start by calling the startScan method of the WifiManager class. This
method returns a list of ScanResult objects. You can access any object by calling
the get method of list. Its syntax is given below −
List<ScanResult> wifiScanList = mainWifiObj.getScanResults();
String data = wifiScanList.get(0).toString();

What is Accelerometer in Mobile Phone?


The accelerometer in smartphone measures the linear acceleration of the device. When at rest
position in whatever orientation, the figure represents the force of gravity active on the device
at the same time it also measures the acceleration on the X and Y axis which will be zero.

What is The Accelerometer Used for in Mobile Devices

Motion Input
The sensor is available in high-end mobile phones. If you own a keypad based mobile phone
then you won’t be able to experience this sensor. You must have a smartphone to see how
accelerometer helps in changing the orientation of your mobile app.

Personal digital assistants and digital audio players control the user interface of the mobile
app with the help of an accelerometer. It adjusts the orientation of content and presentation of
the mobile app to make it user-friendly.

As accelerometer in smartphone can track the movement, it is used as a pedometer to count


steps, and based on the step it enables users to with the detailed analysis of how many
calories burnt, how many kilometers they walked, and more. Thus, the sensor widely used in
health & fitness applications and sports apps.

Orientation Sensing
Most of the smartphones use accelerometer these days to align the screen orientation
depending on the direction of the device is held. With the inbuilt mobile phone
accelerometer, users can get a better viewing experience while turning the page, playing
gesture-based games, adjusting from landscape to portrait orientation, and zoom-out & zoom-
in on the images.

The accelerometer in smartphone comprises at least a tilt sensor to manage the view of the
images. Sometimes, it is used with the purpose to correct shake while taking pictures, auto-
rotation of images, play motion-sensitive mini-games.

Gyroscope Sensor
Gyro sensor is present in your smartphone to sense angular rotational velocity and
acceleration. Simply put, all those mobile games, we are able to play using motion sense in
our phones, tablets, etc, is due to a Gyroscope Sense. Similarly, it is required in a smartphone
to be able to watch 360-degree videos or photos. The photo or the video moves, when we
move our phone due to the presence of Gyroscope.

Applications of Gyroscope in Smartphone

 Motion-sensing GUI

Gyroscope in a smartphone provides a GUI that enables a user to select menus etc by tilting
the phone. One can deflect the phone slightly to go up and down the contact list. It enables a
smartphone to trigger preset commands basis different motions. For instance, one can shake
the phone to lock it.

 Answer phone/open website

A Gyro sensor in your phone provides the ability to answer your phone, or open a website by
present commands such as rotating, gently shaking the phone 2 to 3 times, etc.

 Image stabilization

Image stabilization is one of the applications of a Gyroscope in your smartphone and it


prevents the trembling of the hand from affecting the quality of the image. It enables the
phone to record the actions, during the pressing of the shutter, in order to help catch more
clear photos. It eliminates the effect of vibrations on both photos and videos.

 GPS-inertial navigation

In case of a lost service or network, in tunnels or underground roads, the GPS continues to
help navigate the car with the help of Gyroscope.

 Motion-sensing control game


Apple with its iPhone 4 launch made Gyroscope the core of motion gaming. It enables the
developer to control the game via the detection of action. It enables you to use your phone as
a steering wheel while driving a car in a game, or a jet, etc. The game replicates the moments
you do with your phone and hence controls games with a motion sense.

You might also like