0% found this document useful (0 votes)
3 views80 pages

MD Notes

Mobile application development involves creating software for mobile devices, utilizing backend services and testing on target devices. The two main platforms are iOS and Android, each requiring different development approaches such as native, cross-platform, hybrid, and progressive web applications. Developers often leverage cloud services for backend management to focus on app features and functionality, while also integrating various essential services like user management, analytics, and machine learning capabilities.

Uploaded by

riyazmd1205
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)
3 views80 pages

MD Notes

Mobile application development involves creating software for mobile devices, utilizing backend services and testing on target devices. The two main platforms are iOS and Android, each requiring different development approaches such as native, cross-platform, hybrid, and progressive web applications. Developers often leverage cloud services for backend management to focus on app features and functionality, while also integrating various essential services like user management, analytics, and machine learning capabilities.

Uploaded by

riyazmd1205
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/ 80

UNIT-I

Class:III BCA

Sub: Mobile Application Development

Mobile Application Development:-

Mobile application development is the process of creating software applications


that run on a mobile device, and a typical mobile application utilizes a network
connection to work with remote computing resources. Hence, the mobile development
process involves creating installable software bundles (code, binaries, assets, etc.) ,
implementing backend services such as data access with an API, and testing the
application on target devices.

Mobile Applications and Device Platforms

There are two dominant platforms in the modern smart phone market. One is the
iOS platform from Apple Inc. The iOS platform is the operating system that powers
Apple's popular line of iPhone smart phones. The second is Android from Google. The
Android operating system is used not only by Google devices but also by many other
OEMs to built their own smart phones and other smart devices.

Although there are some similarities between these two platforms when building
applications, developing for iOS vs. developing for Android involves using different
software development kits (SDKs) and different development tool chain. While Apple
uses iOS exclusively for its own devices, Google makes Android available to other
companies provided they meet specific requirements such as including certain Google
applications on the devices they ship. Developers can build apps for hundreds of millions
of devices by targeting both of these platforms.

Alternatives for Building Mobile Apps

There are four major development approaches when building mobile applications

• Native Mobile Applications


• Cross-Platform Native Mobile Applications
• Hybrid Mobile Applications
• Progressive Web Applications

Each of these approaches for developing mobile applications has its own set of
advantages and disadvantages. When choosing the right development approach for their
projects, developers consider the desired user experience, the computing resources and
native features required by the app, the development budget, time targets, and resources
available to maintain the app.

Native Applications:-

Native mobile applications are written in the programming language and


frameworks provided by the platform owner and running directly on the operating system
of the device such as iOS and Android.

Cross-Platform Applications:-

Cross-platform native mobile applications can be written in variety of different


programming languages and frameworks, but they are compiled into a native application
running directly on the operating system of the device.

Hybrid-Web Applications:-

Hybrid mobile applications are built with standard web technologies - such as
JavaScript, CSS, and HTML5 - and they are bundled as app installation packages.
Contrary to the native apps, hybrid apps work on a 'web container' which provides a
browser runtime and a bridge for native device APIs via Apache Cordova.

Progressive Web Applications:-

PWAs offer an alternative approach to traditional mobile app development by


skipping app store delivery and app installations. PWAs are web applications that utilize
a set of browser capabilities - such as working offline, running a background process, and
adding a link to the device home screen - to provide an 'app like' user experience.

Comparing Native vs. Hybrid Applications:-

At the highest level, there are four main ways that native apps differ from hybrid
apps as illustrated in the following table.
Native Hybrid
Platform Specific Cross Platform
Compiled Language Scripting / Compiled
Access to Device Hardware Plugins / Native Modules
Platform Frameworks Web Frameworks
Why Choose the Hybrid/Cross-platform Approach?

One problem with native mobile application development is that it requires a


highly specialized skill set. Although there are large and vibrant developer communities
for C and Java -- the language families that are mostly used for native development --,
there are fewer developers who are knowledgeable in platform-specific versions of those
languages and their respective IDEs. In fact, skilled native app developers are in such
demand, that many companies are hard-pressed to hire and retain them on staff, and
instead they frequently have to resort to outside 3rd party design and development houses
to build their apps for them.

How Hybrid and Cross-platform Frameworks Work?

Hybrid apps allow developers to use web technologies of HTML5/CSS/JavaScript


and then encapsulate those web applications in a container that allows the web
application to act like a native application on the device. Since hybrid mobile apps are
just web apps running on an embedded browser environment, most of the code from a
web app can be used to build a mobile app. As rendering and runtime performance of
mobile browsers are ever-increasing, hybrid development is a viable alternative for web
developers who want to build mobile apps quickly.

Similarly, PWAs are written using traditional web application programming


technologies usually including some variant of JavaScript, HTML5, and CSS, and are
accessed initially through a browser on the device or computer.

Most cross-platform frameworks such as - React Native and Native Script -


provides native components to work with the cross-platform code, while some others
such as Flutter and Xamarin compiles cross-platform code to the native code for better
performance.

The Mobile Application Development Lifecycle

There are two interlinked core components of a mobile application: 1) the mobile
application “Front-End” that resides on the mobile device, and 2) the services “Back-
End” that supports the mobile front-end.
Front-end vs. Back-end:-

In the early days of the modern smartphone applications era, mobile applications
went through a similar evolution as first websites. At first, the applications and sites
where wholly contained within themselves and acted as little more than static
advertisements for the brand, company, product, or service.

However, as connectivity and network capabilities improved, the applications


became increasingly connected to sources of data and information that lived outside of
the app itself, and the apps became increasingly dynamic as they were able to update their
UI and content with data received over the network from queries to data sources.

As a result, the mobile front-end applications increasingly rely on and integrated


with back-end services which provide data to be consumed through the mobile front-end.
Such data can include, for example, product information for e-commerce apps or flight
info for travel and reservation apps. For a mobile game, the data may include new levels
or challenges and scores or avatars from other players.

How Front-end 'Talks' to the Back-end?

The mobile front-end obtains the data from the back-end via a variety of service
calls such as APIs. In some cases, these APIs may be owned and operated by the same
entity developing the mobile application. In other cases, the API may be controlled by a
third party and access is granted to the mobile application via a commercial arrangement.

For example, a developer may obtain social media or advertising content by


making calls to media or advertising company services. In this case, a developer may
have to sign a contract in order to obtain credentials and a key that grants access to the
API and governs how that developer can use it, how much it will cost, or how frequently
it may be called, or how much data can be requested over what time period.

Why Developers Use a Cloud-backend?

For most of the applications, mobile developers are responsible for creating and
managing the back-end services for their application. The mobile developer may not be
an expert or even particularly skilled in spinning up and running a back-end
infrastructure.

In such a case, developers may prefer to take advantage of a cloud services


provider -- a backend-as-a-service provider -- that handles all of the drudge work and
heavy lifting of managing back-end capabilities, so the developers can focus purely on
the features and functionality they are building in their app, without having to worry
about scalability, security, and reliability.

The Mobile Application Front-End

The mobile front-end is the visual and interactive part of the application the user
experiences. It usually resides on the device, or there is at least an icon representing the
app that is visible on the home screen or is pinned in the application catalog of the device.
The application can be downloaded from the platform app store, side-loaded directly onto
the device, or can be reached through the device’s browser, as in the case for PWAs.

What a Front-end Development Workflow Looks Like?

When a developer says they are a mobile application programmer, they are most
often referring to this front-end part of the application, and they are skilled in the
languages and technologies that are used to create this front-end application.

Depending on the size of the team producing the app, there may be many different
people involved in the design and development of the front-end mobile app. The team
size can range from a single developer who does everything associated with building the
app, to tens, hundreds, and more people with specialized skills.

For example, there may be dedicated creative/graphics designers who are


responsible for creating visual elements of applications like icons, backgrounds, colors,
themes and other parts of the app. The team may also have user experience and user
interface designs who work on the layout of the components, how they interact with each
other and the user. In the case of certain types of games, a team may include motion
graphics developers and even engineers who develop engines that govern the physics of
how components move in the app, like a car in a racing game.

How Mobile Apps Integrate with the Backend?


Regardless of the size of the team, a critical element of the development effort is
building the app logic that is responsible for making network calls to the back-end
services, retrieve data and update the data in the back-end systems with new information
generated from the app.

These back-end services are typically accessed through a variety of application


programming interfaces, most commonly known as APIs. There are different types of
APIs, such as REST and GraphQL, and there are also a wide variety of means and styles
of accessing them. While some back-end service APIs are available directly to the
application through calls in the platform itself, many of the specialized services have to
be integrated into the app via a software development kit, commonly known as an SDK.
Once the SDK has been added to the app via the development environment, then the
application can make use of the APIs defined in the SDK.

How to Interact with the Backend Data?

An example of a back-end service for a mobile front-end could be a database that


contains information used in the app. To access the database directly, the mobile
developer would have to know the network location of the database, the protocol for
accessing the database, the credentials for authenticating and authorizing the data access,
and the specific database commands needed to extract the needed data.

Alternatively, the developer can utilize a specialized API when interacting with
the database; the developer may only have to know the parameters needed in a method
call to get or updated the needed information. In some cases, the mobile developer may
develop these APIs themselves or use the API definition provided to them by the
owner/operator of the back-end resource.

Typically, a REST API is used to interact with data sources on the cloud, such as a
cloud database. A GraphQL API is also another option for developers, as it makes easy to
work with backend data in a mobile application. GraphQL provides querying support
through a single API endpoint, and a data schema that can be used to build and easily
extend data models that are used in the app.

The Mobile Application Back-End

Regardless of what front-end platform or development methodology is being used,


delivering high-quality mobile applications that delight and retain users requires reliable
back-end services.

Given the critical importance of back-end services for the success of the mobile
application, the developers have several important architectural decisions that they must
consider. These decisions include which services should they build themselves and which
third party services should they leverage, and then should they run and maintain their
own services or should they take advantage of 3rd party services.
The answer is increasingly clear; to improve developer productivity and efficiency,
mobile app programmers should only build their own services if they are highly specific
to the domain of the application and embody unique intellectual property. Also, even for
the services they build themselves, they should almost always leverage cloud-based
services to build and maintain their backend infrastructure.

Key Mobile Application Services

There are hundreds of cloud and 3rd party services that mobile application
developers can leverage to speed up the development and delivery of their applications.
However, it’s unlikely that a developer is going to be able to become an expert in each of
these individual services.

Instead, the mobile developers should look for a development environment that makes it
easier for them to integrate, use, and consume the most commonly required capabilities
into their application quickly and easily, while still preserving the freedom to take
advantage of the many individual services available.

Essential:-

• User Sign-up/Sign-in and Management


• Social login (Facebook sign-in, Twitter sign-in, etc.)
• Analytics and User Engagement
• Push Notifications:-
Push notifications are small, pop-up messages sent to a user’s device by a mobile
app that appear even when the app isn't open. These notifications are designed to grab
attention and can convey reminders, updates, promotions, and more. Push notifications
can consist of a title, a message, an image, and a URL.

• Real Device Testing:-


A real device cloud is a mobile app testing environment that provides instant
access to thousands of real iOS, Android, and other mobile devices so app developers
and QA testers can test on different device/OS combinations to get real-world feedback
and ensure optimal coverage for your organization's target customers.

