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

Notes MAD

The document provides information about various Android UI components like ProgressBar, ScrollView, ListView, GridView, DatePicker, TimePicker and also covers concepts like Intent and Intent Filters. It explains how to use these components and concepts in Android applications.
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)
19 views

Notes MAD

The document provides information about various Android UI components like ProgressBar, ScrollView, ListView, GridView, DatePicker, TimePicker and also covers concepts like Intent and Intent Filters. It explains how to use these components and concepts in Android applications.
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/ 68

NOTES FOR MAD

Progress Bar

In Android, ProgressBar is used to display the status of work being done like analyzing
status of work or downloading a file etc. In Android, by default a progress bar will be
displayed as a spinning wheel but If we want it to be displayed as a horizontal bar then we
need to use style attribute as horizontal.
A progress bar can also be made indeterminate. In this mode a progress bar shows a cyclic
animation without an indication of progress. This mode is used in application when we don’t
know the amount of work to be done.
By default, a progress bar is a spinning wheel (an indeterminate indicator). To change to a
horizontal progress bar, apply the progress bar’s horizontal style.

Scroll View

ScrollView is used to scroll the items in vertical direction. If you want to scroll the items
horizontally then you need to implement horizontal ScrollView. You can scroll the elements
or views in both vertical and horizontal directions. To scroll in Vertical we simply use
ScrollView and to scroll in horizontal direction we need to use HorizontalScrollview.

Remember ScrollView can hold only one direct child. So we have to jointly put n buttons
inside Linear Layout to make it one child. And then we put it inside ScrollView.

List view

List of scrollable items can be displayed in Android using ListView. It helps you to displaying
the data in the form of a scrollable list. Users can then select any list item by clicking on it.
ListView is default scrollable so we do not need to use scroll View or anything else with
ListView.

ListView is widely used in android applications. A very common example of ListView is your
phone contact book, where you have a list of your contacts displayed in a ListView and if you
click on it then user information is displayed.

To fill the data in a ListView we simply use adapters. List items are automatically inserted to
a list using an Adapter that pulls the content from a source such as an arraylist, array or
database.

An adapter is a bridge between UI component and data source that helps us to fill data in UI
component. It holds the data and send the data to adapter view then view can takes the data
from the adapter view and shows the data on different views like as list view, grid view,
spinner etc.

ListView is a subclass of AdapterView and it can be populated by binding to an Adapter,


which retrieves the data from an external source and creates a View that represents each
data entry.

In android commonly used adapters are:

1. Array Adapter
2. Base Adapter
NOTES FOR MAD

Grid View

In android GridView is a view group that display items in two dimensional scrolling grid (rows
and columns), the grid items are not necessarily predetermined but they are automatically
inserted to the layout using a ListAdapter. Users can then select any grid item by clicking on
it. GridView is default scrollable so we don’t need to use ScrollView or anything else with
GridView.
GridView is widely used in android applications. An example of GridView is your default
Gallery, where you have number of images displayed using grid.
numColumns property has to be specified otherwise GridView behaves like a ListView with
just singleChoice. If numColumns property specified that there is 3 columns to show, if we
set it to auto_fit then it automatically display as many column as possible to fill the
available space of the screen. Even if the phone is in portrait mode or landscape mode it
automatically fill the whole space.

Custom Toast Alert

In Android, Toast is used when we required to notify user about an operation without
expecting any user input. It displays a small popup for message and automatically fades out
after timeout.
In Android, Sometimes simple Toast may not be satisfactory, and then we can go for
customising a Toast.

Create a new layout file for the custom toast message. You can do this by going to res -> layout
and right-clicking to create a new layout resource file. Name the file something like
custom_toast.xml.
In the new layout file, add a TextView to display the text of the toast message. You can also add
other views like an ImageView if you want to include an image in the toast.

Time and Date picker

Android DatePicker is a user interface control which is used to select the date by day,
month and year in our android application. DatePicker is used to ensure that the users will
select a valid date.
In android DatePicker having two modes, first one to show the complete calendar and
second one shows the dates in spinner view.
We can use android:datePickerMode to show only calendar view
We can also show the DatePicker in spinner format like selecting the day, month and year
separately, by using android:datePickerMode attribute and set
android:calendarViewShown=”false”, otherwise both spinner and calendar can be seen
simultaneously.

Android TimePicker is a user interface control for selecting the time in either 24-hour format or
AM/PM mode. It is used to ensure that users pick the valid time for the day in our application.
NOTES FOR MAD

In android, TimePicker is available in two modes first one is clock mode and another one is
spinner mode.
We can use android:timePickerMode to show only clock view
We can also use the TimePicker in spinner format by using android:timePickerMode attribute.

UNIT V

Intent
In Android, it is quite usual for users to witness a jump from one application to another as a
part of the whole process, for example, searching for a location on the browser and
witnessing a direct jump into Google Maps or receiving payment links in Messages
Application (SMS) and on clicking jumping to PayPal or GPay (Google Pay). This process of
taking users from one application to another is achieved by passing the Intent to the
system. Intents, in general, are used for navigating among various activities within the
same application, but note, is not limited to one single application, i.e., they can be utilised
from moving from one application to another as well.
Intents could be Implicit, for instance, calling intended actions, and explicit as well, such as
opening another activity after some operations like onClick or anything else. Below are
some applications of Intents:

1. Sending the User to Another App

2. Getting a Result from an Activity

3. Allowing Other Apps to Start Your Activity

Types of Android Intents

There are two types of intents in android


1. Implicit

2. Explicit

An Intent is a messaging object you can use to request an action from another app
component. Although intents facilitate communication between components in several ways,
there are three fundamental use cases:

● Starting an activity
An Activity represents a single screen in an app. You can start a new instance of
an Activity by passing an Intent to startActivity(). The Intent describes
NOTES FOR MAD

the activity to start and carries any necessary data.


If you want to receive a result from the activity when it finishes, call
startActivityForResult(). Your activity receives the result as a separate
Intent object in your activity's onActivityResult() callback. For more
information, see the Activities guide.
● Starting a service
A Service is a component that performs operations in the background without a
user interface. With Android 5.0 (API level 21) and later, you can start a service with
JobScheduler. For more information about JobScheduler, see its
API-reference documentation.
For versions earlier than Android 5.0 (API level 21), you can start a service by using
methods of the Service class. You can start a service to perform a one-time
operation (such as downloading a file) by passing an Intent to startService().
The Intent describes the service to start and carries any necessary data.
If the service is designed with a client-server interface, you can bind to the service
from another component by passing an Intent to bindService(). For more
information, see the Services guide.
● Delivering a broadcast
A broadcast is a message that any app can receive. The system delivers various
broadcasts for system events, such as when the system boots up or the device starts
charging. You can deliver a broadcast to other apps by passing an Intent to
sendBroadcast() or sendOrderedBroadcast().

Intent Filter

An intent filter is a way of declaring the capabilities of an app component, such as an activity,
service, or broadcast receiver. It specifies the types of intents that the component can
receive, based on the intent’s action, data, and category. For example, an activity that can
show a location on a map can have an intent filter that accepts intents with the action
ACTION_VIEW and the data geo

An intent filter is an expression in an app's manifest file that specifies the type of intents
that the component would like to receive
When you create an implicit intent, the Android system finds the appropriate component
to start by comparing the contents of the intent to the intent filters declared in the
manifest file of other apps on the device. If the intent matches an intent filter, the system
starts that component and delivers it the Intent object.
If multiple intent filters are compatible, the system displays a dialog so the user can pick
which app to use.
intent filters are generally associated with implicit intents, they are not required for explicit
intents where the target component is explicitly specified.
NOTES FOR MAD

1. Explicit Intents are used to call a specific component. When you know which
component you want to launch and you do not want to give the user free
control over which component to use.For example, you have an application
that has 2 activities. Activity A and activity B. You want to launch activity B
from activity A. In this case you define an explicit intent targeting activityB
and then use it to directly call it.
2. Implicit Intents are used when you have an idea of what you want to do, but
you do not know which component should be launched. Or if you want to
give the user an option to choose between a list of components to use. If
these Intents are send to the Android system it searches for all components
which are registered for the specific action and the data type. If only one
component is found, Android starts the component directly. For example, you
have an application that uses the camera to take photos. One of the features
of your application is that you give the user the possibility to send the photos
he has taken. You do not know what kind of application the user has that can
send photos, and you also want to give the user an option to choose which
external application to use if he has more than one. In this case you would
not use an explicit intent. Instead you should use an implicit intent that has
its action set to ACTION_SEND and its data extra set to the URI(Uniform
Resource Identifier) of the photo.
An explicit intent is always delivered to its target, no matter what it contains;
the filter is not consulted. But an implicit intent is delivered to a component
only if it can pass through one of the component's filters

