Notes MAD
Notes 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.
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.
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.
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:
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
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.
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
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
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.
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.
class AirplaneModeChangeReceiver:BroadcastReceiver() {
Registering a BroadcastReceiver:
IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED).also {
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
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)
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.
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.
browser, etc. This part must be unique for every content provider.
support different types of data that are not related to each other like
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.
● 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
hierarchy of the activity. At this point, view can be accessed with the
visible.
● onPause() : The system calls this method as the first indication that
the user is leaving the fragment. This is usually where you should
user session.
method
Types of Fragments
hand hold devices like mobiles, here we can show only one
fragment as a view.
fragment
● Paused : Another activity is in the foreground and has focus, but the
● 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
killed.
NOTES FOR MAD
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.
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:
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.
In android, services have 2 possible paths to complete its life cycle namely
Started and Bounded.
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.
Methods Description
onBind()
bind itself with a service. User-interface is also
provided to communicate
onRebind()
there is a need to connect the service with new
clients, the system calls this method.
a one-time-set-up.
NOTES FOR MAD
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.
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:
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.
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.
3. View System: It builds the user interface by handling the views and
layouts.
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.
1. Media Codec
of audio.
2. Media Player
seekTo().
● Audio Focus: This feature comes into the picture when multiple
set the source for streaming media and use the prepareAsync()
● Media Playback with the surface: To set the surface on which the
3. Media Recorder
● Recording state: This feature enables the user to notify about the
4. Surface View
video frames.
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:
6. Image Reader
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
Manifest declarations
Before starting development on your application using MediaPlayer, make sure your
manifest has the appropriate declarations to allow use of related features.
● 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
Asynchronous preparation
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
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
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
<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
take a long time to fetch a response may cause the program to become
NOTES FOR MAD
the background on a separate thread and return the results back to the UI
correctly and conveniently. The most frequent use case, however, was UI
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
Asynchronous tasks are divided into three generic types: Params, Progress,
computation
NOTES FOR MAD
UI thread.
AsyncTask Example
The following code snippet must be present in the MainActivity class in order
to launch an AsyncTask.
myTask.execute();
NOTES FOR MAD
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:
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:
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.
setParameters(android.hardware.Camera.Parameters).
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.
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()).
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:
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.
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
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
The BluetoothAdapter is required for any and all Bluetooth activity. To get the
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).
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.
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.
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.
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.
● Spring animation.
● Fling animation.
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
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
Android.
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
Below are the several important methods that we will be using in this SQLite
Method Description
NOTES FOR MAD
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:
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.
moveToFirst() is used to point the cursor position from where you want to
Lalit
Rithesh
Paresh
Chandra
NOTES FOR MAD
● 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.
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.
<uses-permission android:name=”android.permission.SEND_SMS”/>
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 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
LocationManager – This class helps to get access to the location service of the
system.
Location – This is the class which represents the geographic location returned at
a particular time.
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
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.
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);
Google map API provides several methods that help to customize Google map.
These methods are as following:
NOTES FOR MAD
Now you have to add the map fragment into xml layout file. Its syntax is given
below −
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
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 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 2: Now select Google Maps Activity and then click Next and finish.
Zoom Controls
mMap.getUiSettings().setZoomControlsEnabled(true);
Zoom Gestures:
mMap.getUiSettings().setZoomGesturesEnabled(true);
mMap.getUiSettings().setCompassEnabled(true);
To retrieve the NavController for a fragment, activity, or view, use one of the
following methods:
• NavHostFragment.findNavController(Fragment)
• 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
Enable/Disable zoom
googleMap.getUiSettings().setZoomGesturesEnabled(true);
Getting location
For achieving Geocode or Reverse Geocode you must first import the
proper package.
import android.location.Geocoder;
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
• 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.
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.
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
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-
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