Data Services:-

• Cloud Storage:-
Cloud storage is a cloud computing model that enables storing data and files on
the internet through a cloud computing provider that you access either through the public
internet or a dedicated private network connection.
• Real-time and Offline Data:-
Offline data entry allows compilation and synchronization of data and information
from all sources. Data entry clerks read and enter data from papers, CDs, DVDs,
electronic gadgets, files, documents, bills, books and online resources, among others.
Even data collected from online sources can also be assigned to offline clerks for
compilation with greater accuracy. Offline data entry also enables clients to save almost
half of their operational and overhead costs as outsourcing vendors offer combined data
conversion and compilation package services.
Online data entry is the compilation of data from internet sources and compiling it
in a format suitable for online storage and accessibility. This data entry method involves
processes such as:
 Data entry
 Data mining
 Data extraction
 Typing
 Web research
These processes help find relevant information online and it is then arranged in an
orderly manner. The collected data and information are converted into a digital format
and is compiled for use on computers. In online data entry, a database is created to store
and access the information from any location

• Application Logic/Cloud Functions:-


Cloud applications provide quick responsiveness and don't need to permanently
reside on the local device. They can function offline, but can be updated online. While
under constant control, cloud applications don't always consume storage space on a
computer or communications device.

Machine Learning:-

• Conversational Bots:-
Chatbots are able to automate human tasks by translating fluidly between
unstructured language and structured data. Imagine a customer service chat via instant
message, email, or voice where the bot has answers before you can ask the question.
• Image and Video Recognition:-
Image recognition is the process of identifying an object or a feature in an image or
video. It is used in many applications like defect detection, medical imaging, and security
surveillance.
Image & Video Recognition solutions tailored to customer needs.
Starting from visual data we offer services of:
 Identification of licence plates
 Identification of people
 Vehicle identification
 Object identification
 Animal identification
 Emotion recognition
 Recognition and segmentation of people by age
 Recognition and segmentation of people by gender
 Check facial features of people even within groups
 Face / name matching

• Speech Recognition:-
Speech recognition, or speech-to-text, is the ability of a machine or program to
identify words spoken aloud and convert them into readable text. Rudimentary speech
recognition software has a limited vocabulary and may only identify words and phrases
when spoken clearly.

Android Versions
The development of the Android operating system was started in 2003 by
Android, Inc. Later on, it was purchased by Google in 2005. The beta version of Android
OS was released on November 5, 2007, while the software development kit (SDK) was
released on November 12, 2007.
The first Android mobile was publicly released with Android 1.0 of the T-Mobile
G1 (aka HTC Dream) in October 2008.
Google announced in August 2019 that they were ending the confectionery
scheme, and they use numerical ordering for future Android versions.
The first Android version which was released under the numerical order format was
Android 10.

Internal Version
Name
codename[9] number(s)

Android 1.0 — 1.0

Android 1.1 Petit Four 1.1

Android Cupcake Cupcake 1.5

Android Donut Donut 1.6

2.0

Android HYPERLINK
Eclair 2.0.1
"https://en.wikipedia.org/wiki/Android_Eclair"Eclair

2.1

Android HYPERLINK
Froyo 2.2 – 2.2.3
"https://en.wikipedia.org/wiki/Android_Froyo"Froyo

2.3 – 2.3.2
Android Gingerbread Gingerbread
2.3.3 – 2.3.7

3.0
Android Honeycomb Honeycomb
3.1
3.2 – 3.2.6

4.0 – 4.0.2
Ice Cream
Android Ice Cream Sandwich
Sandwich
4.0.3 – 4.0.4

4.1 – 4.1.2

Android Jelly Bean Jelly Bean 4.2 – 4.2.2

4.3 – 4.3.1

4.4 – 4.4.4
Android HYPERLINK
Key Lime Pie
"https://en.wikipedia.org/wiki/Android_KitKat"KitKat 4.4W –
4.4W.2

5.0 – 5.0.2
Lemon
Android Lollipop
Meringue Pie
5.1 – 5.1.1

Macadamia Nut
Android Marshmallow 6.0 – 6.0.1
Cookie

7.0
New York
Android Nougat
Cheesecake
7.1 – 7.1.2

8.0
Android Oreo Oatmeal Cookie
8.1
Pistachio Ice
Android Pie 9
Cream[20]

Android 10 Quince Tart[21] 10

Red Velvet
Android 11 11
Cake[21]

Android 12 Snow Cone 12

Android 12L Snow Cone v2 12.1[a]

Android 13 Tiramisu[23] 13

Android Version 1.0 to 1.1: No codename


Android officially publish its Android version 1.0 in September 2008. It is the
initial version of Android operating system. It supports Web browser to show HTML
and XHTMLweb pages, camera, access web email server (POP3, IMAP4, and SMTP).
This version contains Google Calendar, Google Maps, Google Sync, Google Search,
Google Talk, Instant messaging, Media player, Notifications appear in the status bar,
wallpaper, YouTube video player, Alarm Clock, Calculator, Dialer, Pictures (Gallery),
Wi-Fi and Bluetooth support.

Android version 1.5: Cupcake


On April 27, 2009, the Android updated to 1.5 with the codename of the dessert
item (Cupcake). It has Linux
kernel 2.6.27. It supports third-party virtual keyboard, Video recording and playback in
MPEG-4, Copy and paste feature, Animated screen translations, auto-rotation option,
ability to upload a video to YouTube, upload photos to Picasa, check phone usage
history.

Android version 1.6: Donut


On September 15, 2009, Android 1.6 was released with the name Donut. It
contains numerous new features such as voice and text entry search, bookmark history,
contacts, web, "speak" a string of text, faster camera access, user can select multiple
photos for deletion, support text-to-speech engine, WVGA screen resolutions.
Android version 2.0 to 2.1: Eclair
On October 26, 2009, Android 2.0 was released, whose codename was Eclair. It
was based on Linux kernel 2.6.29. It contains the several new features as expanded
account sync, Microsoft Exchange email support, Bluetooth 2.1, ability to tap a Contact
photo and select to call, SMS, ability to search all saved SMS, MMS
messages, delete the oldest message automatically when the defined limit is reached,
Minor API, bug fixes.

Android version 2.2 to 2.2.3: Froyo


On May 20, 2010, Android 2.2 (Froyo) was released based on Linux kernel 2.6.32.
It contains several features as speed, memory, performance optimization. JIT
compilation, Integration of Chrome's V8, JavaScript
engine into the Browser application, support Android Cloud to Device Messaging
service, Adobe Flash support, security updates, and performance improvement.

Android version 2.3 to 2.3.7: Gingerbread


On December 6, 2010, the Android 2.3 (Gingerbread) was released based on
Linux kernel 2.6.35. It includes the following changes: support for extra-large screen size
and resolutions, updated user interface design with increased simplicity and speed,
enhanced copy/paste functionality, select a word by press-holding, support Near Field
Communication (NFC), headphone virtualization, new Download Manager.
It has improved bug fixes for Nexus S, voice or video chat using Google Talk, network
performance for Nexus S 4G, Gmail application, battery efficiency, fixed a voice search
bug, Google Wallet support for Nexus S 4G.
Android version 3.0 to 3.2.6: Honeycomb
On February 22, 2011, Android 3.0 (Honeycomb) was launched for the first tablet
for Android-based on Linux kernel 2.6.36. It contains the features like "holographic" user
interface for tablet, added system Bar, simplified multitasking tapping Recent
Application in system Bar, redesign the keyboard making fast typing, quick access to
camera exposure, hardware acceleration, support for multi-core processor, UI
refinements, connectivity for USB accessories, support for joysticks and gamepads, high-
performance Wi-Fi lock, improved hardware support, Google Books, fixed data
connectivity issues when coming out of Airplane mode.
Android version 4.0 to 4.0.4: Ice Cream Sandwich
On October 19, 2011, Android 4.0.1 (Ice Cream Sandwich) was launched, which
was based on Linux kernel 3.0.1. It was the last version of officially support Adobe
System Flash player. It introduces the numerous new features: refinements to "Holo"
interface with new Roboto font family, separation of widgets in a new tab, integrated
screenshot capture, improved error correction on the keyboard, improved copy and paste
functionality, build-in photo editor, fixed minor bugs, improvement to graphics, spell-
checking, better camera performance.
Android version 4.1 to 4.3.1: Jelly Bean
On June 27, 2012, Google announced Android 4.1(Jelly Bean) in the Google I/O
conference. It is based on Linux kernel 3.0.31. It updates to following features: smoother
user interface, enhance accessibility, expandable notification, fixed bug on Nexus 7, one-
finger gestures to expand/collapse notifications, lock screen improvement, multiple user
accounts (tablets only), new clock application, Bluetooth low energy support, volume for
incoming call, 4K resolution support, native emoji support, bug fixes for the Nexus 7
LTE.
Android version 4.4 to 4.4.4: KitKat
On September 3, 2013, Google announced Android 4.4 (KitKat)
. Initially, its code name was "Key Lime Pie". Google started on Google's Nexus 5 on
October 31, 2013. The minimum required amount of RAM should available to Android is
340 MB. The other devices with less than 512 MB of RAM must report themselves as
"low RAM" devices. It includes several new features as clock no longer display bold
hours, wireless printing capability, WebViews are based on Chromium engine, sensor
batching, built-in screen recording feature, better application compatibility, camera
application loads Google+ Photo instead of Gallery.

Android version 5.0 to 5.1.1: Lollipop


Android 5.0 "Lollipop"was initially named "Android L" on June 25, 2014. It was
of oficially introduced on November 12, 2014. Lollipop provides several features like
redesigned user interface, support for 64-bit CPUs, support for print previews, material
design, Project Volta for battery life improvement, multiple user accounts, audio input,
and output through USB devices, join Wi-Fi networks, support for multiple SIM cards,
device protection, high-definition voice calls, native Wi-Fi calling support.
Android version 6.0 - 6.0.1: Marshmallow:-
Android 6.0 "Marshmallow"was disclosed under the codename "Android M" on
May 28, 2015, for Nexus 5 and Nexus 6 phones, Nexus 9 tablet. On October 5, 2015,
Android lunches "Marshmallow" for all android devices. It contains the various new
features as App Standby feature, introduce the Doze mode to save battery life, native
fingerprint reader support, run-time permission requests, USB-C support, Unicode 7.0 &
8.0 emoji support.
Android version 7.0 to 7.1.2: Nougat:-
Android 7.0 "Nougat"was the major release for the Android operating system. Its
initial codename was "Android N". It was first released as a developer preview on March
9, 2016, with factory images for the Nexus device.
On August 22, 2016, the final preview built was released with following features: file-
based encryption, zoom in the screen, multi-window support, new Data Saver mode, JIT
compiler makes 75 percent faster app installation, picture-in-picture support, support
manager APIs, circular app icons support, send GIFs directly from the default keyboard,
battery usage alerts.
Android version 8.0 to 8.1: Oreo:-
Android 8.0 "Oreo"was the 8th major release of the Android operating system. It
was first released for developer preview on March 21, 2017. The final developer preview
was released on July 24, 2017.
On August 21, 2017, its stable version was released with several features: picture-in-
picture support, support for Unicode 10.0 emoji (5.0), restructured settings, adoptive
icons, notification channels, notification dots, 2 times faster boot time, Google Play
Protect, Integrated printing support, Neural network API, shared memory API, Android
Oreo Go Edition, autofill framework, automatic light, and dark themes.
Android version 9.0: Pie:-
Android 9.0 "Pie"was the ninth major version of the Android operating system. It
was first announced and preview launched by Google on March 7, 2018. It was officially
r eleased on August 6, 2018. It has the following features: the clock has moved to the left
of the notification bar, the "screenshot" button has been added, battery percentage always
shown on display.
Android version 10:-
Android 10is the tenth extensive version of the Androidoperating system. Android
10 has developed under the codename "Android Q". It was initially announced by Google
on March 13, 2019 and its first beta version was released on same day and its second beta
was released on April 3, 2019.
The stable version of Android 10 was released on September 3, 2019. It contains features
like new permissions to access location in the background, floating setting panel, support
for an AV1 video codec, support for biometric authentication, support the WPA3 Wi-Fi
security.
Android 11:-
Android 11 operating system is the eleventh big release of Android. It is the 18th
version of Android mobile OS, which was released on 8 September 2020. The alphabetic
naming system of Android, based on deserts, was stopped since Android 10. So therefore,
this operating system has branded with "Android 11".
Features included in Android 11
• Conversations: Get all your message in one place.