Activity Lifecycle

The activity lifecycle refers to the sequence of states that an activity goes through
during its entire existence.
The Activity class provides a number of callbacks that let the activity know when a state
changes or that the system is creating, stopping, or resuming an activity or destroying the
process the activity resides in.
Within the lifecycle callback methods, we can declare how your activity behaves when the
user leaves and re-enters the activity. For example, if you're building a streaming video
player, you might pause the video and terminate the network connection when the user
switches to another app. When the user returns, you can reconnect to the network and let
the user resume the video from the same spot.

The main states of activity lifecycle are-

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, perform basic application startup logic that happens only once
for the entire life of the activity.
NOTES FOR MAD

If you have a lifecycle-aware component that is hooked up to the lifecycle of your


activity, it receives the ON_CREATE event.

Your activity does not remain 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 onStart(). This 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 code that
maintains the UI is initialized.

When the activity moves to the Started state, any lifecycle-aware component tied to
the activity's lifecycle receives the ON_START event.

The onStart() method completes quickly and, as with the Created state, the
activity does not remain 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 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 as the device receiving a phone call, the user
navigating to another activity, or the device screen turning off.

When the activity moves to the Resumed state, any lifecycle-aware component tied
to the activity's lifecycle receives the ON_RESUME event.

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 the onResume() method. For this reason, implement onResume() to
initialize components that you release during onPause() and to perform any other
initializations that must occur each time the activity enters the Resumed state.

If you want the camera active only when the app is Resumed (visible and active in
the foreground), then initialize the camera after the ON_RESUME event demonstrated
previously. If you want to keep the camera active while the activity is Paused but
NOTES FOR MAD

visible, such as in multi-window mode, then initialize the camera after the ON_START
event.

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. It indicates
that the activity is no longer in the foreground, but it is still visible if the user is in
multi-window mode. There are several reasons why an activity might enter this state:

● An event that interrupts app execution, as described in the section about the
onResume() callback, pauses the current activity. This is the most common
case.
● In multi-window mode, only one app has focus at any time, and the system
pauses all the other apps.
● The opening of a new, semi-transparent activity, such as a dialog, pauses the
activity it covers. As long as the activity is partially visible but not in focus, it
remains paused.

When an activity moves to the Paused state, any lifecycle-aware component tied to
the activity's lifecycle receives the ON_PAUSE event. This is where the lifecycle
components can stop any functionality that does not need to run while the
component is not in the foreground, such as stopping a camera preview.

onStop()

When your activity is no longer visible to the user, it enters the Stopped state, and
the system invokes the onStop() callback. This can occur when a newly launched
activity covers the entire screen. The system also calls onStop() when the activity
finishes running and is about to be terminated.

When the activity moves to the Stopped state, any lifecycle-aware component tied to
the activity's lifecycle receives the ON_STOP event. This is where the lifecycle
components can stop any functionality that does not need to run while the
component is not visible on the screen.

In the onStop() method, release or adjust resources that are not needed while the
app is not visible to the user. For example, your app might pause animations or
switch from fine-grained to coarse-grained location updates. Using onStop()
instead of onPause() means that UI-related work continues, even when the user is
viewing your activity in multi-window mode.
NOTES FOR MAD

Also, use onStop() to perform relatively CPU-intensive shutdown operations. For


example, if you can't find a better time to save information to a database, you might
do so during onStop().

From the Stopped state, the activity either comes back to interact with the user, or
the activity is finished running and goes away. If the activity comes back, the system
invokes onRestart(). If the Activity is finished running, the system calls
onDestroy().

onDestroy()

onDestroy() is called before the activity is destroyed. The system invokes this
callback for one of two reasons:

1. The activity is finishing, due to the user completely dismissing the activity or
due to finish() being called on the activity.
2. The system is temporarily destroying the activity due to a configuration
change, such as device rotation or entering multi-window mode.

When the activity moves to the destroyed state, any lifecycle-aware component tied
to the activity's lifecycle receives the ON_DESTROY event. This is where the lifecycle
components can clean up anything they need to before the Activity is destroyed.

As the user begins to leave the activity, the system calls methods to dismantle the
activity. In some cases, the activity is only partially dismantled and still resides in
memory, such as when the user switches to another app. In these cases, the activity
can still come back to the foreground.

Saving and restoring transient UI state


A user expects an activity’s UI state to remain the same throughout a configuration
change, such as rotation or switching into multi-window mode. However, the system
destroys the activity by default when such a configuration change occurs, wiping
away any UI state stored in the activity instance.

Similarly, a user expects UI state to remain the same if they temporarily switch away
from your app to a different app and then come back to your app later. However, the
system can destroy your application’s process while the user is away and your
activity is stopped.
NOTES FOR MAD

Broadcast Lifecycle

Android apps can send or receive broadcast messages from the Android system and
other Android apps
Apps can register to receive specific broadcasts. When a broadcast is sent, the
system automatically routes broadcasts to apps that have subscribed to receive that
particular type of broadcast.

Creating the Broadcast Receiver:

class AirplaneModeChangeReceiver:BroadcastReceiver() {

override fun onReceive(context: Context?, intent: Intent?) {

// logic of the code needs to be written here

Registering a BroadcastReceiver:

IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED).also {

// receiver is the broadcast receiver that we have registered

// and it is the intent filter that we have created

registerReceiver(receiver,it)

Broadcast in android is the system-wide events that can occur when the
device starts, when a message is received on the device or when incoming
calls are received, or when a device goes to airplane mode, etc. Broadcast
Receivers are used to respond to these system-wide events. Broadcast
Receivers allow us to register for the system and application events, and
when that event happens, then the register receivers get notified. There are
mainly two types of Broadcast Receivers:
NOTES FOR MAD

● Static Broadcast Receivers: These types of Receivers are declared

in the manifest file and works even if the app is closed.

● Dynamic Broadcast Receivers: These types of receivers work only if

the app is active or minimized.

For example:

● Static: Used when you want to listen to an event all the time (e.g., battery status
changes).
● Dynamic: Used when you want to bring up the receiver with certain conditions (e.g., SMS
handling while the app is running)

Following are some of the important system-wide generated intents:-

Description Of
Intent
Event

Indicates low
battery
android.intent.action.BATTERY_LOW :
condition on
the device.

This is
broadcast once
after the
android.intent.action.BOOT_COMPLETED
system has
finished
booting
NOTES FOR MAD

To perform a
call to
android.intent.action.CALL someone
specified by
the data

Indicates that
android.intent.action.DATE_CHANGED the date has
changed

Indicates that
android.intent.action.REBOOT the device has
been a reboot

The mobile
network or wifi
android.net.conn.CONNECTIVITY_CHANGE connection is
changed(or
reset)

This indicates
that airplane
android.intent.ACTION_AIRPLANE_MODE_CHANGED mode has been
switched on or
off.

A broadcast receiver has single callback method: onReceive()


NOTES FOR MAD

Content Providers
In Android, Content Providers are a very important component that serves
the purpose of a relational database to store the data of applications. The
role of the content provider in the android system is like a central repository
in which data of the applications are stored, and it facilitates other
applications to securely access and modifies that data based on the user
requirements. Android system allows the content provider to store the
application data in several ways. Users can manage to store the application
data like images, audio, videos, and personal contact information by storing
them in SQLite Database, in files, or even on a network. In order to share
the data, content providers have certain permissions that are used to grant or
restrict the rights to other applications to interfere with the data.

Content URI(Uniform Resource Identifier) is the key concept of Content


providers. To access the data from a content provider, URI is used as a query
string.

Structure of a Content URI: content://authority/optionalPath/optionalID

Details of different parts of Content URI:


NOTES FOR MAD

● content:// – Mandatory part of the URI as it represents that the

given URI is a Content URI.

● authority – Signifies the name of the content provider like contacts,

browser, etc. This part must be unique for every content provider.

● optionalPath – Specifies the type of data provided by the content

provider. It is essential as this part helps content providers to

support different types of data that are not related to each other like

audio and video files.

● optionalID – It is a numeric value that is used when there is a need

to access a particular record.

Operations in Content Provider

Four fundamental operations are possible in Content Provider namely Create,


Read, Update, and Delete. These operations are often termed as CRUD
operations.

Working of the Content Provider

UI components of android applications like Activity and Fragments use an


object CursorLoader to send query requests to ContentResolver. The
ContentResolver object sends requests (like create, read, update, and delete)
to the ContentProvider as a client. After receiving a request, ContentProvider
process it and returns the desired result. Below is a diagram to represent
these processes in pictorial form.
NOTES FOR MAD

Fragments
Fragment is a piece of an activity that enables a more modular activity
design. A fragment encapsulates functionality so that it is easier to reuse
within activities and layouts. Android devices exist in a variety of screen sizes
and densities. Fragments simplify the reuse of components in different
layouts and their logic. You can build single-pane layouts for handsets
(phones) and multi-pane layouts for tablets. You can also use fragments also
to support different layouts for landscape and portrait orientation on a
smartphone. The below image shows how two UI modules defined by
fragments can be combined into one activity for a tablet design but separated
for a handset design.
NOTES FOR MAD

Android fragments have their own life cycle very similar to an android
activity.

● onAttach() : The fragment instance is associated with an activity

instance. The fragment and the activity is not fully initialized.

Typically you get in this method a reference to the activity which

uses the fragment for further initialization work.

● onCreate() : The system calls this method when creating the

fragment. You should initialize essential components of the

fragment that you want to retain when the fragment is paused or

stopped, then resumed.


NOTES FOR MAD

● onCreateView() : The system calls this callback when it’s time for

the fragment to draw its user interface for the first time. To draw a

UI for your fragment, you must return a View component from this

method that is the root of your fragment’s layout. You can return

null if the fragment does not provide a UI.

● onActivityCreated() : The onActivityCreated() is called after the

onCreateView() method when the host activity is created. Activity

and fragment instance have been created as well as the view

hierarchy of the activity. At this point, view can be accessed with the

findViewById() method. example. In this method you can instantiate

objects which require a Context object

● onStart() : The onStart() method is called once the fragment gets

visible.

● onResume() : Fragment becomes active.

● onPause() : The system calls this method as the first indication that

the user is leaving the fragment. This is usually where you should

commit any changes that should be persisted beyond the current

user session.

● onStop() : Fragment going to be stopped by calling onStop()

● onDestroyView() : Fragment view will destroy after call this

method

● onDestroy() :called to do final clean up of the fragment’s state but

Not guaranteed to be called by the Android platform.


NOTES FOR MAD

Types of Fragments

● Single frame fragments : Single frame fragments are using for

hand hold devices like mobiles, here we can show only one

fragment as a view.

● List fragments : fragments having special list view is called as list

fragment

● Fragments transaction : Using with fragment transaction. we can

move one fragment to another fragment.

Fragment transactions are a way of adding, removing, or replacing fragments


in an activity at runtime. They allow you to create dynamic and flexible user
interfaces that adapt to different screen sizes and orientations.

Handling the Fragment Lifecycle

A Fragment exist in three states:

● Resumed : The fragment is visible in the running activity.

● Paused : Another activity is in the foreground and has focus, but the

activity in which this fragment lives is still visible (the foreground

activity is partially transparent or doesn’t cover the entire screen).

● Stopped : The fragment is not visible. Either the host activity has

been stopped or the fragment has been removed from the activity

but added to the back stack. A stopped fragment is still alive (all

state and member information is retained by the system). However,

it is no longer visible to the user and will be killed if the activity is

killed.
NOTES FOR MAD

The effect of the activity lifecycle on the fragment lifecycle :


NOTES FOR MAD
NOTES FOR MAD

Services in Android with Example


Services in Android are a special component that facilitates an application to
run in the background in order to perform long-running operation tasks. The
prime aim of a service is to ensure that the application remains active in the
background so that the user can operate multiple applications at the same
time. A user-interface is not desirable for android services as it is designed to
operate long-running processes without any user intervention. A service can
run continuously in the background even if the application is closed or the
user switches to another application. Further, application components can
bind itself to service to carry out inter-process communication(IPC).

There is a major difference between android services and threads, one must
not be confused between the two. Thread is a feature provided by the
Operating system to allow the user to perform operations in the background.
While service is an android component that performs a long-running
operation about which the user might not be aware of as it does not have UI.

Types of Android Services


NOTES FOR MAD

1. Foreground Services:

Services that notify the user about its ongoing operations are termed as
Foreground Services. Users can interact with the service by the
notifications provided about the ongoing task. Such as in downloading a
file, the user can keep track of the progress in downloading and can also
pause and resume the process.

2. Background Services:

Background services do not require any user intervention. These services


do not notify the user about ongoing background tasks and users also
cannot access them. The process like schedule syncing of data or storing
of data fall under this service.

3. Bound Services:

This type of android service allows the components of the application like
activity to bound themselves with it. Bound services perform their task as
long as any application component is bound to it. More than one
component is allowed to bind themselves with a service at a time. In order
to bind an application component with a service bindService() method is
used.

The Life Cycle of Android Services

In android, services have 2 possible paths to complete its life cycle namely
Started and Bounded.

1. Started Service (Unbounded Service):


By following this path, a service will initiate when an application
component calls the startService() method. Once initiated, the service can
run continuously in the background even if the component is destroyed
which was responsible for the start of the service. Two option are
available to stop the execution of service:

● By calling stopService() method,

● The service can stop itself by using stopSelf() method.


NOTES FOR MAD

2. Bounded Service:
It can be treated as a server in a client-server interface. By following this
path, android application components can send requests to the service
and can fetch results. A service is termed as bounded when an application
component binds itself with a service by calling bindService() method. To
stop the execution of this service, all the components must unbind
themselves from the service by using unbindService() method.

To carry out a downloading task in the background, the startService()


method will be called. Whereas to get information regarding the
download progress and to pause or resume the process while the
application is still in the background, the service must be bounded with a
component which can perform these tasks.

Fundamentals of Android Services

A user-defined service can be created through a normal class which is


extending the class Service. Further, to carry out the operations of service
on applications, there are certain callback methods which are needed to
NOTES FOR MAD

be overridden. The following are some of the important methods of


Android Services:

Methods Description

The Android service calls this method when a


component(eg: activity)

onStartCommand requests to start a service using startService(). Once


() the service is started,

it can be stopped explicitly using stopService() or


stopSelf() methods.

This method is mandatory to implement in android


service and is invoked

whenever an application component calls the


bindService() method in order to

onBind()
bind itself with a service. User-interface is also
provided to communicate

with the service effectively by returning an IBinder


object.
NOTES FOR MAD

If the binding of service is not required then the


method must return null.

The Android system invokes this method when all


the clients
onUnbind()

get disconnected from a particular service interface.

Once all clients are disconnected from the particular


interface of service and

onRebind()
there is a need to connect the service with new
clients, the system calls this method.

Whenever a service is created either using


onStartCommand() or onBind(),

onCreate() the android system calls this method. This method


is necessary to perform

a one-time-set-up.
NOTES FOR MAD

When a service is no longer in use, the system


invokes this method

just before the service destroys as a final clean up


call. Services must
onDestroy()

implement this method in order to clean up


resources like registered listeners,

threads, receivers, etc.

Example of Android Services

Playing music in the background is a very common example of services in


android. From the time when a user starts the service, music play
continuously in the background even if the user switches to another
application. The user has to stop the service explicitly in order to pause
the music. Below is the complete step-by-step implementation of this
android service using a few callback methods.

Android System Architecture


The Android software stack generally consists of a Linux kernel and a
collection of C/C++ libraries that are exposed through an application
framework that provides services, and management of the applications
and run time.

Linux Kernel
NOTES FOR MAD

Android was created on the open-source kernel of Linux. One main reason
for choosing this kernel was that it provided proven core features on
which to develop the Android operating system. The features of the Linux
kernel are:

1. Security: The Linux kernel handles the security between the application
and the system.

2. Memory Management: It efficiently handles memory management


thereby providing the freedom to develop our apps.

3. Process Management: It manages the process well and allocates


resources to processes whenever they need them.

4. Network Stack: It effectively handles network communication.

5. Driver Model: It ensures that the application works. Hardware


manufacturers can build their drivers into the Linux build.

Libraries:
Running on top of the kernel, the Android framework was developed with
various features. It consists of various C/C++ core libraries with numerous
open-source tools. Some of these are:

1. The Android Runtime: The Android runtime consists of core libraries of


Java and ART(the Android RunTime). Older versions of Android (4.x and
earlier) had Dalvik runtime.

2. Open GL(graphics library): This cross-language, cross-platform


application program interface (API) is used to produce 2D and 3D
computer graphics.

3. WebKit: This open-source web browser engine provides all the


functionality to display web content and simplify page loading.

4. Media frameworks: These libraries allow you to play and record audio
and video.

5. Secure Socket Layer (SSL): These libraries are there for Internet
security.
NOTES FOR MAD

Android Runtime
It is the third section of the architecture. It provides one of the key
components which is called Dalvik Virtual Machine. It acts like Java Virtual
Machine which is designed especially for Android. Android uses its own
custom VM designed to ensure that multiple instances run efficiently on a
single device.

The Dalvik VM uses the device’s underlying Linux kernel to handle


low-level functionality, including security, threading, and memory
management.

Application Framework
The Android team has built on a known set of proven libraries, built in the
background, and all of it is exposed through Android interfaces. These
interfaces wrap up all the various libraries and make them useful for the
Developer. They don’t have to build any of the functionality provided by
the android. Some of these interfaces include:

1. Activity Manager: It manages the activity lifecycle and the activity stack.

2. Telephony Manager: It provides access to telephony services as related


subscriber information, such as phone numbers.

3. View System: It builds the user interface by handling the views and
layouts.

4. Location manager: It finds the device’s geographic location.

Applications:
Android applications can be found at the topmost layer. At the application
layer, we write our application to be installed on this layer only. Examples
of applications are Games, Messages, Contacts, etc.

Multimedia Framework in Android


Android multimedia framework is designed to provide a reliable interface
for java service. It is a system that includes multimedia applications,
frameworks, an OpenCore engine, hardware devices for audio/video/ input,
NOTES FOR MAD

output devices also several core dynamic libraries such as libmedia,


libmediaplayservices, and so on.

The Media Server creates the corresponding media service to the


multimedia application. The communication between the media server and
Libmedia forms a client-server model. The PV player processes the media
data stream by demuxing the media data to separate the video/audio data
stream, decode video/audio data, sync video, and audio time, and send the
decoded data out.

The Android Multimedia framework is a set of APIs for developers which


enables them to create a multimedia application on an android platform.
This framework provides support for audio, video, and images, which
provides a range of features such as media playback, recording, editing,
streaming, etc.

Components of Android Multimedia Framework

1. Media Codec

It provides low-level access to hardware and software codecs for encoding


and decoding audio and video data. Format of media codec/format,
container, and network protocol supported by the android platform-
NOTES FOR MAD

● Container: It is used to store audio file format on a system, where

data can be manipulated to reduce the size or change the quality

of audio.

● Audio Format: Any format or codec can be used including the

ones provided by android devices. However, it is recommended to

use the specified file formats as per devices.

● Network Protocol: Protocols supported in audio and video

playback are RTSP, HTTP/HTTPS progressive streaming, and live

streaming draft protocol.

Common media codec formats used in android multimedia applications


include

● H.264: Widely used video codec format that provides

high-quality compression and is supported by most modern

devices and software.

● AAC: Popular audio codec format that provides high-quality

compression and is widely supported by devices and software.

● MP3: Well-known audio codec format that provides good

compression and is supported by most devices and software.

● VP9: Video codec format that provides high-quality compression

and is supported by some modern devices and software.

● JPEG: Image codec format that provides good compression and is

widely supported by devices and software.

● PNG: Image codec format That provides lossless compression

which is supported by devices and software.


NOTES FOR MAD

2. Media Player

It is a component in the multimedia framework that provides high-level


access to the media playback functionality of Android that enables
developers to play audio/video files and stream. It is also a core
component of the Android multimedia framework that enables developers
to play audio and video files in their applications and provides a simple
and flexible API for playing media files from different sources. The sources
are local files, network streams, and content providers. Media player
supports a wide range of audio and video formats which includes MP3,
AAC, WAV, MPEG-4, H.264, etc.

Some key features of media players are:

● Playback control: This helps in controlling media files by

providing a range of methods such as start(), pause(), stop(), and

seekTo().

● Playback State: This feature informs the developer about the

playback state by providing functions that are onPrepared(),

onCompletion(), and onError().

● Audio Focus: This feature comes into the picture when multiple

audio sources are playing simultaneously and the developer has

to manage all of it.

● Media Streaming: The media player supports streaming media

from various sources such as HTTP, RTSP, and RTP so to handle

the streaming media developers use setDataSourse() method to

set the source for streaming media and use the prepareAsync()

method to prepare the media player for asynchronous playback.

● Media Playback with the surface: To set the surface on which the

video should be rendered setSurface() is used.


NOTES FOR MAD

3. Media Recorder

Provides high-level access to the media recording functionality of Android


which allows developers to capture audio/video data from a device’s
microphone and camera. It provides a simple and flexible API for recording
media from different sources such as the device’s microphone or camera.
Features of the media recorder are:

● Recording control: This feature provides methods like start(),

stop(), and reset() for controlling the recording of media files.

● Recording state: This feature enables the user to notify about the

state of recording by using methods onInfo() and onError().

● Audio and Video Sources: This feature provides two methods

setAudioSource and setVideoSource() which enable developers

to select appropriate audio and video sources for their recordings.

● Audio and Video Encoding: For video formatting, this feature

contains methods such as setOutputFormat() method.

setAudioEncoder() and setVideoEncoder() methods are used to

select appropriate encoding for audio and video.

4. Surface View

The surface provides a facility to play video content on android devices. It


is a subclass of the view class and provides a dedicated drawing surface
for applications that need to display video or graphics which are more
complicated than simple views. Feature of Surface View:

● Drawing surface: This feature is used by developers to draw

complex graphics or display video frames.

● Efficient rendering: This is used when developers when designing

efficient rendering is needed and provides better performance


NOTES FOR MAD

compared to other View classes when rendering large images or

video frames.

● Compatibility with Android Graphics Framework: It is compatible

with OpenGL ES, which is a 3D graphics library that can be used

to create advanced multimedia applications.

5. Audio Manager

Controls the overall audio settings such as volume and routing. It allows
developers to manage audio settings and control audio playback for
various applications and devices. Functions of Audio Manager:

● Controlling Audio Volume

● Managing Audio Routing

● Handling Audio Focus

● Monitoring audio States

6. Image Reader

Provides access to raw image data from a device’s camera or image


sensors. It is a part of the android Camera2 API and is available in Android
API level 19 and higher. Function that ImageReader class include:

● Capturing raw images

● Processing captured images

● Configuring capture settings

● Handling image buffers


NOTES FOR MAD

MediaPlayer
The Android multimedia framework includes support for playing variety of common
media types, so that you can easily integrate audio, video and images into your
applications. You can play audio or video from media files stored in your application's
resources (raw resources), from standalone files in the filesystem, or from a data
stream arriving over a network connection, all using MediaPlayer APIs.

The basics

The following classes are used to play sound and video in the Android framework:

MediaPlayer

This class is the primary API for playing sound and video.

AudioManager

This class manages audio sources and audio output on a device.

Manifest declarations

Before starting development on your application using MediaPlayer, make sure your
manifest has the appropriate declarations to allow use of related features.

● Internet Permission - If you are using MediaPlayer to stream network-based


content, your application must request network access.

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

● Wake Lock Permission - If your player application needs to keep the screen
from dimming or the processor from sleeping, or uses the
NOTES FOR MAD

MediaPlayer.setScreenOnWhilePlaying() or

MediaPlayer.setWakeMode() methods, you must request this permission.

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

Asynchronous preparation

Using MediaPlayer can be straightforward in principle. However, it's important to


keep in mind that a few more things are necessary to integrate it correctly with a
typical Android application. For example, the call to prepare() can take a long time
to execute, because it might involve fetching and decoding media data. So, as is the
case with any method that may take long to execute, you should never call it from
your application's UI thread. Doing that causes the UI to hang until the method
returns, which is a very bad user experience and can cause an ANR (Application Not
Responding) error. Even if you expect your resource to load quickly, remember that
anything that takes more than a tenth of a second to respond in the UI causes a
noticeable pause and gives the user the impression that your application is slow.

To avoid hanging your UI thread, spawn another thread to prepare the


MediaPlayer and notify the main thread when done. However, while you could
write the threading logic yourself, this pattern is so common when using
MediaPlayer that the framework supplies a convenient way to accomplish this task

by using the prepareAsync() method. This method starts preparing the media in
the background and returns immediately. When the media is done preparing, the
onPrepared() method of the MediaPlayer.OnPreparedListener, configured

through setOnPreparedListener() is called.

TextToSpeech
TTS technology enables computers to convert written text into
spoken words, making it possible for devices to “speak” and
communicate with users in a more naturally and engaging way.
NOTES FOR MAD

open class TextToSpeech

kotlin.Any
↳ android.speech.tts.TextToSpeech

Synthesizes speech from text for immediate playback or to create a sound file.

A TextToSpeech instance can only be used to synthesize text once it has completed
its initialization. Implement the TextToSpeech.OnInitListener to be notified of
the completion of the initialization.
When you are done using the TextToSpeech instance, call the shutdown() method
to release the native resources used by the TextToSpeech engine. Apps targeting
Android 11 that use text-to-speech should declare
android.speech.tts.TextToSpeech.Engine#INTENT_ACTION_TTS_SERVI

CE in the queries elements of their manifest:

<queries>
...
<intent>
<action android:name="android.intent.action.TTS_SERVICE" />
</intent>
</queries>

AsyncTask
AsyncTask is an abstract class in Android that offers us the freedom to

execute demanding tasks in the background while keeping the UI thread light

and the application responsive. When launched, an Android application

operates in a single thread. Due to this single-thread approach, tasks that

take a long time to fetch a response may cause the program to become
NOTES FOR MAD

unresponsive. We use Android AsyncTask to perform these heavy tasks in

the background on a separate thread and return the results back to the UI

thread in order to prevent this. As a result, the UI thread is always responsive

when AsyncTask is used in an Android application.

The purpose of AsyncTask was to make it possible to use the UI thread

correctly and conveniently. The most frequent use case, however, was UI

integration, which led to Context leaks, missed callbacks, or crashes when

settings changed. Additionally, it behaves differently depending on the

platform version, swallows exceptions from doInBackground, and offers little

benefit over using Executors directly. AsyncTask is not intended to be a

general-purpose threading system; rather, it is intended to be a helper class

for Thread and Handler. AsyncTasks are best used for brief operations (a few

seconds at the most.) It is strongly advised that you use the various APIs

offered by the java.util.concurrent package, such as Executor,

ThreadPoolExecutor, and FutureTask, if you need to keep threads running for

extended periods of time.

Asynchronous tasks are divided into three generic types: Params, Progress,

& Result and four steps: onPreExecute, doInBackground,

onProgressUpdate, & onPostExecute. The following lists the three generic

types utilized in an Android AsyncTask class:

● Params: Parameters sent to the task upon execution

● Progress: Progress units shared during the background

computation
NOTES FOR MAD

● Result: Result obtained from the background computation

The following definitions outline the fundamental methods used in an

Android AsyncTask class:

● doInBackground(): The code that has to be run in the background is

contained in the doInBackground() method. The publishProgress()

method in this method allows us to repeatedly deliver results to the

UI thread. We only need to use the return statements to signal that

the background processing has been finished.

● onPreExecute(): The code that runs prior to the beginning of the

background processing is contained in this function.

● onPostExecute(): After the doInBackground method has finished

processing, the onPostExecute() method is called. This method

receives the output of the doInBackground method as its input.

● onProgressUpdate(): This method can use the progress updates it

receives from the publishProgress method, which publishes

progress updates from the doInBackground function, to update the

UI thread.

AsyncTask Example

The following code snippet must be present in the MainActivity class in order

to launch an AsyncTask.

MyTask myTask = new MyTask();

myTask.execute();
NOTES FOR MAD

The execute method is used to start the background thread

Audio Capture
Android features a built-in microphone that you can use to record and store sounds
or play them back on your phone. There are a few ways to accomplish this, but the
most typical is to use the MediaRecorder class.

MediaRecorder class

The MediaRecorder class in Android allows you to record audio or video. You must
first build an instance of the MediaRecorder class before you can utilize it. The
following is the syntax for it.
Syntax:

MediaRecorder my_audio_recorder_obj = new MediaRecorder();

Important Methods of AudioCapture

Your app must inform the user that it will access the device's audio input in order to
record. So this permission tag must be included in the manifest file of the app:

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


Apart from this, The MediaRecorder class also includes a few additional useful
features. Below is a list of these methods.
NOTES FOR MAD

● setAudioSource(): This function defines the audio source for recording.


● setVideoSource(): This function defines the video source to record.
● setOutputFormat(): This method provides the audio format that will be
used to store the audio.
● setAudioEncoder(): The audio encoder to be utilized is specified via this
method.
● setOutputFile(): This method specifies the location of the file where the
captured audio will be saved.
● stop(): This procedure brings the recording to a halt.
● release(): When the recorder instance is no longer required, this method
should be called.

Camera
The Camera class is used to set image capture settings, start/stop preview, snap
pictures, and retrieve frames for encoding for video. This class is a client for the
Camera service, which manages the actual camera hardware.

To access the device camera, you must declare the


android.Manifest.permission#CAMERA permission in your Android Manifest.
Also be sure to include the <uses-feature> manifest element to declare camera
features used by your application. For example, if you use the camera and
auto-focus feature, your Manifest should include the following:

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


<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />

To take pictures with this class, use the following steps:

1. Obtain an instance of Camera from open(int).


NOTES FOR MAD

2. Get existing (default) settings with getParameters().

3. If necessary, modify the returned Camera.Parameters object and call

setParameters(android.hardware.Camera.Parameters).

4. Call setDisplayOrientation(int) to ensure correct orientation of


preview.
5. Important: Pass a fully initialized SurfaceHolder to

setPreviewDisplay(android.view.SurfaceHolder). Without a
surface, the camera will be unable to start the preview.
6. Important: Call startPreview() to start updating the preview surface.
Preview must be started before you can take a picture.
7. When you want, call
takePicture(android.hardware.Camera.ShutterCallback,andro

id.hardware.Camera.PictureCallback,android.hardware.Camer

a.PictureCallback,android.hardware.Camera.PictureCallback

) to capture a photo. Wait for the callbacks to provide the actual image data.
8. After taking a picture, preview display will have stopped. To take more photos,
call startPreview() again first.

9. Call stopPreview() to stop updating the preview surface.

10. Important: Call release() to release the camera for use by other
applications. Applications should release the camera immediately in
android.app.Activity#onPause() (and re-open() it in

android.app.Activity#onResume()).

To quickly switch to video recording mode, use these steps:

1. Obtain and initialize a Camera and start preview as described above.


2. Call unlock() to allow the media process to access the camera.
3. Pass the camera to
android.media.MediaRecorder#setCamera(Camera). See

android.media.MediaRecorder information about video recording.


NOTES FOR MAD

4. When finished recording, call reconnect() to re-acquire and re-lock the


camera.
5. If desired, restart preview and take more photos or videos.
6. Call stopPreview() and release() as described above.

Bluetooth
The Android platform includes support for the Bluetooth network stack, which allows
a device to wirelessly exchange data with other Bluetooth devices. The application
framework provides access to the Bluetooth functionality through the Android
Bluetooth APIs. These APIs let applications wirelessly connect to other Bluetooth
devices, enabling point-to-point and multipoint wireless features.

Using the Bluetooth APIs, an Android application can perform the following:

● Scan for other Bluetooth devices


● Query the local Bluetooth adapter for paired Bluetooth devices
● Establish RFCOMM channels
● Connect to other devices through service discovery
● Transfer data to and from other devices
● Manage multiple connections

The basics

In order for Bluetooth-enabled devices to transmit data between each other, they
must first form a channel of communication using a pairing process. One device, a
discoverable device, makes itself available for incoming connection requests.
Another device finds the discoverable device using a service discovery process.
After the discoverable device accepts the pairing request, the two devices complete
a bonding process where they exchange security keys. The devices cache these
NOTES FOR MAD

keys for later use. After the pairing and bonding processes are complete, the two
devices exchange information. When the session is complete, the device that
initiated the pairing request releases the channel that had linked it to the
discoverable device. The two devices remain bonded, however, so they can
reconnect automatically during a future session as long as they're in range of each
other and neither device has removed the bond.

Bluetooth permissions

In order to use Bluetooth features in your application, you must declare two
permissions. The first of these is BLUETOOTH. You need this permission to perform
any Bluetooth communication, such as requesting a connection, accepting a
connection, and transferring data.

The other permission that you must declare is ACCESS_FINE_LOCATION. Your app
needs this permission because a Bluetooth scan can be used to gather information
about the location of the user. This information may come from the user's own
devices, as well as Bluetooth beacons in use at locations such as shops and transit
facilities.

Services running on Android 10 and higher cannot discover Bluetooth devices unless
they have the ACCESS_BACKGROUND_LOCATION permission.

An exception to this permission requirement is when your app is installed on a


device running Android 11 or higher and has used companion device pairing to
associate a device. In this case, once a device is associated, apps can scan for their
associated Bluetooth devices without requiring a location permission.

If you want your app to initiate device discovery or manipulate Bluetooth settings,
you must declare the BLUETOOTH_ADMIN permission in addition to the BLUETOOTH
permission. Most applications need this permission solely for the ability to discover
local Bluetooth devices.
NOTES FOR MAD

Work with profiles


Starting in Android 3.0, the Bluetooth API includes support for working with Bluetooth
profiles. A Bluetooth profile is a wireless interface specification for Bluetooth-based
communication between devices. An example is the Hands-Free profile. For a
mobile phone to connect to a wireless headset, both devices must support the
Hands-Free profile.

Headset. The Headset profile provides support for Bluetooth headsets to be


used with mobile phones. Android provides the BluetoothHeadset class, which is
a proxy for controlling the Bluetooth Headset Service. This includes both Bluetooth
Headset and Hands-Free (v1.5) profiles.

A2DP. The Advanced Audio Distribution Profile (A2DP) profile defines how
high quality audio can be streamed from one device to another over a
Bluetooth connection. Android provides the BluetoothA2dp class, which is
a proxy for controlling the Bluetooth A2DP Service.

Health Device. Android 4.0 (API level 14) introduces support for the
Bluetooth Health Device Profile (HDP). This lets you create applications that
use Bluetooth to communicate with health devices that support Bluetooth,
such as heart-rate monitors, blood meters, thermometers, scales, and so on.

Set up bluetooth

Before your application can communicate over Bluetooth, you need to verify that
Bluetooth is supported on the device, and if so, ensure that it is enabled.

If Bluetooth isn't supported, then you should gracefully disable any Bluetooth
features. If Bluetooth is supported, but disabled, then you can request that the user
enable Bluetooth without leaving your application. This setup is accomplished in two
steps, using the BluetoothAdapter:
NOTES FOR MAD

Get the BluetoothAdapter.

The BluetoothAdapter is required for any and all Bluetooth activity. To get the

BluetoothAdapter, call the static getDefaultAdapter() method. This returns

a BluetoothAdapter that represents the device's own Bluetooth adapter (the


Bluetooth radio). There's one Bluetooth adapter for the entire system, and your
application can interact with it using this object. If getDefaultAdapter() returns

null, then the device doesn't support Bluetooth.

Enable Bluetooth.

Next, you need to ensure that Bluetooth is enabled. Call isEnabled() to check
whether Bluetooth is currently enabled. If this method returns false, then Bluetooth is
disabled. To request that Bluetooth be enabled, call
startActivityForResult(), passing in an ACTION_REQUEST_ENABLE intent
action. This call issues a request to enable Bluetooth through the system settings
(without stopping your application).

A dialog appears requesting user permission to enable Bluetooth, as shown in


Figure 1. If the user responds "Yes", the system begins to enable Bluetooth, and
focus returns to your application once the process completes (or fails).

Find devices

Using the BluetoothAdapter, you can find remote Bluetooth devices either
through device discovery or by querying the list of paired devices.
NOTES FOR MAD

Device discovery is a scanning procedure that searches the local area for
Bluetooth-enabled devices and requests some information about each one. This
process is sometimes referred to as discovering, inquiring, or scanning. However, a
nearby Bluetooth device responds to a discovery request only if it is currently
accepting information requests by being discoverable. If a device is discoverable, it
responds to the discovery request by sharing some information, such as the device's
name, its class, and its unique MAC address. Using this information, the device that
is performing the discovery process can then choose to initiate a connection to the
discovered device.

Because discoverable devices might reveal information about the user's location, the
device discovery process requires location access.

Once a connection is made with a remote device for the first time, a pairing request
is automatically presented to the user. When a device is paired, the basic information
about that device—such as the device's name, class, and MAC address—is saved
and can be read using the Bluetooth APIs. Using the known MAC address for a
remote device, a connection can be initiated with it at any time without performing
discovery, assuming the device is still within range.

Note that there is a difference between being paired and being connected:

● To be paired means that two devices are aware of each other's existence,
have a shared link-key that can be used for authentication, and are capable of
establishing an encrypted connection with each other.
● To be connected means that the devices currently share an RFCOMM
channel and are able to transmit data with each other. The current Android
Bluetooth API's require devices to be paired before an RFCOMM connection
can be established. Pairing is automatically performed when you initiate an
encrypted connection with the Bluetooth APIs.
NOTES FOR MAD

Animations
Animations can add visual cues that notify users about what's going on in your
app. They are especially useful when the UI changes state, such as when
new content loads or new actions become available. Animations also add a
polished look to your app, which gives it a higher quality look and feel.

Animate UI visibility and motion

When you need to change the visibility or position of views in your layout, it's
best to include subtle animations to help the user understand how the UI is
changing.To move, reveal, or hide views within the current layout, you can use
the property animation system provided by the android.animation
package, available in Android 3.0 (API level 11) and higher.

Property Animation
The property animation system is a robust framework that allows you to
animate almost anything. You can define an animation to change any object
property over time, regardless of whether it draws to the screen or not. A
property animation changes a property's (a field in an object) value over a
specified length of time. To animate something, you specify the object
property that you want to animate, such as an object's position on the screen,
how long you want to animate it for, and what values you want to animate
between.

The property animation system lets you define the following characteristics of an
animation:
NOTES FOR MAD

● Duration: You can specify the duration of an animation. The default length is
300 ms.
● Time interpolation: You can specify how the values for the property are
calculated as a function of the animation's current elapsed time.
● Repeat count and behavior: You can specify whether or not to have an
animation repeat when it reaches the end of a duration and how many times
to repeat the animation. You can also specify whether you want the animation
to play back in reverse. Setting it to reverse plays the animation forwards then
backwards repeatedly, until the number of repeats is reached.
● Animator sets: You can group animations into logical sets that play together or
sequentially or after specified delays.
● Frame refresh delay: You can specify how often to refresh frames of your
animation. The default is set to refresh every 10 ms, but the speed in which
your application can refresh frames is ultimately dependent on how busy the
system is overall and how fast the system can service the underlying timer.

The ValueAnimator object keeps track of your animation's timing, such as how
long the animation has been running, and the current value of the property that it is
animating.

The ValueAnimator encapsulates a TimeInterpolator, which defines

animation interpolation, and a TypeEvaluator, which defines how to calculate


values for the property being animated.
NOTES FOR MAD

To start an animation, create a ValueAnimator and give it the starting and ending
values for the property that you want to animate, along with the duration of the
animation. When you call start() the animation begins.

When the ValueAnimator is done calculating an elapsed fraction, it calls the

TimeInterpolator that is currently set, to calculate an interpolated fraction.

When the interpolated fraction is calculated, ValueAnimator calls the appropriate

TypeEvaluator, to calculate the value of the property that you are animating,
based on the interpolated fraction

Physics-based motion

Whenever possible, apply real-world physics to your animations so that they are
natural-looking. For example, they should maintain momentum when their target
changes and make smooth transitions during any changes.

Two common physics-based animations are the following:

● Spring animation.
● Fling animation.

Lifecycle of a spring animation

In a spring-based animation, the SpringForce class lets you customize spring's


stiffness, its damping ratio, and its final position. As soon as the animation begins,
the spring force updates the animation value and the velocity on each frame. The
animation continues until the spring force reaches an equilibrium.

For example, if you drag an app icon around the screen and later release it by lifting
your finger from the icon, the icon tugs back to its original place by an invisible but a
familiar force.

fling animation
NOTES FOR MAD

Fling-based animation uses a friction force that is proportional to an object's velocity.


Use it to animate a property of an object and to end the animation gradually. It has
an initial momentum, which is mostly received from the gesture velocity, and
gradually slows down. The animation comes to an end when the velocity of the
animation is low enough that it makes no visible change on the device screen.

Animate drawable graphics


In some situations, images need to be animated. This is useful if you want to display
a custom loading animation composed of several images or if you want an icon to
morph after a user's action. Android provides two options for animating drawables.

The first option is to use an AnimationDrawable. This lets you specify several
static drawable files that display one at a time to create an animation. The second
option is to use an AnimatedVectorDrawable, which lets you animate the
properties of a vector drawable.

SQLite Database

SQLite is another data storage available in Android where we can store data

in the user’s device and can use it any time when required. We will take a

look at creating an SQLite database in the Android app and adding data to

that database in the Android app. We are going to perform the basic CRUD

(Create, Read, Update, and Delete) operation with SQLite Database in

Android.

How Data is Being Stored in the SQLite Database?


NOTES FOR MAD

Data is stored in the SQLite database in the form of tables. When we stored

this data in our SQLite database it is arranged in the form of tables that are

similar to that of an excel sheet. Below is the representation of our SQLite

database which we are storing in our SQLite database.

Important Methods in SQLite Database

Below are the several important methods that we will be using in this SQLite

database integration in Android.

Method Description
NOTES FOR MAD

This method is used to get the Array of


getColumnNames()
column names of our SQLite table.

This method will return the number of


getCount()
rows in the cursor.

This method returns a Boolean value


isClosed()
when our cursor is closed.

This method returns the total number of


getColumnCount()
columns present in our table.

This method will return the name of the


getColumnName(int
column when we passed the index of our
columnIndex)
column in it.
NOTES FOR MAD

getColumnIndex(String This method will return the index of our

columnName) column from the name of the column.

This method will return the current


getPosition()
position of our cursor in our table.

SQLite is the default database engine used in Android Studio for local data storage in
Android applications. There are several reasons why SQLite is necessary and widely
used in Android development:

​ Lightweight: SQLite is a lightweight database engine that is designed to be


embedded directly into applications. It has a small footprint, making it
well-suited for mobile devices with limited resources.
​ Efficiency: SQLite is optimized for efficiency, making it fast and responsive,
even on devices with lower processing power.
​ Ease of Use: SQLite is easy to use and integrate into Android applications.
Android provides built-in support for SQLite through the
android.database.sqlite package, making it straightforward for developers

to work with databases.


​ Local Data Storage: SQLite allows Android applications to store data locally
on the device, enabling offline functionality and improving performance by
reducing the need to make network requests for data.
​ Transactional Support: SQLite supports transactions, which allow multiple
database operations to be grouped together and executed as a single unit.
NOTES FOR MAD

This ensures data integrity and consistency, particularly in scenarios where


multiple operations need to be performed atomically.
​ Flexibility: SQLite supports SQL queries, allowing developers to perform
complex database operations such as filtering, sorting, and joining data. This
flexibility makes it suitable for a wide range of applications and use cases.
​ Compatibility: SQLite databases are cross-platform compatible, meaning that
they can be easily transferred between different operating systems and
devices. This makes it convenient for developers to develop and test
applications on different platforms.

Cursors
Cursors are what contain the result set of a query made against a database in
Android. The Cursor class has an API that allows an app to read the columns
that were returned from the query as well as iterate over the rows of the result
set.

Cursor is a Interface whice returns collection of your query data.

moveToFirst() is used to point the cursor position from where you want to

get data from your cursor. There are methods moveToLast(),

moveToNext(), moveToPrevious(), moveToPosition(position)


by which you can iterate through your cursor by desired way. For example, you
have data in your Cursor

Lalit

Rithesh

Paresh

Chandra
NOTES FOR MAD

● moveToFirst() - If you use cursor.moveToFirst() then in this case it


will point Lalit, as it is the first data in your cursor. To get the next data from
cursor you can use moveToNext().

● moveToLast() - This will point Chandra as the current data in your cursor.

To get the previous data from cursor you can use moveToPrevious()

To get the number of elements of the resulting query use the getCount() method.

The isAfterLast() method allows to check if the end of the query result has been
reached.

Cursor provides typed get*() methods, e.g. getLong(columnIndex),

getString(columnIndex) to access the column data for the current position of the
result. The "columnIndex" is the number of the column you are accessing.

Unit 6

SMS Telephony

In android, we can send SMS from our android application in two ways either by using
SMSManager API or Intents based on our requirements. If we use SMSManager API, it
will directly send SMS from our application. In case if we use Intent with proper action
(ACTION_VIEW), it will invoke a built-in SMS app to send SMS from our application.

Android Send SMS using SMSManager API

SMSManager API required SEND_SMS permission in our android manifest to send


SMS. Following is the code snippet to set SEND_SMS permissions in manifest file.

<uses-permission android:name=”android.permission.SEND_SMS”/>

Android Send SMS using Intent


NOTES FOR MAD

In android, Intent is a messaging object which is used to request an action from another
app component such as activities, services, broadcast receivers, and content providers.

Even for Intent, it required a SEND_SMS permission in our android manifest to send
SMS. Following is the code snippet to set SEND_SMS permissions in manifest file.

<uses-permission android:name=”android.permission.SEND_SMS”/>

Location Based Services

Location Based Services are provided by Android through its location framework.
The framework provides a location API which consists of certain classes and
interface. These classes and interface are the key components which allow us to
develop Location Based Application in Android

Classes and Interfaces of Location Based Services:

LocationManager – This class helps to get access to the location service of the
system.

LocationListener – This interface acts as the listener which receives notification


from the location manager when the location changes or the location provider is
disabled or enabled.

Location – This is the class which represents the geographic location returned at
a particular time.

Android Google Map

Android provides facility to integrate Google map in our application. Google map
displays your current location, navigate location direction, search location etc. We
can also customize Google map according to our requirement.
NOTES FOR MAD

Types of Google Maps

There are four different types of Google maps, as well as an optional to no map
at all. Each of them gives different view on map. These maps are as follow:

1. Normal: This type of map displays typical road map, natural features like river
and some features build by humans.

2. Hybrid: This type of map displays satellite photograph data with typical road
maps. It also displays road and feature labels.

3. Satellite: Satellite type displays satellite photograph data, but doesn't display
road and feature labels.

4. Terrain: This type displays photographic data. This includes colors, contour
lines and labels and perspective shading.

5. None: This type displays an empty grid with no tiles loaded

Syntax of different types of map

1. googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

2. googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

3. googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);

4. googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);

Methods of Google map

Google map API provides several methods that help to customize Google map.
These methods are as following:
NOTES FOR MAD

Google Map - Layout file

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

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 −
NOTES FOR MAD

Getting the maps API key

An API key is needed to access the Google Maps servers. This key is free and
you can use it with any of your applications.

Step 1: Open Google developer console and signin with your gmail account:
https://console.developers.google.com/project

Step 2: Now create new project. You can create new project by clicking on the
Create Project button and give name to your project.

Step 3: Now click on APIs & Services and open Dashboard from it.

Step 4: In this open Enable APIS AND SERICES.

Step 5: Now open Google Map Android API.

Step 6: Now enable the Google Maps Android API

Step 6: Now go to Credentials

Step 7: Here click on Create credentials and choose API key


NOTES FOR MAD

Step 8: Now API your API key will be generated. Copy it and save it somewhere
as we will need it when implementing Google Map in our Android project.

Creating the project, displaying the map, displaying the zoom control

Step 1: Create a New Android Project and name it GoogleMaps.

Step 2: Now select Google Maps Activity and then click Next and finish.

Step 3: Now open google_maps_api.xml (debug) in values folder

Zoom Controls

The Maps API provides built-in zoom controls,these can be enabled by


calling:

mMap.getUiSettings().setZoomControlsEnabled(true);

