MAD altra Lecture Notes
MAD altra Lecture Notes
2. Fundamental
3. Android OS
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
Web services and Parsing, JSON Parsing, Access web data with JSON, Connect
to Web Services, Using Async Task & Third Party Library : Retrofit
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
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
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 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.
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.
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.
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.
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.
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.
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:
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);
Update Rows
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
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:
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.
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
Open HelloGridView.java and insert the following code for the onCreate()method:
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).
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.
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:
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.
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:
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:
What is Listview. Write a java class to add any 10 items within Listview.
Basically we create a ListView class and use TextView objects for each row. Each planet name is
rendered in a
TextView.
Our ListView is defined in the main layout file (res/layout/main.xml) within a LinearLayout.
The resource ID of the ListViewis mainListView, which we will use to get a reference to the
ListViewin our Activity class.
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.
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 ;
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()
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
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.
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.
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.
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.
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.
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.
</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:
<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.
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
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:
Once the activity has been called, the file key.xml will be created with the provided data.
This code violates several best practices.
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:
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.
Example in Java:
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:
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();
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.
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.
If the user Accepts the permissions, the app is installed. Else the app installation is
canceled.
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
JSON Parsing
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.
@Override
try {
String name =
c.getString("name"); String email
= c.getString("email"); String
address = c.getString("address");
String gender =
c.getString("gender");
JSONObject phone =
c.getJSONObject("phone"); String
mobile = phone.getString("mobile");
String home =
phone.getString("home"); String office
= phone.getString("office");
contact.put("name", name);
contact.put("email", email);
contact.put("mobile", mobile);
@Override
Toast.LENGTH_LONG).show();
});
} else {
});
return null;
KXmlParserviaXmlPullParserFactory.newPullParser()
ExpatPullParser, via Xml.newPullParser()
XML Parsing
<?xml version="1.0"?>
<current>
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.
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
HTTP Response
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.
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 −
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 −
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;
@Override
try {
InputStream is = getAssets().open("file.xml");
DocumentBuilderFactory dbFactory =
DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder =
dbFactory.newDocumentBuilder();
Element element=doc.getDocumentElement();
element.normalize();
NodeList nList =
doc.getElementsByTagName("employee"); for (int
i=0; i<nList.getLength(); i++) {
if (node.getNodeType() ==
Node.ELEMENT_NODE) { Element
element2 = (Element) node;
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.
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.
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 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
<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<!--Permissions-->
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyDKymeBXNeiFWY5jRUejv6zItpmr2MVyQ0" />
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 −
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);
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.
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;
// Add the ImageView to the layout and set the layout as the content view
mLinearLayout.addView(i);
setContentView(mLinearLayout);
}
Create if not:
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
clearAnimation() This method will clear the animation running on a specific view.
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;
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");
finalTime = mediaPlayer.getDuration();
startTime = mediaPlayer.getCurrentPosition();
if (oneTimeOnly == 0) {
seekbar.setMax((int) finalTime);
oneTimeOnly = 1;
}
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();
}
}
});
}
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
We will see the implementation of CRUD one by one. Just open your DatabaseHandler.kt
and the following.
CREATE/INSERT Data
UPDATE Data
DELETE Data
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.
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:
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:
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.
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.
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.
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:
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 application for release is a multi-step process that involves the following
tasks:
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.
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.
Before you distribute your application, you should thoroughly test the release version on at
least one target handset device and one target tablet device.
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.
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.
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.
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:
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.
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.
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.
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.
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;
}
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.
@Override
public void onPictureTaken(byte[] data, Camera camera) {
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());
}
}
};
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:
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.
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 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 −
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();
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.
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.
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.
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
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.