• Accessibility: Perceptive apps help us to control and navigate our phone using
voice command.
• Device controls: Android 11 allows us to control all our connected devices (IOT)
from a single point.
• Content capture: Android 11 comes with a screen recording feature that captures
our phone's current screen activity.
• Predictive tools: By predicting our habits and patterns of working, it suggests
accordingly.
• Privacy & security: Android 11 gives more security and privacy fixes to our
smartphone straight from Google Play.
• Media: We can play music from other devices connected to our phones.
Android version 12
Google officially launched the final version of Android 12 in October 2021 and
started rolling the software out to its own Pixel devices soon after — alongside the launch
of its new Pixel 6 and Pixel 6 Pro phones. Android 12's design principles will stretch into
both apps on your phone and Google services on the web. The same principles will show
up on Chromebooks, Smart Displays, and Google-associated wearables as well.

Android version 13
Android 13, launched in August 2022, is one of Google's strangest Android
versions yet. The software is simultaneously one of the most ambitious updates in
Android history and one of the most subtle version changes to date. It's an unusual
duality, and it ultimately all comes down to what type of device you're using to
experience the software. On the former front, Android 13 introduces a whole new
interface design for both tablets and foldable phones, with a renewed focus on creating an
exceptional large-screen experience in the operating system itself and within apps (as first
observed and reported by Computerworld in January). The enhancements in that area
include a fresh framework and series of guidelines for app optimizations along with a
more capable split-screen mode for multitasking and a ChromeOS-like desktop-style
taskbar that makes it easy to access frequently used apps from anywhere.
Android 13 started rolling out to Google's current Pixel phones in August. If past Android
upgrade trends are any indication, it'll likely reach the first non-Google-made devices
later this year and then continue rolling out slowly to more phones and tablets as the
months progress.

Obtaining Required Tools


The android developer tools let you create interactive and powerful application for
android platform. The tools can be generally categorized into two types.
• SDK tools
• Platform tools
SDK tools
SDK tools are generally platform independent and are required no matter which android
platform you are working on. When you install the Android SDK into your system, these
tools get automatically installed. The list of SDK tools has been given below −
Sr.No Tool & description
android
1 This tool lets you manage AVDs, projects, and the installed components of the
SDK
ddms
2
This tool lets you debug Android applications
Draw 9-Patch
3 This tool allows you to easily create a NinePatch graphic using a WYSIWYG
editor
emulator
4
This tools let you test your applications without using a physical device
mksdcard
5 Helps you create a disk image (external sdcard storage) that you can use with
the emulator
proguard
6
Shrinks, optimizes, and obfuscates your code by removing unused code
sqlite3
7
Lets you access the SQLite data files created and used by Android applications
8 traceview
Provides a graphical viewer for execution logs saved by your application
Adb
9 Android Debug Bridge (adb) is a versatile command line tool that lets you
communicate with an emulator instance or connected Android-powered device.

AndroidStudio
ThefirstandmostimportantpieceofsoftwareyouneedtodownloadisAndroidStudio2.Afte
ryouhavedownloadedandinstalledAndroidStudio2,youcanusetheSDKManagertodow
nloadandinstallmultipleversionsoftheAndroidSDK.HavingmultipleversionsoftheSDK
availableenablesyoutowriteprogramsthattargetdifferentdevices.Forexample,youcanw
riteoneversionofanapplicationthatspecificallytargetsAndroidNougat,butbecausethatfl
avorofAndroidis
on less than 1% of devices, with multiple versions of the SDK you can also write a
version of yourapp that uses older features and targets Marshmallow or Lollipop
users. You can use the AndroidDeviceManagertosetupdeviceemulators.
AndroidStudio2ispackagedinanexecutable.RuntheinstallprocesstosetupAndr
oidStudio

AndroidSDK
Themostimportantpieceofsoftwareyouneedtodownloadis,ofcourse,theAndroidSDK.
TheAndroidSDKcontainsallofthepackagesandtoolsrequiredtodevelopafunctionalAn
droidapplication.TheSDKsarenamedaftertheversionofAndroidOStowhichtheycorres
pond.Bydefault,theMarshmallowSDKwasinstalledwithAndroidStudio2,whichmeans
youcandevelopapplicationsthatwillrunseamlesslyondeviceswithAndroidMarshmallo
w.
However,ifyouwanttoinstalladifferentAndroidSDK,youcandosousingtheSDKManag
erfromtheAndroidStudiowelcomescreenFromthisscreen,clicktheConfiguredrop-
downmenuinthelower-rightcorner.TheConfigureselectionmenuopens.
ChooseSDKManagerfromthismenu.
TheSDKconfigurationscreen,showsthattheMarshmallowSDKisalreadyinsta
lled.AndroidNisavailabletobeinstalled.

LaunchingYourFirstAndroidApplication
New terminologies:-

 Method - A block of code that only runs when called and performs an action.
 Activity - This is one screen on an Android App’s user interface.
 Fragment - A Fragment represents a reusable portion of your app’s UI.

The steps to build your Application

Step 1. Android Studio Setup

 Select create a new project.


 Select Empty Activity.

 Configure your project by choosing an appropriate name.


 Write an appropriate and unique package name if you plan to launch your app on
the Play Store, if not leave it on default.
 Select the language as Java.
 Ensure to choose an SDK that will run your app on many devices.
 Click Finish.

Step 2. User Interface design

 Navigate to the res Folder -> Layout Folder


 Click on the layout name activity_main.xml created by default to design the UI of
the MainActivity.

Step 3. Write the Java Code

We find the Java classes for the Activities in the Java Folder -> first folder with
the Application’s package name
 In the first activity outside the onCreate method, call the onClick you created in
the XML on the button.
 Inside this method, convert the text input from the user to a String.
 Then create an extra that will facilitate parsing of the data.
 Finally, create an intent that refers to a messaging object used to request an action
from another app component. The action requested in this case is Activity
navigation.

public class MainActivity extends AppCompatActivity {


EditText username;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onButtonClick (View view){
// taking text from one activity to another
username = findViewById(R.id.username_input);
String message = username.getText().toString();
Intent intent = new Intent(this, Page2.class);
intent.putExtra("EXTRA_MESSAGE" , message );
startActivity(intent);
}
}
Run the application:-
Using the Android emulator:-

1. Under the tools menu on Android Studio navigate to AVD Manager.


2. You will have one emulator by default. Click on the play button in the Actions
column on the table to start the emulator. Or, at the top, next to the emulator name,
click the play button to start it.

Debugging your Application


Debugging is the process of finding and fixing errors (bugs) or unexpected
behavior in your code. All code has bugs, from incorrect behavior in your app, to
behavior that excessively consumes memory or network resources, to actual app
freezing or crashing.
Bugs can result for many reasons:
• Errors in your design or implementation
• Android framework limitations (or bugs)
• Missing requirements or assumptions for how the app should work
• Device limitations (or bugs)
Use the debugging, testing, and profiling capabilities in Android Studio to help you
reproduce, find, and resolve all of these problems. Those capabilities include:
• The Logcat pane for log messages
• The Debugger pane for viewing frames, threads, and variables
• Debug mode for running apps with breakpoints
• Test frameworks such as JUnit or Espresso
• Dalvik Debug Monitor Server (DDMS), to track resource usage
In this chapter you learn how to debug your app with the Android Studio debugger, set
and view breakpoints, step through your code, and examine variables.

Running the debugger:-


Running an app in debug mode is similar to running the app. You can either run
an app in debug mode, or attach the debugger to an already-running app.

Run your app in debug mode:-

To start debugging, click Debug in the toolbar. Android Studio builds an APK,
signs it with a debug key, installs it on your selected device, then runs it and opens
the Debug pane with the Debugger and Console tabs.
The Debugger tab is selected, showing the Debugger pane with the following
features:
• Frames tab: Click to show the Frames pane with the current execution stack frames
for a given thread. The execution stack shows each class and method that have been
called in your app and in the Android runtime, with the most recent method at the top.
Click the Threads tab to replace the Frames pane with the Threads pane.
• Watches button: Click to show the Watches pane within the Variables pane, which
shows the values for any variable watches you have set. Watches allow you to keep
track of a specific variable in your program, and see how that variable changes as your
program runs.
• Variables pane: Shows the variables in the current scope and their values. Each
variable in this pane has an expand icon to expand the list of object properties for the
variable. Try expanding a variable to explore its properties.

Debug a running app

If your app is already running on a device or emulator, start debugging that app
with these steps:
• Select Run > Attach debugger to Android process or click the Attach icon in the
toolbar.
• In the Choose Process dialog, select the process to which you want to attach the
debugger.
By default, the debugger shows the device and app process for the current project, as
well as any connected hardware devices or virtual devices on your computer. Check
the Show all processes option to show all processes on all devices.
• Click OK. The Debug pane appears as before.

Resume or stop debugging

To resume executing an app after debugging it, select Run > Resume Program or
click the Resume icon.
To stop debugging your app, select Run > Stop or click the Stop icon in the toolbar.

Using breakpoints
Android Studio supports several types of breakpoints that trigger different debugging
actions. The most common type is a breakpoint that pauses the execution of your app
at a specified line of code. While paused, you can examine variables, evaluate
expressions, then continue execution line by line to determine the causes of runtime
errors.
You can set a breakpoint on any executable line of code.

Add breakpoints

To add a breakpoint to a line in your code, use these steps:


• Locate the line of code where you want to pause execution.
• Click in the left gutter of the editor pane at that line, next to the line numbers. A red
dot appears at that line, indicating a breakpoint. The red dot includes a check mark if
the app is already running in debug mode.
As an alternative, you can choose Run > Toggle Line Breakpoint or
press Control-F8 (Command-F8 on a Mac) to set or clear a breakpoint at a line.
If your app is already running, you don't need to update it to add the breakpoint.
If you click a breakpoint by mistake, you can undo it by clicking the breakpoint. If you
clicked a line of code that is not executable, the red dot includes an "x" and a warning
appears that the line of code is not executable.
When your code execution reaches the breakpoint, Android Studio pauses execution of
your app. You can then use the tools in the Debug pane to view the state of the app and
debug that app as it runs.