Zoom Gestures:

ZoomIn: Double tap to increase the zoom level by 1.

Zoom Out: Two finger tap to decrease the zoom level by 1.


NOTES FOR MAD

mMap.getUiSettings().setZoomGesturesEnabled(true);

Compass: You can set compass by calling below method:

mMap.getUiSettings().setCompassEnabled(true);

Navigating to a specific location

Navigating to a destination is done using a NavController, an object that


manages app navigation within a NavHost. Each NavHost has its own
corresponding NavController. NavController provides a few different ways
to navigate to a destination

To retrieve the NavController for a fragment, activity, or view, use one of the
following methods:

• NavHostFragment.findNavController(Fragment)

• Navigation.findNavController(Activity, @IdRes int viewId)

• Navigation.findNavController(View)

After you've retrieved a NavController, you can call one of the overloads of
navigate() to navigate between destinations. Each overload provides
support for various navigation scenarios

Adding markers

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 −
NOTES FOR MAD

final LatLng Himalaya = new LatLng(21 , 57); Marker TP =


googleMap.addMarker(new MarkerOptions()
.position(Himalaya).title("Himalaya"));

Enable/Disable zoom

enable or disable the zoom gestures in the map by calling the


setZoomControlsEnabled(boolean) method. Its syntax is given below

googleMap.getUiSettings().setZoomGesturesEnabled(true);

Getting location

Appropriate use of location information can be beneficial to users of your


app. For example, if your app helps the user find their way while walking or
driving, or if your app tracks the location of assets, it needs to get the
location of the device at regular intervals. As well as the geographical
location (latitude and longitude), you may want to give the user further
information such as the bearing (horizontal direction of travel), altitude, or
velocity of the device. This information, and more, is available in the
Location object that your app can retrieve from the location provider. In
response, the API updates your app periodically with the best available
location, based on the currently-available location providers such as WiFi
and GPS (Global Positioning System). The accuracy of the location is
determined by the providers, the location permissions you've requested,
and the options you set in the location request.

Geocoding and reverse Geocoding


NOTES FOR MAD

Geocoding is the process of converting addresses (like a street address)


into geographic coordinates (like latitude and longitude), which you can use
to place markers on a map, or position the map

Reverse geocoding is the process of converting geographic coordinates


into a humanreadable address.

For achieving Geocode or Reverse Geocode you must first import the
proper package.

import android.location.Geocoder;

The geocoding or reverse geocoding operation needs to be done on a


separate thread and should never be used on the UI thread as it will cause
the system to display an Application Not Responding (ANR) dialog to the
user.

Getting Location Data