View and configure breakpoints

To view all the breakpoints you've set and configure breakpoint settings, click
the View Breakpoints icon on the left edge of the Debug pane.
The Breakpoints window appears.
In this window all the breakpoints you have set appear in the left pane, and you
can enable or disable each breakpoint with the checkboxes. If a breakpoint is disabled,
Android Studio does not pause your app when execution reaches that breakpoint.
Select a breakpoint from the list to configure its settings. You can configure a
breakpoint to be disabled at first and have the system enable it after a different
breakpoint is encountered. You can also configure whether a breakpoint should be
disabled after it has been reached.
To set a breakpoint for any exception, select Exception Breakpoints in the list of
breakpoints.

Disable (mute) all breakpoints:-

Disabling a breakpoint enables you to temporarily "mute" that breakpoint


without removing it from your code. If you remove a breakpoint altogether you also
lose any conditions or other features you created for that breakpoint, so disabling it can
be a better choice.
To mute all breakpoints, click the Mute Breakpoints icon . Click the icon again to
enable (unmute) all breakpoints.

Use conditional breakpoints:-

Conditional breakpoints are breakpoints that only stop execution of your app if
the test in the condition is true. To define a test for a conditional breakpoint, use these
steps:
• Right-click (or Control-click) a breakpoint, and enter a test in the Condition field.
The test you enter in this field can be any Java expression as long as it returns a
boolean value. You can use variable names from your app as part of the expression.
You can also use the Breakpoints window to enter a breakpoint condition.
• Run your app in debug mode. Execution of your app stops at the conditional
breakpoint, if the condition evaluates to true.

Stepping through code:-


After your app's execution has stopped because a breakpoint has been reached,
you can execute your code from that point one line at a time with the Step Over, Step
Into, and Step Out functions.
To use any of the step functions:
• Begin debugging your app. Pause the execution of your app with a breakpoint.
Your app's execution stops, and the Debugger pane shows the current state of the app.
The current line is highlighted in your code.
• Click the Step Over icon , select Run > Step Over, or press F8. Step Over executes
the next line of the code in the current class and method, executing all of the method
calls on that line and remaining in the same file.
• Click the Step Into icon , select Run > Step Into, or press F7. Step Into jumps into
the execution of a method call on the current line (as compared to just executing that
method and remaining on the same line). The Frames pane (which you'll learn about in
the next section) updates to show the new stack frame (the new method). If the method
call is contained in another class, the file for that class is opened and the current line in
that file is highlighted. You can continue stepping over lines in this new method call,
or step deeper into other methods.
• Click the Step Out icon , select Run > Step Out, or press Shift-F8. Step Out finishes
executing the current method and returns to the point where that method was called.
• To resume normal execution of the app, select Run > Resume Program or click the
Resume icon.

Viewing execution stack frames


The Frames pane of the Debug pane allows you to inspect the execution stack
and the specific frame that caused the current breakpoint to be reached.
The execution stack shows all the classes and methods (frames) that are being
executed up to this point in the app, in reverse order (most recent frame first). As
execution of a particular frame finishes, that frame is popped from the stack and
execution returns to the next frame.
Clicking a line for a frame in the Frames pane opens the associated source in
the editor and highlights the line where that frame was initially executed.
The Variables and Watches panes also update to reflect the state of the execution
environment when that frame was last entered.

Inspecting and modifying variables


The Variables pane of the Debugger pane allows you to inspect the variables
available at the current stack frame when the system stops your app on a breakpoint.
Variables that hold objects or collections such as arrays can be expanded to view their
components.
The Variables pane also allows you to evaluate expressions on the fly using
static methods or variables available within the selected frame.
If the Variables pane is not visible, click the Restore Variables View icon .
To modify variables in your app as it runs:
• Right-click (or Control-click) any variable in the Variables pane, and select Set
Value. You can also press F2.
• Enter a new value for the variable, and press Return.
The value you enter must be of the appropriate type for that variable, or Android
Studio returns a "type mismatch" error.

Setting watches:-
The Watches pane provides similar functionality to the Variables pane except
that expressions added to the Watches pane persist between debugging sessions. Add
watches for variables and fields that you access frequently or that provide state that is
helpful for the current debugging session.
To use watches:
• Begin debugging your app.
• Click the Show Watches icon . The Watches pane appears next to
the Variables pane.
• In the Watches pane, click the plus (+) button. In the text box that appears, type the
name of the variable or expression you want to watch and then press Enter.
Remove an item from the Watches list by selecting the item and then clicking the
minus (–) button.
Change the order of the elements in the Watches pane list by selecting an item and
then clicking the up or down icons.

PUBLISHINGYOURAPPLICATION
Afteryouhavecreated,andfullydebugged,yourapplication,youmightwanttodeployittot
heGoogleStoreforotherstoenjoy.Thefollowingsectionsoutlinethestepsforpublishingyourapp
lications.

GeneratingaSignedAPK
TopublishyourfinishedapplicationontheGooglePlayStore,youmustgenerateasignedA
PK
(theAndroidapplicationpackage).TheAPKisthecompiled,executableversionofyourap
plication.Signingitismuchlikesigningyournametoadocument.Thesignatureidentifiest
heapp’sdevel-
opertoGoogleandtheuserswhoinstallyourapplication.Moreimportantly,unlessyourAn
droidStudioisindevelopermode,unsignedapplicationswillnotrun.Usethefollowingstep
stogenerateasignedAPK:
• GenerateasignedAPKfromyourcodebyselectingBuild➪GenerateSig
nedAPKfromtheMenubartobringuptheGenerateSignedAPKwindow
asshowninFigure2-17.

FIGURE2-17

• AssumingyouhaveneverpublishedanapplicationfromAndroidStudio,youneedt
ocreateanewkeystore.ClicktheCreateNewbuttontodisplaytheNewKeyStorewin
dow(seeFigure2-18).
• Filloutalloftheinformationonthisformbecauseitpertainstoyourentityandapplica
tion.
Notice that there are two places for a password. These are the passwords for
your key storeand your key, respectively. Because a key store can hold
multiple keys, it requires a separatepasswordthanthatofthekeyforaspecificapp.
4. ClickOK to return tothe Generate Signed APKwindow.

5.
IntheGenerateSignedAPKwindows,clickNexttoreviewandfinishtheprocess.

NowthatyouhaveasignedAPK,youcanuploadittotheGooglePlayStoreusingth
edeveloperconsoleathttps://play.google.com/apps/publish/.
UNIT-III
USINGBASICVIEWS
Views:-
View is the basic building block of UI(User Interface) in android. In
Android Application the commonly used views such as the TextView, EditText, and Button
Views are called Basic Views. Some of the basic views that can be used in Android
applications are
➤ TextView
➤ EditText
➤ Button
➤ ImageButton
➤ CheckBox
➤ ToggleButton
➤ RadioButton
➤ RadioGroup

Syntax:-
<ViewName
Attribute1=Value1
Attribute2=Value2
Attribute3=Value3
.
.
AttributeN=ValueN/>

These basic views enable you to display text information,as well as perform
some basic selection.

TextView View:-
TextView is the most widely used view used to show pre-defined text on display
screen.

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="hello"
android:textSize="45sp"
android:padding="20dp"
android:textColor="#DD2C00"/>
Attributes:-
1.android:id="@+id/name"
This gives an id(identification) to this textview which can be used in Java files to
access this textview and to make any changes to it dynamically.
2. android:text="Hello"
The TextView will show the given value in the attribute as the text.
3.android:textSize="45sp"
This is used to determine the size of the text displayed in the TextView.
4.android:padding="20dp"
This provides a padding of 20dp arround the text.
5.android:textColor="#DD2C00"
This sets the color of the text. #DD2C00 is the hexa code for color some dark
red shade.

O/P:-

EditText View:-
EditText is used to get data from user in android application. It can be either single
line or multi-line. Touching a text field places makes the field active, places a cursor and
automatically displays the keyboard.
<EditText
android:id="@+id/et_address"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Write your email Address here"
android:textSize="20sp"
android:inputType="textWebEmailAddress"
android:maxLines="3"/>
Attributes:-

android:hint:-
This attribute gives a hint to the user about what should be entered in the box. This
is a temporary message that goes off as soon as the user starts to write anything in
the field.
android:inputType-This attribute specifies what the text entered should be like and for
what purpose it will be used.
Text- Used to display content.
textAutoComplete - This provides with suggestions as user is typing in text.
textAutoCorrect - This will enable auto correct on user input text.
textPassword - Display the entered text in form of dots or stars.
phone - This will present only the numeric keyboard to users.
android:maxLines="3"
This displays at max. only 3 lines of text.

O/P:-
Button: It is a component which can be pressed or clicked by the user to perform an action. It
has the same properties as a TextView, with a few Button specific properties.
<Button
android:id="@+id/btn_submit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Submit"
android:gravity=”Center”
android:textColor="@android:color/holo_blue_dark" />
Attributes:-

 android:gravity: This can be used to set the position of any View on the app screen.
The available value are right, left, center, center_vertical etc. It can also be use to
values together, using the | symbol.

 android:textSize: To set text size inside button.

 android:background: To set the background color of the button.

public class MainActivity extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b = (Button) findViewById(R.id.btn_submit);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {

}
});
}
}

ToggleButton:-
A control of type ToggleButton is a type of button that can remain in two possible
states, pressed or not-presses so that’s why we need to declare the properties of textOn
and TextOff If we want two different text in the button.

The ToggleButton displays a rectangular button that users can toggle on and off by
clicking:
<ToggleButton
android:id="@+id/toggle1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggle1);


toggleButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v) {
if (((ToggleButton)v).isChecked())
DisplayToast("Toggle button is On");
else
DisplayToast("Toggle button is Off");
}
})

O/P:-

Image Button: In a control of type ImageButton we can define an image to be displayed


instead of a text, for which we must assign the android property: src. Normally we will assign
this property with the descriptor of some resource that we have included in the / res /
drawable folders this time I choose a default image from the android project.
<ImageButton
android:id="@+id/imgButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="fitCenter"
android:src="@drawable/img_nature"/>

imageButton = (ImageButton)findViewById(R.id.imgButton);
imageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

// do anything here

}
});

ImageView: The ImageView control allows displaying images in the application. The most
interesting property is android: src, which allows you to indicate the image to be displayed.
Again, the normal thing will be to indicate as the origin of the image the identifier of a
resource of our folder / res / drawable.

<ImageView
android:id="@+id/img"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="fitCenter"
android:src="@drawable/img_nature"/>
Attributes:-
android:maxHeight -Used to specify a maximum height for this view.
android:maxWidth -Used to specify a maximum width for this view.
android:src -Sets a drawable as the content for this ImageView.
android:scaleType -Controls how the image should be resized or moved to match the size of
the ImageView.

CheckBox: A checkbox control is usually used to mark or unmark options in an application,