There are two types of location providers,

1. GPS Location Provider

2. Network Location Provider

Any one of the above providers is enough to get current location of the user
or user’s device. But, it is recommended to use both providers as they both
have different advantages. Because, GPS provider will take time to get
location at indoor area. And, the Network Location Provider will not get
location when the network connectivity is poor
NOTES FOR MAD

Network Location Provider vs GPS Location Provider

• Network Location provider is comparatively faster than the GPS provider


in providing the location coordinates.

• GPS provider may be very very slow in in-door locations and will drain the
mobile battery.

• Network location provider depends on the cell tower and will return our
nearest tower location.

• GPS location provider, will give our location accurately.

Android Security Model

The Android security model is primarily based on a sandbox and


permission mechanism. Each application is running in a specific Dalvik
virtual machine with a unique user ID assigned to it, which means the
application code runs in isolation from the code of all others applications.
As a consequence, one application has not granted access to other
applications’ files. Android application has been signed with a certificate
with a private key Know the owner of the application is unique. This allows
the author of The application will be identified if needed. When an
application is installed in The phone is assigned a user ID, thus avoiding it
from affecting it Other applications by creating a sandbox for it. This user ID
is permanent on which devices and applications with the same user ID are
allowed to run in a single process. This is a way to ensure that a malicious
application has Can not access / compromise the data of the genuine
application. It is mandatory for an application to list all the resources it will
Access during installation. Terms are required of an application, in The
NOTES FOR MAD

installation process should be user-based or interactive Check with the


signature of the application.

Declaring and Using Permissions

The purpose of a permission is to protect the privacy of an Android user.


Android apps must request permission to access sensitive user data (such
as contacts and SMS), as well as certain system features (such as camera
and internet). Depending on the feature, the system might grant the
permission automatically or might prompt the user to approve the request.
(2) Permissions are divided into several protection levels. The protection
level affects whether runtime permission requests are required. There are
three protection levels that affect third-party apps: normal, signature, and
dangerous permissions.

Normal permissions cover areas where your app needs to access data
or resources outside the app’s sandbox, but where there’s very little risk to
the user’s privacy or the operation of other apps. For example, permission
to set the time zone is a normal permission. If an app declares in its
manifest that it needs a normal permission, the system automatically grants
the app that permission at install time. The system doesn’t prompt the user
to grant normal permissions, and users cannot revoke these permissions.

Signature permissions: The system grants these app permissions at


install time, but only when the app that attempts to use permission is
signed by the same certificate as the app that defines the permission.

Dangerous permissions cover areas where the app wants data or


resources that involve the user’s private information, or could potentially
affect the user’s stored data or the operation of other apps. For example,
NOTES FOR MAD

the ability to read the user’s contacts is a dangerous permission. If an app


declares that it needs a dangerous permission, the user has to explicitly
grant the permission to the app. Until the user approves the permission,
your app cannot provide functionality that depends on that permission. To
use a dangerous permission, your app must prompt the user to grant
permission at runtime.

Using Custom Permission

Apps can define their own custom permissions and request custom
permissions from other apps by defining elements. To enforce your own
permissions, you must first declare them in your AndroidManifest.xml using
one or more elements.

Application Deployment

Android application publishing is a process that makes your Android


applications available to users. Infact, publishing is the last phase of the
Android application development process.
NOTES FOR MAD

Once you developed and fully tested your Android Application, you can
start selling or distributing free using Google Play

Check list which will help you in launching your Android application-

1. Regression Testing Before you publish your application, you need


to make sure that its meeting the basic quality expectations for all
Android apps, on all of the devices that you are targeting. So perform
all the required testing on different devices including phone and
tablets.
2. Application Rating When you will publish your application at Google
Play, you will have to specify a content rating for your app, which
informs Google Play users of its maturity level. Currently available
ratings are (a) Everyone (b) Low maturity (c) Medium maturity (d)
High maturity.
NOTES FOR MAD

3. Targeted Regions Google Play lets you control what countries and
territories where your application will be sold. Accordingly you must
take care of setting up time zone,localization or any other specific
requirement as per the targeted region.
4. Application Size Currently, the maximum size for an APK published
on Google Play is 50 MB. If your app exceeds that size, or if you
want to offer a secondary download, you can use APK Expansion
Files, which Google Play will host for free on its server infrastructure
and automatically handle the download to devices
5. SDK and Screen Compatibility It is important to make sure that
your app is designed to run properly on the Android platform versions
and device screen sizes that you want to target.
6. Application Pricing Deciding whether you app will be free or paid is
important because, on Google Play, free app's must remain free. If
you want to sell your application then you will have to specify its price
in different currencies.
7. Promotional Content It is a good marketing practice to supply a
variety of highquality graphic assets to showcase your app or brand.
After you publish, these appear on your product details page, in store
listings and search results, and elsewhere.
8. Build and Upload release-ready APK The release-ready APK is
what you you will upload to the Developer Console and distribute to
users. You can check complete detail on how to create a
release-ready version of your app: Preparing for Release.
9. Finalize Application Detail Google Play gives you a variety of ways
to promote your app and engage with users on your product details
page, from colourful graphics, screen shots, and videos to localized
descriptions, release details, and links to your other apps. So you can
NOTES FOR MAD

decorate your application page and provide as much as clear crisp


detail you can provide.

You might also like