and Android is represented by the class of the same name, CheckBox. The way to define it in
our interface and the methods available to manipulate them from our code are analogous to
those already commented for the ToggleButton control.
<CheckBox
android:id="@+id/myCheckbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Studytonight"
android:checked="true"
android:textColor="@android:color/black"
android:layout_marginLeft="30dp"/>

CheckBoxmyCheckbox = (CheckBox) findViewById(R.id.myCheckbox);


CheckBoxcheckBox = (CheckBox) findViewById(R.id.chkAutosave);
checkBox.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v) {
if (((CheckBox)v).isChecked()) DisplayToast("CheckBox is checked");
else
DisplayToast("CheckBox is unchecked");
}
});

Radio buttons: Like the checkbox controls, a radio button can be marked or unmarked, but
in this case they are usually used within a group of options where one, and only one, of them
must be marked, that is, if the options, the one that was previously active will be
automatically unchecked. You need to regroup all these button in a RadioGroup to make it
know the group. RadioButton is used when you have to allow selection of only one option
among the list of multiple options. It is used under its parent view – RadioGroup so that we
can get one selected value out of all the listed radio buttons.

<RadioGroup
android:id="@+id/rg_gender"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginLeft="20dp">

<RadioButton
android:id="@+id/rb_male"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Male"
android:textColor="@android:color/black"/>

<RadioButton
android:id="@+id/rb_female"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@android:color/black"
android:text="Female"/>
</RadioGroup>

RadioButtonmaleRadioButton = (RadioButton) findViewById(R.id.rb_male);


// check current state of the radio button (true or false)
Boolean RadioButtonState = maleRadioButton.isChecked();

AutoCompleteTextView View
The AutoCompleteTextView is a view that is similar to EditText except that it
automatically shows a list of completion suggestions while the user is
typing.

<AutoCompleteTextView
android:id="@+id/txtCountries"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />

String[] presidents = {
"Dwight D. Eisenhower", "John F. Kennedy", "Lyndon B. Johnson", "Richard Nixon",
"Gerald Ford",
"Jimmy Carter", "Ronald Reagan", "George H. W. Bush", "Bill Clinton", "George W. Bush",
"Barack Obama"
};
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,


android.R.layout.simple_dropdown_item_1line, presidents);
AutoCompleteTextViewtextView = (AutoCompleteTextView)
findViewById(R.id.txtCountries);
textView.setThreshold(3);
textView.setAdapter(adapter);
}

Picker Views
Date Picker
Android DatePicker is a widget to select date. It allows you to select date by day,
month and year.If we use DatePicker in our application, it will ensure that the users will
select a valid date.In android DatePicker available in two modes, one is to show the complete
calendar and another one is to show the dates in spinner view.
Common Atrributes:-
android:id -It is used to uniquely identify the control
android:datePickerMode -It is used to specify datepicker mode either spinner or calendar
android:background- It is used to set the background color for the date picker.
android:padding -It is used to set the padding for left, right, top or bottom of the date
picker.

<DatePicker
android:id="@+id/datePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:datePickerMode="calendar" />

DatePicker
android:id="@+id/datePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:datePickerMode="spinner"/>
public class MainActivity extends AppCompatActivity {
DatePicker picker;
Button btnGet;
TextView tvw; protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvw=(TextView)findViewById(R.id.textView1);
picker=(DatePicker)findViewById(R.id.datePicker1);
btnGet=(Button)findViewById(R.id.button1);
btnGet.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
tvw.setText("Selected Date: "+ picker.getDayOfMonth()+"/"+
(picker.getMonth() + 1)+"/"+picker.getYear());
}
});
}
}

TimePicker:-TimePicker is a widget used for selecting the time of the day in either
AM/PM mode or 24 hours mode. The displayed time consist of hours, minutes and clock
format. If we need to show this view as a Dialog then we have to use a TimePickerDialog
class.

<TimePicker
android:id="@+id/timePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

Sr.No Method & description

1 is24HourView()
This method returns true if this is in 24 hour view else false

2 isEnabled()
This method returns the enabled status for this view
3 setCurrentHour(Integer currentHour)
This method sets the current hour

4 setCurrentMinute(Integer currentMinute)
This method sets the current minute

5 setEnabled(boolean enabled)
This method set the enabled state of this view

6 setIs24HourView(Boolean is24HourView)
This method set whether in 24 hour or AM/PM mode

7 setOnTimeChangedListener(TimePicker.OnTimeChangedListeneronTimeChangedLis
This method Set the callback that indicates the time has been adjusted by the user
publicclassMainActivityextendsAppCompatActivity{
TimePickertimePicker;

publicvoidonCreate(BundlesavedInstanceState)
{
super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);

timePicker=(TimePicker)findViewById(R.id.timeP
icker);timePicker.setIs24HourView(true);
}

public void onClick(View view)


{Toast.makeText(getBaseCo
ntext(),
"Time selected:"
+timePicker.getHou
r()+
":" +
timePicker.getMinute(),
Toast.LENGTH_SHOR
T).show();
}

}
Using a Dialog to Display the TimePicker View
public class MainActivity extends AppCompatActivity
{TimePickerDialog.OnTimeSetListenerdialogListener=newTimePickerDialog
.OnTimeSetListener(){
@Override
publicvoidonTimeSet(TimePickertimePicker,inti,inti1){

}
};
Calendarcal=Calendar.getInstance();

@Override
Public void
onCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

showTimeDialog();
}

Public void showTimeDialog(){


newTimePickerDialog(MainActivity.this,dialogListener,cal.get(Calendar.HOUR_
OF_DAY),cal.get(Calendar.MINUTE),false).show();{};
}}
USING LISTVIEWS TO DISPLAY LONG LISTS
Listviews are views that enable you to display a long list of items. The
ListView displays a list of items in a vertically scrolling list. In Android,there are two
types of listviews:ListView and SpinnerView. Both are useful for displaying longlists
of items.
Public class MainActivity extends ListActivity{
String[]presidents={
"DwightD.Eisenhower","John F. Kennedy","Lyndon B.
Johnson","Richard Nixon","GeraldFord","Jimmy Carter","Ronald
Reagan","GeorgeH.W.Bush","Bill Clinton","George W.
Bush","BarackObama"
};

Public void onCreate(BundlesavedInstanceState)


{
super.onCreate(savedInstanceState);
setListAdapter(new
ArrayAdapter<String>(this,android.R.layout.sim
ple_list_item_1,presidents));
}

Public void onListItemClick(ListView parent,View v,int position,long id)


{
Toast.makeText(this,
"Youhaveselected"+presidents[position],Toast.LENGTH_SH
ORT).show();
}
Customizing the ListView:-
The ListView is a versatile view that you can further customize.
Public void onCreate(BundlesavedInstanceState)
{
super.onCreate(savedInstanceState);

ListViewlstView = getListView();
lstView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lstView.setTextFilterEnabled(true);
setListAdapter(newArrayAdapter<String>(this,
android.R.layout.simple_list_item_checked,presidents));
}
Using the SpinnerView
The SpinnerView displays one item at a time from a list and enables users to
choose from them.
<Spinner
android:id="@+id/spinner1"android:layout_
width="wrap_content"android:layout_height="
wrap_content"android:drawSelectorOnTop="tr
ue"/>
Addthefollowinglinestothestrings.xmlfilelocatedintheres/valuesfolder:
<resources>
<string-arrayname="presidents_array">
<item>DwightD.Eisenhower</item>
<item>JohnF.Kennedy</item>
<item>LyndonB.Johnson</item>
<item>RichardNixon</item>
<item>GeraldFord</item>
</string-array>
</resources>

Public class MainActivity extends AppCompatActivity{


String[] presidents;
Public void onCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
presidents=getResources().getStringArray(R.array.presidents_array);
Spinner s1 = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<String>adapter=newArrayAdapter<String>(this,
android.R.layout.simple_spinner_item,
presidents);
s1.setAdapter(adapter);
s1.setOnItemSelectedListener(newAdapterView.OnItemSelectedListener
()
{
Public void onItemSelected(AdapterView<?>arg0,
View arg1,int arg2,long arg3)
{
int index = arg0.getSelectedItemPosition();
Toast.makeText(getBaseContext(),
"You have selected item : " +
presidents[index],Toast.LENGTH_SHORT).s
how();
}
publicvoidonNothingSelected(AdapterView<?>arg0){}
});
}
}

UNDERSTANDING SPECIALIZED FRAGMENTS


Android Fragment is the part of activity, it is also known as sub-
activity. There can be more than one fragment in an activity. Fragments
represent multiple screen inside one activity.
Android fragment lifecycle is affected by activity lifecycle because
fragments are included in activity.
Each fragment has its own life cycle methods that is affected by activity
life cycle because fragments are embedded in activity.
➤ DialogFragment
➤ PreferenceFragment

Using a ListFragment
A list fragment is a fragment that contains a ListView, which displays a list of
items from a data source, such as an array or a Cursor. A listfragment is useful
because it’s common to have one fragment that contains a list of items,and
another fragment that displays details about the selected posting. To create a list
fragment,you need to extend the ListFragment baseclass.

Create an Androidproject and name itListFragmentExample.


<fragment
android:name="com.jfdimarzio.listfragmentexample.Frag
ment1"android:id="@+id/fragment1"
android:layout_weight="0.5"a
ndroid:layout_width="0dp"and
roid:layout_height="200dp"/>
<fragment
android:name="com.jfdimarzio.listfragmentexample.Frag
ment1"android:id="@+id/fragment2"
android:layout_weight="0.5"a
ndroid:layout_width="0dp"and
roid:layout_height="300dp"/>
<ListView
android:id="@id/android:list"andr
oid:layout_width="match_parent"a
ndroid:layout_height="match_pare
nt"android:layout_weight="1"andr
oid:drawSelectorOnTop="false"/>
Add a Java Class file to the package and name it Fragment1.

import android.app.ListFragment;
public class Fragment1 extends ListFragment {
String[] presidents = {
"Dwight D. Eisenhower", "John F. Kennedy", "Lyndon B. Johnson", "Richard Nixon",
"Gerald Ford",
"Jimmy Carter", "Ronald Reagan", "George H. W. Bush", "Bill Clinton", "George W. Bush",
"Barack Obama"
};
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {
return inflater.inflate(R.layout.fragment1, container, false);
}
@Override
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, presidents));
}

public void onListItemClick(ListView parent, View v, int position, long id)


{
Toast.makeText(getActivity(),
"You have selected " + presidents[position], Toast.LENGTH_SHORT).show();
}
}

Using a DialogFragment
A dialog fragment floats on top of an activity and is displayed
modally.Dialogfragments are usefull when you need to obtain the user’s
response before continuing with execution. To create a dialogfragment,you must
extend the DialogFragmentbaseclass.
1. Create an Android project and name it DialogFragmentExample.
2. AddaJavaClassfileunderthepackageandnameitFragment1.

Public class Fragment1extendsDialogFragment{


staticFragment1newInstance(Stringtitle){
Fragment1fragment=newFragment1();
Bundle args = new Bundle();args.putString("title", title);
fragment.setArguments(args);
return fragment;
}
@Override
Public Dialog onCreateDialog(BundlesavedInstanceState){
String title = getArguments().getString("title");
returnnewAlertDialog.Builder(getActivity())
.setIcon(R.mipmap.ic_launcher)
.setTitle(title)
.setPositiveButton("OK",
newDialogInterface.OnClickListener(){
public void onClick(DialogInterfacedialog,
intwhichButton){
((MainActivity)
getActivity()).doPositiveClick();
}
})
.setNegativeButton("Cancel",
newDialogInterface.OnClickListener(){
publicvoidonClick(DialogInterfacedialog,
intwhichButton){
((MainActivity)
getActivity()).doNegativeClick();
}
}).create();
}
}
3. IntheMainActivity.javafile
importandroid.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends AppCompatActivity{
protected void onCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);set
ContentView(R.layout.activity_main);
Fragment1 dialogFragment =
Fragment1.newInstance("Areyousurey
ouwanttodothis?");
dialogFragment.show(getFragmentManager(),"dialog");
}

publicvoiddoPositiveClick(){
Log.d("DialogFragmentExample","UserclicksonOK");
}
publicvoiddoNegativeClick(){
Log.d("DialogFragmentExample","UserclicksonCancel");
}
}

Using a PreferenceFragment
In Android,you can use the Preference Activity base class to display an activity for the user
to edit the preferences.

<PreferenceScreenxmlns:android="http://schemas.android.com/apk/res/a
ndroid">
<PreferenceCategory
android:title="Category1">
<CheckBoxPreference
android:title="Checkbox"
android:defaultValue="false"
android:summary="TrueofFalse"
android:key="checkboxPref"/>
</PreferenceCategory>

<PreferenceCategory
android:title="Category2">
<EditTextPreference
android:name="EditText"
android:summary="Enterastring"
android:defaultValue="[Enterastringhere]"
android:title="Edit Text"
android:key="editTextPref"/>
<RingtonePreference
android:name="RingtonePreference"
android:summary="Selectaringtone"
android:title="Ringtones"
android:key="ringtonePref"/>
<PreferenceScreen
android:title="SecondPreferenceScreen"
android:summary=
"ClickheretogotothesecondPreferenceScreen"
android:key="secondPrefScreenPref">
<EditTextPreferenceandroid:name="EditText"
android:summary="Enterastring"
android:title="EditText(secondScreen)"
android:key="secondEditTextPref"/>
</PreferenceScreen>
</PreferenceCategory>

</PreferenceScreen>

Public class Fragment1extends PreferenceFragment{


Public void onCreate(BundlesavedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
publicclassMainActivityextendsAppCompatActivity{@Ov
erride
protectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstan
ceState);setContentView(R.layout.activity_main);

FragmentManager fragmentManager =
getFragmentManager();
FragmentTransactionfragmentTransaction=
fragmentManager.beginTransaction();
Fragment1fragment1=newFragment1();
fragmentTransaction.replace(android.R.id.content,fragment
1);
fragmentTransaction.addToBackStack(null);fragmentTrans
action.commit();

}
}

USINGIMAGEVIEWSTODISPLAYPICTURES
In Android, ImageView class is used to display an image file in application. In general
user can use the ImageView, ImageSwitcher, and GridView views for displaying images.

ImageView View
The ImageView is a view that shows images on the device screen.

<LinearLayout
android:id="@+id/activity_main"
android:layout_width="wrap_content"
android:layout_height="match_parent"
</LinearLayout>

ImageSwitcher
User may want to apply some animation to an image when it transitions from
one image to another.
In this case,you need to use the ImageSwitcher.
<Button
android:text="View Windows"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button2"
/>

<ImageSwitcher
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_below="@+id/button2"
android:id="@+id/imageSwitcher">
</ImageSwitcher>

<Button
android:text="View Butterfly"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
/>

Public class MainActivity extends AppCompatActivity{


Private ImageSwitcher imgSwitcher;
Private Button btnViewWindows, btnViewButterfly;

@Override
Protected void onCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

imgSwitcher=(ImageSwitcher)findViewById(R.id.imageSwit
cher);
imgSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,
android.R.anim.fade_in));
imgSwitcher.setOutAnimation(AnimationUtils.load
Animation(this,
android.R.anim.fade_out));

btnViewWindows = (Button)
findViewById(R.id.button2);
btnViewButterfly=(Button)findViewById(R.id.butto
n);

imgSwitcher.setFactory(new
ViewSwitcher.ViewFactory() {@Override
publicViewmakeView(){
ImageViewmyView = new
ImageView(getApplicationContext());
myView.setScaleType(ImageView.ScaleType.FIT_CEN
TER);myView.setLayoutParams(newImageSwitcher.La
youtParams(
ActionBar.LayoutParams.WRAP_CONTENT,ActionBar.LayoutParams.
WRAP_CONTENT));returnmyView;
}
});
btnViewWindows.setOnClickListener(newView.OnClickLi
stener(){@Override
public void onClick(View v)
{Toast.makeText(getApplicationCon
text(), "View
Windows",Toast.LENGTH_LONG).
show();imgSwitcher.setImageResourc
e(R.mipmap.windows);
}
});

btnViewButterfly.setOnClickListener(newView.OnClickListe
ner(){@Override
public void onClick(View v)
{Toast.makeText(getApplicationContext(),"ViewButt
erfly"
,Toast.LENGTH_LONG).show();
imgSwitcher.setImageResource(R.mipmap.butterfly);
}
});
}
}

GridView:-
The GridView shows items in a two-dimensional scrolling grid. Use the
GridView together with an ImageView to display a series of images.

<GridView
android:layout_width="384dp"/>

Public class MainActivity extends AppCompatActivity{


Integer[] imageIDs={
R.mipmap.butterfly,R.mipmap.windows,R.mipmap.ic_launcher
};

Protected void onCreate(BundlesavedInstanceState)


{super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

GridView gridView = (GridView) findViewById(R.id.gridview);


gridView.setAdapter(new ImageAdapter(this));
gridView.setOnItemClickListener(newAdapterView.OnItemClick
Listener()
{
Public void onItemClick(AdapterViewparent,
Viewv,intposition,longid)
{
Toast.makeText(getBaseContext(),
"pic" + (position + 1) + "
selected",Toast.LENGTH_SHORT).show()
} ;
});
}

getView(int
P IImageView imageView;
u if(convertView==null){
b imageView=new
l ImageView(context);
i imageView.setLayoutParams(new
c GridView.L
V ayoutParams(150,1
i 50));
e imageView.
w
s
e
t
S
c
a
l
e
T
y
p
e
(
I ROP)
m ieetPadding(5,5,5,5)
a ;
g }else{
e imageView=(ImageView)convertView;
V }
i imageView.setImageReso
e urce(imageIDs[position]);
w return imageView;
. }
_ }
C }
USINGMENUS WITH VIEWS
Menu is an important part of the UI component which is used to provide some
common functionality around the application.
Menus are useful for displaying additional options that are not directly visible on
the main user interface(UI) of an application. There are two main types of menus
in Android:
➤ Optionsmenu—This menu displays information related to the current
activity. In Android, you activate the options menu by pressing the
Menubutton.
➤ Contextmenu—This menu displays information related to a particular view
on an activity.
In Android, you tap and hold a contextmenu to activate it.
OptionsMenu

To define the menu_file.xml file, first create a menu directory under res folder. This is
done by right clicking on res --> new --> Android resource directory.

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


<menu xmlns:android="http:// schemas.android.com/apk/res/android">
<item android:id="@+id/mail"
android:icon="@drawable/ic_mail"
android:title="@string/mail" />
<item android:id="@+id/upload"
android:icon="@drawable/ic_upload"
android:title="@string/upload"
android:showAsAction="ifRoom" />
<item android:id="@+id/share"
android:icon="@drawable/ic_share"
android:title="@string/share" />
</menu>

The items in the above menu include the following attributes:

 android:id
A resource ID that's unique to the item, which allows the application to recognize the
item when the user selects it.

 android:icon

A reference to a drawable to use as the item's icon.

 android:title

A reference to a string to use as the item's title.

If we want to add a submenu in menu item, then we need to add a <menu> element as the
child of an <item>.
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http:// schemas.android.com/apk/res/android">
<item android:id="@+id/file"
android:title="@string/file" >
<!-- "file" submenu -->
<menu>
<item android:id="@+id/create_new"
android:title="@string/create_new" />
<item android:id="@+id/open"
android:title="@string/open" />
</menu>
</item>
</menu>

public boolean onCreateOptionsMenu(Menu menu) {


MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_file, menu);
return true;
}

 MenuInflater inflater = getMenuInflater();


This gives a MenuInflater object that will be used to inflate(convert our XML file into Java
Object) the menu_file.xml file.
 inflater.inflate(R.menu.menu_file, menu);
inflate() method is used to inflate the menu_file.xml file.
public boolean onOptionsItemSelected(MenuItem item) {
//Handle item selection
switch (item.getItemId()) {
case R.id.i1:
//perform any action;
return true;
case R.id.a:
//perform any action;
return true;
case R.id.b:
//perform any action;
return true;
default:
return super.onOptionsItemSelected(item);
}
}

ContextMenu
A context menu is usually associated with a view on an activity.A contextmenu
is displayed when the user taps and holds an item. For example,if the user taps a
Button view and holds it for a few seconds, a context menu can be displayed.
To make a floating context menu, you need to follow the following steps:
 Register the View to which the context menu should be associated by
calling registerForContextMenu() and pass it the View.
If your activity uses a ListView or GridView and you want each item to provide the same
context menu, you can register all items for a context menu by passing the ListView or
GridView object to registerForContextMenu() method.
 Implement the onCreateContextMenu() method in your Activity.
When the registered view receives a long-click event, the system calls
your onCreateContextMenu() method. This is where you define the menu items, usually by
inflating a menu resource. For example:
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_file, menu);
}
MenuInflater allows you to inflate the menu_file.xml file from a menu resource. The method
parameters include the View that the user selected and aC
ontextMenu. ContextMenuInfo object provides additional information about the item
selected. If your activity has several views such that each provide a different context menu,
you might use these parameters to determine which context menu to inflate.
Handling Click Events
When the user selects a menu item, the system calls onContextItemSelected() method so that
you can perform the appropriate action. For example:
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.i1:
//Perform any action;
return true;
case R.id.a:
//Perform any action;
return true;
case R.id.b:
//Perform any action;
return true;
default:
return super.onContextItemSelected(item);
}
}

USINGWEBVIEW

WebView:-
WebView is a view that display web pages inside your application. You can also
specify HTML string and can show it inside your application using WebView.

<WebView
android:id="@+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>

In AndroidManifest.xml file.
<uses-permission android:name="android.permission.INTERNET" />

Methods:-
1.loadUrl() – Load a web page in our WebView
loadUrl(String url)
This function is used to load a web page in a web view of our application. In this method
we specify the url of the web page that should be loaded in a web view.

WebView wv=(WebView) findViewById(R.id.simpleWebView);


// specify the url of the web page in loadUrl function
wv.loadUrl("www.gmail.com");
2. loadData() – Load Static Html Data on WebView
loadData(String data, String mimeType, String encoding)
This method is used to load the static HTML string in a web view. loadData() function
takes html string data, mime-type and encoding param as three parameters.
WebView wv = (WebView) findViewById(R.id.simpleWebView);
String customHtml = "<html><body><h1>Hello, AbhiAndroid</h1>" +
"<h1>Heading 1</h1><h2>Heading 2</h2><h3>Heading 3</h3>" +
"<p>This is a sample paragraph of static HTML In Web view</p>" +
"</body></html>";
wv.loadData(customHtml, "text/html", "UTF-8");

3. Load Remote URL on WebView using WebViewClient:


WebViewClient help us to monitor event in a WebView. You have to Override
the shouldOverrideUrlLoading() method. This method allow us to perform our own action
when a particular url is selected. Once you are ready with the WebViewClient, you can set
the WebViewClient in your WebView using the setWebViewClient() method.
Below we load a url by using web view client in a WebView.
wv= (WebView) findViewById(R.id.simpleWebView);
wv.setWebViewClient(new MyWebViewClient());
String url = "https://abhiandroid.com/ui/";
wv.getSettings().setJavaScriptEnabled(true);
wv.loadUrl(url);
}

private class MyWebViewClient extends WebViewClient {


public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url); // load the url
return true;
}
4. canGoBack() – Move to one page back if a back history exist
This method is used to specify whether the web view has a back history item or not. This
method returns a Boolean value either true or false. If it returns true then goBack() method is
used to move one page back.
WebView simpleWebView=(WebView)findViewById(R.id.simpleWebView);
Boolean canGoBack=simpleWebView.canGoBack();
5. canGoForward() – Move one page forward if forward history exist
This method is used to specify whether the web view has a forword history item or not. This
method returns a Boolean value either true or false. If it returns true then goForword()
method is used to move one page forword.
WebView simpleWebView=(WebView)findViewById(R.id.simpleWebView);
Boolean canGoForword=simpleWebView.canGoForward() ;
6. clearHistory() – clear the WebView history
This method is used to clear the web view forward and backward history.
WebView simpleWebView=(WebView)findViewById(R.id.simpleWebView);
simpleWebView.clearHistory(); // clear the forward and backward history
Email:-

Email is messages distributed by electronic means from one system user to one or
more recipients via a network. Intent is carrying data from one component to another
component with-in the application or outside the application. Write an Activity that launches
an email client, using an implicit Intent with the right action and data.

Intent Object - Action to send Email:-


Use ACTION_SEND action to launch an email client installed on your Android device.
Syntax:-

Intent i = new Intent(Intent.ACTION_SEND);


Intent Object - Data/Type to send Email
To send an email you need to specify mailto: as URI using setData() method and data
type will be to text/plain using setType() method as follows −
i.setData(Uri.parse("mailto:"));
i.setType("text/plain");
Intent Object - Extra to send Email
Android has built-in support to add TO, SUBJECT, CC, TEXT etc. fields which can
be attached to the intent before sending the intent to a target email client. You can use
following extra fields in your email –

1 EXTRA_BCC
A String[] holding e-mail addresses that should be blind carbon copied.
2 EXTRA_CC
A String[] holding e-mail addresses that should be carbon copied.
3 EXTRA_EMAIL
A String[] holding e-mail addresses that should be delivered to.
4 EXTRA_HTML_TEXT
A constant String that is associated with the Intent, used with ACTION_SEND to
supply an alternative to EXTRA_TEXT as HTML formatted text.
5 EXTRA_SUBJECT
A constant string holding the desired subject line of a message.
6 EXTRA_TEXT
A constant CharSequence that is associated with the Intent, used with
ACTION_SEND to supply the literal data to be sent.
7 EXTRA_TITLE
A CharSequence dialog title to provide to the user when used with a
ACTION_CHOOSER.
Here is an example showing you how to assign extra data to your intent −
i.putExtra(Intent.EXTRA_EMAIL , new String[]{"Recipient"});
i.putExtra(Intent.EXTRA_SUBJECT, "subject");
i.putExtra(Intent.EXTRA_TEXT , "Message Body");

public class MainActivity extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Button startBtn = (Button) findViewById(R.id.sendEmail);


startBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sendEmail();
}
});
}

protected void sendEmail() {


Log.i("Send email", "");
String[] TO = {""};
String[] CC = {""};
Intent emailIntent = new Intent(Intent.ACTION_SEND);

emailIntent.setData(Uri.parse("mailto:"));
emailIntent.setType("text/plain");
emailIntent.putExtra(Intent.EXTRA_EMAIL, TO);
emailIntent.putExtra(Intent.EXTRA_CC, CC);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Your subject");
emailIntent.putExtra(Intent.EXTRA_TEXT, "Email message goes here");

startActivity(Intent.createChooser(emailIntent, "Send mail..."));


}
}
SMS Messaging:-

In Android, use SmsManager API or devices Built-in SMS application to send SMS's. Use an
implicit Intent to launch a messaging app with the ACTION_SENDTO intent action. Send the
SMS message using the sendTextMessage() method or other methods of the SmsManager
class.

SmsManager API

SmsManager sm= SmsManager.getDefault();


sm.sendTextMessage("phoneNo", null, "sms message", null, null);

Built-in SMS application

Intent i= new Intent(Intent.ACTION_VIEW);


i.putExtra("sms_body", "default content");
i.setType("vnd.android-dir/mms-sms");
startActivity(i);

In AndroidManifest.xml:-

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

public class MainActivity extends Activity {


private static final int MY_PERMISSIONS_REQUEST_SEND_SMS =0 ;
Button sendBtn;
EditText txtphoneNo;
EditText txtMessage;
String phoneNo;
String message;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendBtn = (Button) findViewById(R.id.btnSendSMS);
txtphoneNo = (EditText) findViewById(R.id.editText);
txtMessage = (EditText) findViewById(R.id.editText2);

sendBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sendSMSMessage();
}
});
}

protected void sendSMSMessage() {


phoneNo = txtphoneNo.getText().toString();
message = txtMessage.getText().toString();

if (ContextCompat.checkSelfPermission(this,
Manifest.permission.SEND_SMS)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.SEND_SMS)) {
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.SEND_SMS},
MY_PERMISSIONS_REQUEST_SEND_SMS);
}
}
}

public void onRequestPermissionsResult(int requestCode,String permissions[], int[]


grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_SEND_SMS: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, message, null, null);
Toast.makeText(getApplicationContext(), "SMS sent.",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again.", Toast.LENGTH_LONG).show();
return;
}
}
}

}
}

Using Built-in Intent to send SMS


Use Android Intent to send SMS by calling built-in SMS functionality of the Android.
Intent Object - Action to send SMS
Use ACTION_VIEW action to launch an SMS client installed on your Android device.
Intent i = new Intent(Intent.ACTION_VIEW);
Intent Object - Data/Type to send SMS
To send an SMS you need to specify smsto: as URI using setData() method and data type
will be to vnd.android-dir/mms-sms using setType() method.

i.setData(Uri.parse("smsto:"));
i.setType("vnd.android-dir/mms-sms");
Intent Object - Extra to send SMS
Android has built-in support to add phone number and text message to send an SMS

i.putExtra("address" , new String("0123456789;3393993300"));


i.putExtra("sms_body" , "Test SMS to Angilla");

Displaying Maps:-

Android provides facility to integrate Google map in our application. Google map
displays your current location, navigate location direction, search location etc.

Types of Google Maps


Normal: This type of map displays typical road map, natural features like river and some
features build by humans.
Hybrid: This type of map displays satellite photograph data with typical road maps. It also
displays road and feature labels.
Satellite: Satellite type displays satellite photograph data, but doesn't display road and feature
labels.
Syntax:-
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);

In AndroidManifest.xml file.

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


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

Fine Location :
The Fine location provides better and accurate locations.
Coarse Location :
The Coarse location provides less accurate locations.

Adding Marker:-
User can place a maker with some text over it displaying your location on the map. It
can be done by via addMarker() method.
Syntax:-
LatLng ll= new LatLng(21 , 57);
Marker TP = googleMap.addMarker(new MarkerOptions()
.position(l1).title("TutorialsPoint"));
Enable/Disable zoom:-
User can enable or disable the zoom gestures in the map by calling the
setZoomControlsEnabled(boolean) method.
Syntax:-
googleMap.getUiSettings().setZoomGesturesEnabled(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.
animateCamera:-This method Moves the map according to the update with an animation.
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
// Zoom in, animating the camera.
map.animateCamera(CameraUpdateFactory.zoomIn());

// Zoom out to zoom level 10, animating with a duration of 2 seconds.


map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);

MapsActivity.java
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback{
private GoogleMap mMap;

protected void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment)
getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);

public void onMapReady(GoogleMap googleMap) {


mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));

PERSISTING DATA TO FILES


This storage stores files that your application intends to share with other apps like
media, documents, and other files.
In this, we access the data with a media store API and storage access framework.
Permission is required to read the media file. These permissions are:
1.READ_EXTERNAL_STORAGE.
2.WRITE_EXTERNAL_STORAGE.
In the AndroidManifest.xml file:-
<uses-permission
android:name="android.permission.READ_INTERNAL_STORAGE" />
android: name = "android.permission.WRITE_INTERNAL_STORAGE" / >

Saving to Internal Storage:-


User can save files in internal storage. These files are automatically set to
private and they can’t be used by other apps.
To Create and Write a Private File in Internal Storage:
FileOutputStream() method: It is called with the name of the file and the correct mode.
read() method: It is used for reading files.
write() method: It is used for writing in the file.
close() method: It is used to close your file.

In activitymain.xml:
<TextView
android:text="Please enter some text."
android:layout_width="245dp"
android:layout_height="wrap_content"
android:id="@+id/textView"/>

<EditText
android:layout_width="241dp"
android:layout_height="wrap_cont
ent"android:inputType="text"
android:ems="10"
android:id="@+id/editText"
/>
<Button
android:text="Save"
android:layout_width="240dp"
android:layout_height="wrap_cont
ent"android:id="@+id/btnSave"
android:onClick="onClickSave"/>

In the MainActivity.javafile:
Public class MainActivity extends AppCompatActivity{
EditText textBox;
Static final int READ_BLOCK_SIZE=100;
Protected void onCreate(BundlesavedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textBox=(EditText)findViewById(R.id.editText);
}

Public void onClickSave(Viewview){


String str = textBox.getText().toString();
FileOutputStreamfOut =
openFileOutput("textfile.txt",MODE_PRIVATE);
OutputStreamWriterosw=newOutputStreamWriter(fOut);
osw.write(str);
osw.flush();
osw.close();
Toast.makeText(getBaseConte(),"Filesavedsuccessfully!",Toast.LENGT
H_SHORT).show();
textBox.setText("");
}

Saving to External Storage(SDCard)


User can store files in external storage. External storage can be removable storage, while
internal storage is non-removable. In external storage our files can be accessed by other apps. Our files
do not get deleted if we uninstall the app.
In the AndroidManifest.xml file:-
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
In MainActivity.java File:-

Public void onClickSave(Viewview){


String str =
textBox.getText().toString();try
{
File sdCard =
Environment.getExternalStorageDirectory();
Filedirectory=newFile(sdCard.getAbsolutePath()+
"/MyFiles");
directory.mkdi
rs();
File file = new File(directory, "textfile.txt");
FileOutputStreamfOut=newFileOutputStream(fil
e);

OutputStreamWriterosw = newOutputStreamWriter(fOut);
osw.write(str);
osw.flush();
osw.close();
Toast.makeText(getBaseContext(),
"File saved
successfully!",Toast.LEN
GTH_SHORT).show();
textBox.setText("");
}
}

CREATING AND USING DATABASES


SQLite Database is an open-source database provided in Android which is used to
store data inside the user’s device in the form of a Text file. We can perform so many
operations on this data such as adding new data, updating, reading, and deleting this data.
SQLite is an offline database that is locally stored in the user’s device and we do not have
to create any connection to connect to this database.

SQLitedatabasethatyoucreateprogrammaticallyinanapplicationisalwaysstoredinthe/data
/data/<package_name>/databasesfolder.

Creating the DBAdapterHelper Class:-


Database - Package
The main package is android.database.sqlite that contains the classes to manage
databases.
Database - Creation
In order to create a database you just need to call method openOrCreateDatabase with
database name and mode as a parameter. It returns an instance of SQLite database.Its syntax
is given below

SQLiteDatabase mydatabase = openOrCreateDatabase("your database name",MODE


_PRIVATE,null);

Database - Insertion
we can create table or insert data into table using execSQL method defined in
SQLiteDatabase class.
mydatabase.execSQL("CREATE TABLE IF NOT EXISTS TutorialsPoint(Username
VARCHAR,Password VARCHAR);");
mydatabase.execSQL("INSERT INTO TutorialsPoint VALUES('admin','admin');");
publicvoidonUpgrade(SQLiteDatabasedb,intoldVersion,intnewVersion)
{
Log.w(TAG,"Upgradingdatabasefromversion"+oldVersion+"to"
+ newVersion + ", which will destroy all old
data");db.execSQL("DROPTABLEIFEXISTScontacts");
onCreate(db);
}
}

//---insertacontactintothedatabase---
publiclonginsertContact(Stringname,Stringemail)
{
ContentValuesinitialValues=newContentValues();initialValues.p
ut(KEY_NAME, name);initialValues.put(KEY_EMAIL,email);
returndb.insert(DATABASE_TABLE,null,initialValues);
}
//---deletes a particular contact---
publicbooleandeleteContact(longrowId)
{
returndb.delete(DATABASE_TABLE,KEY_ROWID+"="+rowId,null)>0;
}
//---updatesacontact---
publicbooleanupdateContact(longrowId,Stringname,Stringemail)
{
ContentValuesargs=newContentValues();args
.put(KEY_NAME,
name);args.put(KEY_EMAIL,email);
returndb.update(DATABASE_TABLE,args,KEY_ROWID+"="+rowId,null)>
0;
}
}
UNIT V

Consuming Web Services Using HTTP

A web service is a standard for exchanging information between different types of


applications irrespective of language and platform. For example, an android application
can interact with java or .net application using web services.

Characteristics:-

1. Web services are XML – based. They use it at its data representational layer and its
transportational layer as it removes networking, operating system or even the platform
binding. These services are highly interoperable at their core level.

2. Web services are loosely coupled. That means the consumer web services and
providers of web service are not tied together directly.

3. Web services have the ability to be either Synchronous or Asynchronous. Here


Synchronous can be understood as binding the client to the execution of the service. On
the other hand, Asynchronous refers to allowing the client to invoke a service first and
later executing the other functions.

4. Web Services supports Remote Procedure Calls. Remote Procedure calls can often be
referred to as RPCs. These RPCs let the clients invoke various functions, methods, and
services on remote objects using XML.
5. There is support to Document exchange in Web Services. In fact, XML has a very
generic way to represent data as well as complex documents. Along with that, it has got
various ways to represent these documents.

XML Remote Procedure Calls

1. It uses XML messages to perform Remote Calls.


2. These requests are encoded in XML and are transferred via http POST.
3. The XML responses are embedded in the same way as http responses.
4. XML- RPC is platform-independent as well as Language independent.
5. It also allows diverse applications to communicate with each other.
6. It is developed using W3C standards.

Types of Web Services in Android

There are various types of Web Services as below:

1. XML-RPC
In XML-RPC, RPC stands for remote procedure calls. It is an XML based protocol for
the exchange of data between a huge range of devices over the internet.
2. UDDI
UDDI stands for Universal Descriptive, discovery, and integration. It is an XML- based
standard used for detailing, publishing and discovering new web services.
3. SOAP
SOAP here stands for Simple object access protocol. It is an XML based web service
protocol used for the exchange of data or documents over HTTP(Hypertext transfer
protocol) or SMTP(Simple Message Transfer Protocol). It allows the communication of
independent processes that operate on disparate systems.

4. REST
Here, REST is Representational State Transfer. It provides communication and
connectivity between devices and the internet.

Advantages of Web Services

1. Web services enable interoperability among different Applications.


2. One of the very important advantages of using web services is Reusability.
3. Web services offer faster communications within and across applications and
organizations.
4. They use a quality industry-standard protocol to enable communication between
different applications.
5. They use SOAP over HTTP to enable the use of low-cost internet for implementing
web services.
6. Web Services are deployed over the standard internet technologies.
7. They allow us to expose the functions of the existing code over the internet.

Android Web Services Limitations

There are also some disadvantages of web services as below:

1. Web services do not access from the browser.


2. They don’t leverage emerging Web developments
3. The HTTP protocol used by web services is not reliable and is insecure.

Consuming JSON Services

JSON stands for JavaScript Object Notation. It is a format for data exchange and storage.
When compared to XML, it is very simple and easy to parse information interchange
format. JSON is extensively used for data exchange between the device and server in
android applications.

JSON Structures in Android

JSON uses two types of brackets that are as follows:


 [] – To declare the elements of Array in JSON, they’re written in square brackets.

 {} – To create JSON objects, the elements are written in curly brackets.

JSON has the following types of structures that are:

1. JSON Objects

The elements inside the curly brackets are known as Objects.

2. JSON Array

A list of values, known as Arrays.

3. JSON Key-Value

This data is stored as a pair of keys and values. Here the keys can be a name, a number
for which the values can be Seema, 98767586 etc.

Examples:-

{ “students”: [
{ “name”: “Sia Sharma”, “city”: “Chandigarh”},
{ “name”: “Prachi D’Souza”, “city”: “Nagpur”},
{ “name”: “Annas Jones”, “city”: “Mumbai”}
]}

JSON Parsing Functions in Android


Here are functions which we need for JSON parsing:
1. get(int index)
This function gets the value of the object type present in the JSON array.
2. getType(int index)
Here Type can be Int, Double, Boolean, Long, String, JSONArray, or JSONObject. This
function gets the value of any of the mentioned types present in the JSON array.
3. length()
using this function, we get the length of the array that has come from the server.
4. opt(int index)
This function returns the Object Type value in the JSONArray at a particular index.
5. optType(int index )
Here Type can be Int, Double, Boolean, Long, String, JSONArray, or JSONObject. This
function returns the value of the mentioned types in the JSONArray at a particular index.
6.getJSONArray(String name): This method is used to get the JSONArray type value.
We pass the String type key and it returns JSONArray if exists otherwise it throws
JSONException.
7.getJSONObject(String name): This method is used to get the JSONObject type value.
We pass the String type key and it returns the JSONObject value if exists otherwise it
throws JSONException.

public class MainActivity extends AppCompatActivity {

String JSON_STRING = "{\"employee\":{\"name\":\"Abhishek


Saini\",\"salary\":65000}}";

String name, salary;

TextView employeeName, employeeSalary;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// get the reference of TextView's

employeeName = (TextView) findViewById(R.id.name);

employeeSalary = (TextView) findViewById(R.id.salary);

// get JSONObject from JSON file

JSONObject obj = new JSONObject(JSON_STRING);

// fetch JSONObject named employee

JSONObject employee = obj.getJSONObject("employee");

// get employee name and salary

name = employee.getString("name");

salary = employee.getString("salary");

// set employee name and salary in TextView's


employeeName.setText("Name: "+name);

employeeSalary.setText("Salary: "+salary);

Creating Your Own Services

Android service is a component that is used to perform operations on the


background such as playing music, handle network transactions, interacting content
providers etc. It doesn't has any UI (user interface). A service can run continuously in
the background even if the application is closed or the user switches to another
application.

Types of Android Services

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.
Life Cycle of Android Service
There can be two forms of a service.The lifecycle of service can follow two different
paths: started or bound.

1. Started
2. Bound
1) Started Service
A service is started when component (like activity) calls startService() method, now it
runs in the background indefinitely. It is stopped by stopService() method. The service
can stop itself by calling the stopSelf() method.
2) Bound Service
A service is bound when another component (e.g. client) calls bindService() method.
The client can unbind the service by calling the unbindService() method.
The service cannot be stopped until all clients unbind the service.

1. public class MyService extends Service {


2. MediaPlayer myPlayer;
3. @Nullable
4. @Override
5. public IBinder onBind(Intent intent) {
6. return null;
7. }
8. @Override
9. public void onCreate() {
10. Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();
11.
12. myPlayer = MediaPlayer.create(this, R.raw.sun);
13. myPlayer.setLooping(false); // Set looping
14. }
15. @Override
16. public void onStart(Intent intent, int startid) {
17. Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
18. myPlayer.start();
19. }
20. @Override
21. public void onDestroy() {
22. Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
23. myPlayer.stop();
24. }
25. }

Understanding Threading

Threads are the mini-processes running within a main process, the purpose of
which is to enable at least the appearance of parallel execution paths within applications.
When an Android application is first started, the runtime system creates a single thread in
which all application components will run by default. This thread is generally referred to
as the main thread. The primary role of the main thread is to handle the user interface in
terms of event handling and interaction with views in the user interface.
Threading in Android

In Android, you can categorize all threading components into two basic categories:
1. Threads that are attached to an activity/fragment: These threads are tied to the
lifecycle of the activity/fragment and are terminated as soon as the
activity/fragment is destroyed. Eg: AsyncTask , Loaders
2.Threads that are not attached to any activity/fragment: These threads can continue
to run beyond the lifetime of the activity/fragment (if any) from which they were
spawned. Eg:- Service
Intent Service

ASYNCTASK:-

AsyncTask is the most basic Android component for threading. It’s simple to use and can
be good for basic scenarios.
private class MyTask extends AsyncTask<String, Void, String> { @Override
protected String doInBackground(String... params) { String url = params[0];
return doSomeWork(url);
}
@Override protected void onPostExecute(String result) {
super.onPostExecute(result); // do something with result }

LOADERS:-

Loaders can automatically stop when the activity is destroyed, and can also restart
themselves after the activity is recreated.

There are mainly two types of loaders: AsyncTaskLoader and CursorLoader.


private class MyLoader extends AsyncTaskLoader { public MyLoader(Context
context) { super(context); } @Override public Object loadInBackground() { return
someWorkToDo(); }

SERVICE:-

Service is a component that is useful for performing long (or potentially long) operations
without any UI.
Service runs in the main thread of its hosting process; the service does not create its own
thread and does not run in a separate process unless you specify otherwise.

public class ExampleService extends Service {

public int onStartCommand(Intent intent, int flags, int startId)


{

doSomeLongProccesingWork();

stopSelf();

return START_NOT_STICKY; }

public IBinder onBind(Intent intent) {

return null;

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy