Sbs 1603
Sbs 1603
Sbs 1603
Most of the methodologies in use are based on the model-driven approach which has
three different views of the application development process: (1) the application itself and its
structure, (2) the business logic and (3) the graphical user interface of the application.
Platforms Available
1. J2ME
Programming Language: Java
Integrated Development Environment: Netbeans/Eclipse
FrameWork: KVM
Hardware Deployment: Multiple
Installer Packaging Options: Jad/Jar
2. iOS (Apple)
Programming Language: Objective C
Integrated Development Environment: Xcode
FrameWork: Cocoa Touch
Hardware Deployment: iPhone, iPad, iPod
Installer Packaging Options: .app/.ipa
Development Tool Cost
3. Android
Programming Language: Java
Integrated Development Environment: Eclipse/Netbeans
FrameWork: Dalvik VM
Hardware Deployment: Android Only
Installer Packaging Options: .apk
Development Tool Cost
4. BlackBerry
Programming Language: Java
Integrated Development Environment: JDE - BlackBerry Java Development Environment
FrameWork: Dalvik VM
Hardware Deployment: Android Only
Installer Packaging Options: .alx, .cod
5. Windows Mobile
Programming Language: C#, VB.NET, Basic4ppc
Integrated Development Environment: Visual Studio 2008, 2005, 2003, Basic4ppc IDE
FrameWork: .Net Compact Framework
Hardware Deployment: Windows Mobiles
Installer Packaging Options: .ota/.cab
Typical Applications
Platforms supported
• iOS - platform developed by the company Apple supported by mobile devices: iPhone,
iPod Touch, iPad. Among standard applications iOS are Google maps, YouTube, iTunes,
iBooks etc. iOS is based on the C programming language.
• BlackBerry – compact operating system for mobile development with the basic
applications like text messaging, internet faxing, web browsing etc. Blackberry works on
some devices – Smart phones and communicators – produced by the company RIM.
Many BlackBerry Smart phones have full-size QWERTY keyboard, which easies the
work with texts.
• Android - an open operating system for cell phones and smart books based on Linux.
Android is supported by over 34 major software, hardware and telecoms companies
including Google, HTC, Motorola, Qualcomm, and T-Mobile. Android apps are mostly
written in the Java programming language.
• Windows Mobile / Windows Phone 7 – operating system supported by the company
Microsoft based on Microsoft Win32 API. Windows mobile can work on some devices
including Pocket PC, smart phones, and communicators. The current version for
Windows phones is somewhat analogical to the desktop Windows versions (functions,
lay-out).
• Symbian platform - It’s specifics are memory economy and high programs speed. The
main language of applications development is C++. Symbian foundation includes 40
companies: Nokia, Sony Ericsson, Siemens, Panasonic, Fujitsu, Samsung, Sony, Sony
Ericsson, Motorola etc. The Symbian Foundation maintains the code for the open source
software platform based on Symbian OS and software assets contributed by Nokia, NTT
DOCOMO, and Sony Ericsson.
• Java ME – This platform mostly supports portable applications. It is successfully used
on the most cell phones and portative organizers. According to the information of the
company Sun Microsystems, 2004 there were produced 579 million mobile devices
supported by Java. It makes the technology java ME to a dominant java technology in the
world.
• BREW Binary Runtime Environment for Wireless (BREW) —a platform for mobile
application development. The big advantage of the platform is the ease of applications
transportation among different devices supporting BREW. BREW allows realization of
many applications like games, message and data exchange etc. Brew applications are
developed on the base of the programming languages C/C++.
1. Mobile devices are deeply personal. The phone is something that belongs to just one
individual. It’s private, personal, and likely to be carried with you everywhere you go. We like to
customize our phones and they have become a symbol of social status. The phone I carry, and
the content I have, become part of my personal brand.
2. Mobile devices are hyper-social. The phone holds all of your contacts and allows you to do
much more with them. Basic communications include voice calling, text messaging (sending a
message of 140 characters or less. SMS or Short Message Service was the first Twitter),
multimedia messaging (sending video or photos along with text messages), and e-mail. Beyond
the basics, you may want to consider online presence, physical proximity, or relationship
strength, to allow for more “contextual communications.”
3. Mobile devices are location-aware. Even if you don’t know exactly where you are, your
phone does! It can also help you discover what is located nearby, get directions, or even interpret
what is right in front of you. If your friends opt-in, you can display their present location. This is
one of the most powerful features of mobile devices and one that, until recently, was reserved for
native applications. However, the most recent versions of Fireworks, Chrome, and the Android
browser, now have location APIs as well.
4. Mobile devices promote quick focused usage. Assuming that one is on the move, I will stop
to navigate my phone when I need a vital bit of information like my shopping list, current traffic,
flight arrival times, stock prices, or recent messages. The exception to this is entertainment. More
and more, mobiles fill those empty spaces when we’re standing in line, waiting, or sitting for
long idle periods — we reach for our phones to watch our favorite podcasts, scan tweets, listen to
music, or immerse ourselves in a good film.
5. Mobile devices are sometimes connected. When planning your mobile offering, it’s
important to develop for both the online and offline scenarios. Sometimes your users will be
riding the subway, on a plane, traveling abroad or otherwise unable to connect to the Internet,
their home network, or both. Although unlimited data plans do exist, they’re not as prevalent as
you may think. So if you want to avoid costly phone bills you need to consider how users will
engage with your content when they’re offline.
6. Mobile devices support a spontaneous lifestyle. Carrying all of your PIM (personal
information management) data means you can respond to events as they unfold and share new
data in real time. For example, if traffic is blocked, I can meet my party at a different restaurant.
If I’m standing in line at the cinema and tickets sell out, I can quickly locate an alternative and
have my friends meet me there.
7. Connectivity. Apps are always online as the device is constantly logged in to the mobile
network. This allows user specific information or notifications being pushed to the App as they
are available. In combination with the ubiquity of mobile applications, this is the most important
characteristic. A service, that must be called actively to get a reaction is useless in a mobile
environment. And with the growing number of Apps on each smartphone, this push-functionality
becomes critical to keep an App in the users mind.
8. Convenience
An emotional design and a simple (one-handed) handling guarantee a high acceptance. A good
App can do its job in different contexts and fast varying situations (changing environmental light
and noise, unsteady movement of the device, etc.). So the information architecture and the
overall usability must be planned with care to create a fitting and joyful interaction flow. Of
course good content also counts to convenience. Analyzing the users’ needs and creating a useful
idea out of it is still essential.
9.Localization
Localization and the possibility to offer location-based information is a key feature that makes
mobility vivid and practical. It separates the wheat from the chaff as it embeds the App to the
users’ context. Sure, this feature might not make sense for every App but localization must not
always be thought of as the big thing. Just think of automatically associate the location with a
note or photo or by just limiting possible options or by sorting places. It can be useful in little,
just creating a good experience for the user.
10. Reachability
Reachability covers a more social attribute given by the nature of mobile applications itself. A
good App can really be used – and more important makes sense – anywhere at any time. The
core of mobile devices is to be used anywhere at any time. The same is true for Apps where
reachability has become availability. Not in sense of usage, but in sense of updated information
and perpetual usefulness.
11. Security
Security has several facets. The data transferred over the network must be encrypted through the
carrier network. As some Apps sync data with online, web-based applications, the storage of this
data on the server must also be secured. Another aspect concerns the data on the device itself. I
don’t want anybody playing around with my mobile phone getting access to my bank account
data. Mobility is delicate, and so is the date aggregated and generated in this context.
12. Personalization
Creating personalized content based on individual usage or context is another characteristic. It
builds on all previous characteristics as it is a kind of melting down of all of them. I want my
App fitting my needs and I want my App behaving like I want it to do. This need covers not only
personalized content but also control over data stored, shared or used for further actions. The
option of turning localization on or off is true personalization. An individual background or
personal categories are convenience.
Benefits
• Presentation layer. This layer contains the user oriented functionality responsible for
managing user interaction with the system, and generally consists of components that
provide a common bridge into the core business logic encapsulated in the business layer.
• Business layer. This layer implements the core functionality of the system, and
encapsulates the relevant business logic. It generally consists of components, some of
which may expose service interfaces that other callers can use.
• Data layer. This layer provides access to data hosted within the boundaries of the
system, and data exposed by other networked systems; perhaps accessed through
services. The data layer exposes generic interfaces that the components in the business
layer can consume.
Presentation Layer:
The presentation layer contains the components that implement and display the user
interface and manage user interaction. This layer includes controls for user input and display, in
addition to components that organize user interaction.
• User Interface components. These are the application's visual elements used to display
information to the user and accept user input.
• Presentation Logic components. Presentation logic is the application code that defines
the logical behavior and structure of the application in a way that is independent of any
specific user interface implementation. When implementing the Separated Presentation
pattern, the presentation logic components may include Presenter, Presentation Model,
and ViewModel components. The presentation layer may also include Presentation Layer
Model components that encapsulate the data from your business layer, or Presentation
Entity components that encapsulate business logic and data in a form that is easily
consumable by the presentation layer.
Business Layer
Data Layer
• Data Access components. These components abstract the logic required to access the
underlying data stores. They centralize common data access functionality in order to
make the application easier to configure and maintain. Some data access frameworks may
require the developer to identify and implement common data access logic in separate
reusable helper or utility data access components. Other data access frameworks,
including many Object/Relational Mapping (O/RM) frameworks, implement such
components automatically, reducing the amount of data access code that the developer
must write.
• Service agents. When a business component must access data provided by an external
service, you might need to implement code to manage the semantics of communicating
with that particular service. Service agents implement data access components that isolate
the varying requirements for calling services from your application, and may provide
additional services such as caching, offline support, and basic mapping between the
format of the data exposed by the service and the format your application requires.
Crosscutting concerns
The majority of applications design will contain common functionality that spans layers
and tiers. This functionality typically supports operations such authentication, authorization,
caching, communication, exception management, logging and instrumentation, and validation.
Such functionality is generally described as crosscutting concerns because it affects the entire
application, and should be centralized in one location in the code where possible.
Authentication
Failure to design and implement a good authentication strategy can leave your application
vulnerable to spoofing attacks, dictionary attacks, session hijacking, and other types of attacks.
Consider the following guidelines when designing an authentication strategy:
• Identify your trust boundaries and authenticate users and calls across the trust boundaries.
Consider that calls might need to be authenticated from the client as well as from the
server (mutual authentication).
• Enforce the use of strong passwords or password phrases.
• If you have multiple systems within the application or users must be able to access
multiple applications with the same credentials, consider a single sign-on strategy.
• Do not transmit passwords over the wire in plain text, and do not store passwords in a
database or data store as plain text. Instead, store a hash of the password.
Authorization
Failure to design and implement a good authorization strategy can make your application
vulnerable to information disclosure, data tampering, and elevation of privileges. Consider the
following guidelines when designing an authorization strategy:
• Identify your trust boundaries and authorize users and callers across the trust boundary.
• Protect resources by applying authorization to callers based on their identity, groups, or
roles. Minimize granularity by limiting the number of roles you use where possible.
• Consider using role-based authorization for business decisions. Role-based authorization
is used to subdivide users into groups (roles) and then set permissions on each role rather
than on individual users. This eases management by allowing you to administer a smaller
set of roles rather than a larger set of users.
• Consider using resource-based authorization for system auditing. Resource-based
authorization sets permissions on the resource itself; for example, an access control list
(ACL) on a Windows resource uses the identity of the original caller to determine access
rights to the resource. If you use resource-based authorization in WCF, you must to
impersonate the original caller through the client or presentation layer, through the WCF
service layer, and to the business logic code that accesses the resource.
• Consider using claims-based authorization when you must support federated
authorization based on a mixture of information such as identity, role, permissions, rights,
and other factors. Claims-based authorization provides additional layers of abstraction
that make it easier to separate authorization rules from the authorization and
authentication mechanism. For example, you can authenticate a user with a certificate or
with username/password credentials and then pass that claim-set to the service to
determine access to resources.
Caching
Caching can improve the performance and responsiveness of your application. However, a
poorly designed caching strategy can degrade performance and responsiveness. You should use
caching to optimize reference data lookups, avoid network round trips, and avoid unnecessary
and duplicate processing. When you implement caching, you must decide when to load the cache
data and how and when to remove expired cached data. Try to preload frequently used data into
the cache asynchronously or by using a batch process to avoid client delays. Consider the
following guidelines when designing a caching strategy:
• Choose an appropriate location for the cache. If application is deployed in Web farm,
avoid using local caches that must be synchronized;
• Consider caching data in a ready-to-use format when working with an in-memory cache.
For example, use a specific object instead of caching raw database data. Consider using
Microsoft Velocity to implement in-memory caching.
• Do not cache volatile data, and do not cache sensitive data unless you encrypt it.
• Do not depend on data still being in your cache; it may have been removed. Implement a
mechanism to handle cache failures, perhaps by reloading the item from the source.
• Be especially careful when accessing the cache from multiple threads. If you are using
multiple threads, ensure that all access to the cache is thread-safe to maintain consistency.
Communication
Communication is concerned with the interaction between components across layers and
tiers. The mechanism you choose depends on the deployment scenarios your application must
support. Consider the following guidelines when designing communication mechanisms:
Configuration Management
Designing a good configuration management mechanism is important for the security and
flexibility of your application. Failure to do so can make your application vulnerable to a variety
of attacks, and also leads to an administrative overhead for your application. Consider the
following guidelines when designing for configuration management:
• Carefully consider which settings must be externally configurable. Verify that there is an
actual business need for each configurable setting, and provide the minimal configuration
options necessary to meet these requirements. Excessive configurability can result in
systems that are more complicated, and may leave the system vulnerable to security
breaches and malfunctions due to incorrect configuration.
• Decide if you will store configuration information centrally and have it downloaded or
applied to users at startup (for example, though Active Directory Group Policy). Consider
how you will restrict access to your configuration information. Consider using least
privileged process and service accounts, and encrypt sensitive information in your
configuration store.
• Categorize the configuration items into logical sections based on whether they apply to
users, application settings, or environmental settings. This makes it easier to divide
configuration when you must support different settings for different sets of users, or
multiple environments.
• Categorize the configuration items into logical sections if your application has multiple
tiers. If your server application runs in a Web farm, decide which parts of the
configuration are shared and which parts are specific to the machine on which the
application is running. Then choose an appropriate configuration store for each section.
• Provide a separate administrative UI for editing configuration information.
Exception Management
Designing a good exception management strategy is important for the security and reliability
of your application. Failure to do so can make it very difficult to diagnose and solve problems
with your application. It can also leave your application vulnerable to Denial of Service (DoS)
attacks, and it may reveal sensitive and critical information. Raising and handling exceptions is
an expensive process, so it is important that the design also takes into account performance
issues. A good approach is to design a centralized exception management mechanism for your
application, and to consider providing access points within your exception management system
(such as WMI events) to support enterprise level monitoring systems such as Microsoft System
Center. Consider the following guidelines when designing an exception management strategy:
• Design a centralized logging and instrumentation mechanism that captures system- and
business-critical events. Avoid logging and instrumentation that is too fine grained, but
consider additional logging and instrumentation that is configurable at run time for
obtaining extra information and to aid debugging.
• Create secure log file management policies. Do not store sensitive information in the log
files, and protect log files from unauthorized access. Consider how you will access and
pass auditing and logging data securely across application layers, and ensure that you
suppress but correctly handle logging failures.
• Consider allowing your log sinks, or trace listeners, to be configurable so that they can be
modified at run time to meet deployment environment requirements.
State Management
State management concerns the persistence of data that represents the state of a component,
operation, or step in a process. State data can be persisted using different formats and stores. The
design of a state management mechanism can affect the performance of your application;
maintaining even small volumes of state information can adversely affect performance and the
ability to scale out your application. You should only persist data that is required, and you must
understand the options that are available for managing state. Consider the following guidelines
when designing a state management mechanism:
• Keep your state management as lean as possible; persist the minimum amount of data
required to maintain state.
• Make sure that your state data is serializable if it must be persisted or shared across
process and network boundaries.
• Choose an appropriate state store. Storing state in process and in memory is the technique
that can offer the best performance, but only if your state does not have to survive
process or system restarts. Persist your state to a local disk or local SQL Server if you
want it available after a process or system restart. Consider storing state in a central
location such as a central SQL Server if state is critical for your application, or if you
want to share state between several machines.
Validation
Designing an effective validation mechanism is important for the usability and reliability of
your application. Failure to do so can leave your application open to data inconsistencies,
business rule violations, and a poor user experience. In addition, failing to adequately validate
input may leave your application vulnerable to security issues such as cross-site scripting attacks,
SQL injection attacks, buffer overflows, and other types of input attacks. Unfortunately there is
no standard definition that can differentiate valid input from malicious input. In addition, how
your application actually uses the input influences the risks associated with exploitation of the
vulnerability. Consider the following guidelines when designing a validation mechanism:
• Whenever possible, design your validation system to use allow lists that define
specifically what is acceptable input, rather than trying to define what comprises invalid
input. It is much easier to widen the scope of an allow list later than it is to narrow a
block list.
• Do not rely on only client-side validation for security checks. Instead, use client-side
validation to give the user feedback and improve the user experience. Always use server-
side validation to check for incorrect or malicious input because client-side validation can
be easily bypassed.
• Centralize your validation approach in separate components if it can be reused, or
consider using a third-party library such as the patterns & practices Enterprise Library
Validation Block. Doing so will allow you to apply a consistent validation mechanism
across the layers and tiers of your application.
• Be sure to constrain, reject, and sanitize user input. In other words, assume that all user
input is malicious. Identify your trust boundaries and validate all input data for length,
format, type, and range as it crosses trust boundaries.
Design Considerations
The following design guidelines provide information about different aspects you should
Consider when designing a mobile application. Follow these guidelines to ensure that your
application meets your requirements and performs efficiently in scenarios common to mobile
applications.
• Decide if you will build a rich client, a thin Web client, or rich Internet application (RIA).
If your application requires local processing and must work in an occasionally connected
scenario, consider designing a rich client. A rich client application will be more complex to
install and maintain. If your application can depend on server processing and will always be fully
connected, consider designing a thin client. If your application requires a rich user interface (UI),
only limited access to local resources, and must be portable to other platforms, design an RIA
client.
• Determine the device types you will support. When choosing which device types to support,
consider screen size, resolution (DPI), CPU performance characteristics, memory and storage
space, and development tool environment availability. In addition, factor in user requirements
and organizational constraints. You may require specific hardware such as GPS or a camera and
this may impact not only your application type, but also your device choice.
• Design considering occasionally connected limited-bandwidth scenarios when required. If
your mobile device is a stand-alone device, you will not need to account for connection issues.
When network connectivity is required, Mobile applications should handle cases when a network
connection is intermittent or not available. It is vital in this case to design your caching, state
management, and data-access mechanisms with intermittent network connectivity in mind. Batch
communications for times of connectivity. Choose hardware and software protocols based on
speed, power consumption, and “chattiness,” and not just on ease of programming.
• Design a UI appropriate for mobile devices, taking into account platform constraints.
QMobile devices require a simpler architecture, simpler UI, and other specific design decisions
in order to work within the constraints imposed by the device hardware. Keep these constraints
in mind and design specifically for the device instead of trying to reuse the architecture or UI
from a desktop or Web application. The main constraints are memory, battery life, ability to
adapt to difference screen sizes and orientations, security, and network bandwidth.
• Design a layered architecture appropriate for mobile devices that improves reuse and
maintainability. Depending on the application type, multiple layers may be located on the
device itself. Use the concept of layers to maximize separation of concerns, and to improve reuse
and maintainability for your mobile application. However, aim to achieve the smallest footprint
on the device by simplifying your design compared to a desktop or Web application.
• Design considering device resource constraints such as battery life, memory size, and
processor speed. Every design decision should take into account the limited CPU, memory,
storage capacity, and battery life of mobile devices. Battery life is usually the most limiting
factor in mobile devices. Backlighting, reading and writing to memory, wireless connections,
specialized hardware, and processor speed all have an impact on the overall power usage. When
the amount of memory available is low, the Microsoft® Windows Mobile® operating system
may ask your application to shut down or sacrifice cached data, slowing program execution.
Optimize your application to minimize its power and memory footprint while considering
performance during this process.
• 1G Wireless networks
– Data rate 2.4 kbps
– Basic voice service
– Analog based protocols
• 2G Wireless networks
– Data rate 64kbps
– Roaming services
– TDMA, CDMA technology used
– Designed for voice service
– Improved coverage and capacity
– First digital standard (GSM, CDMA)
• 2.5G (GPRS)
– Implemented a packet-switched domain in addition to the circuit-switched domain
– The first major step in the evolution of GSM networks to 3G occurred with the
introduction of General Packet Radio Service (GPRS)
• 2.75G (EDGE)
– Enhanced Data rates for GSM Evolution (EDGE), Enhanced GPRS (EGPRS)
– EDGE was deployed on GSM networks beginning in 2003.
• 3G Wireless networks
– Data rate 200 kbps
– 3.5G and 3.75G with high data rate
– Designed for voice with some data (multimedia, text, internet)
– First mobile broadband 2000 kbps
• 4G Wireless networks
– Data rate 1,00,000 kbps
– Global roaming
– Designed primary for data
– IP-based protocols
– True mobile broadband
– WiFi and WiMAX technology
– 4G LTE – Long-Term Evolution - High speed data for mobile phones and data
terminals
2G network - GSM
Digital cellular phone beginning in commercial use based on 2nd generation technology what
we called 2G. The well known 2G networking technology are GSM, CDMA, PCS etc.
• GSM stands for Global System for Mobile Communication and is an open, digital
cellular technology used for transmitting mobile voice and data services.
• The GSM emerged from the idea of cell-based mobile radio systems at Bell Laboratories
in the early 1970s.
• The GSM (formally, Groupe Speciale Mobile) is the name of a standardization group
established in 1982 to create a common European mobile telephone standard.
• The GSM was developed using digital technology. It has an ability to carry 64 kbps to
120 Mbps of data rates.
• Presently GSM supports more than one billion mobile subscribers in more than 210
countries throughout the world.
• The GSM provides basic to advanced voice and data services including Roaming service.
• Roaming is the ability to use your GSM phone number in another GSM network.
Why GSM:
• Improved spectrum efficiency
• International roaming
• Low-cost mobile sets and base stations (BSs)
• High-quality speech
• Compatibility with Integrated Services Digital Network (ISDN) and other telephone
company services
• Support for new services
Radio SubSystem(RSS):
The radio subsystem is comprised of all the radio specific elements, i.e.
• Mobile Station(MS):
It consist of a
BSS consists of a Base Station Controller (BSC) and one or more Base
Transceiver Station (BTS).
Each BTS defines a cell size and includes radio antenna, radio transceiver and a
link to a BSC. A GSM cell can have a radius of between 100m and 35km, depending on
the environment.
BSC is responsible for reserving radio frequencies, manages hand off mobile unit
from one cell to another within BSS, and control paging.
Central element of NSS is Mobile Switching Center (MSC) which is supported by four
databases that it controls.
• Security Management.
• Maintenance Tasks.
Advantages of GSM over Analog system
Limitations of GSM
• No end-to-end encryption of user data
• Reduced concentration while driving
• Electromagnetic radiation
• Abuse of private data possible
• High complexity of the system
• Several incompatibilities within the GSM standards
2.5G - GPRS
GPRS:
GPRS stands for General Packet Radio System. GPRS provides packet radio access for
mobile Global System for Mobile Communications (GSM) and time-division multiple access
(TDMA) users.
GPRS is important as a migration step toward third-generation (3G) networks and allows
network operators to implement an IP-based core architecture for data applications, which will
continue to be used and expanded for 3G services for integrated voice and data applications.
GPRS is a new bearer service for GSM that greatly improves and simplifies wireless
access to packet data networks, e.g., to the Internet. It applies a packet radio principle to transfer
user data packets in an efficient way between GSM mobile stations and external packet data
networks. Packets can be directly routed from the GPRS mobile stations to packet switched
networks.
Networks based on the Internet Protocol (IP) (e.g., the global Internet or private/corporate
intranets) and X.25 networks are also supported in the current versions of GPRS.
• The always online feature: Removes the dial-up process, making applications only one
click away.
• An upgrade to existing systems: Operators do not have to replace their equipment;
rather, GPRS is added on top of the existing infrastructure.
• An integral part of future 3G systems: GPRS is the packet data core network for 3G
systems EDGE and WCDMA.
Goals of GPRS:
GPRS is the first step toward an end-to-end wireless infrastructure and has the following goals:
• Open architecture
• Consistent IP services
• Same infrastructure for different air interfaces
• Integrated telephony and Internet infrastructure
• Leverage industry investment in IP
• Service innovation independent of infrastructure
Benefits of GPRS:
Users of GPRS benefit from shorter access times and higher data rates. In conventional
GSM, the connection setup takes several seconds and rates for data transmission are restricted to
9.6 kbit/s. GPRS in practice offers session establishment times below one second and ISDN-like
data rates up to several ten kbit/s.
Easy Billing:
GPRS packet transmission offers a more user friendly billing than that offered by circuit
switched services. In circuit switched services, billing is based on the duration of the connection.
This is unsuitable for applications with burst traffic. The user must pay for the entire airtime,
even for idle periods when no packets are sent (e.g., when the user reads a Web page).
In contrast to this, with packet switched services, billing can be based on the amount of
transmitted data. The advantage for the user is that he or she can be "online" over a long period
of time but will be billed based on the transmitted data volume.
GPRS enables a variety of new and unique services to the mobile wireless subscriber. These
mobile services have unique characteristics that provide enhanced value to customers. These
characteristics include the following:
• Mobility: The ability to maintain constant voice and data communications while on the
move
• Immediacy Allows subscribers to obtain connectivity when needed, regardless of
location and without a lengthy login session.
• Localization Allows subscribers to obtain information relevant to their current location.
The combination of these characteristics provides a wide spectrum of possible applications that
can be offered to mobile subscribers. In general, applications can be separated into two high-
level categories: corporate and consumer. These include:
It is also possible to send SMS messages over GPRS. In addition, it is planned to implement
supplementary services, such as call forwarding unconditional (CFU), call forwarding on mobile
subscriber not reachable (CFNRc), and closed user group (CUG).
GPRS Architecture:
GPRS is a data network that overlays a second-generation GSM network. This data
overlay network provides packet data transport at rates from 9.6 to 171 kbps. Additionally,
multiple users can share the same air-interface resources simultaneously.
GPRS attempts to reuse the existing GSM network elements as much as possible, but to
effectively build a packet-based mobile cellular network, some new network elements,
interfaces, and protocols for handling packet traffic are required.
Mobile Station (MS) New Mobile Station is required to access GPRS services. These new
terminals will be backward compatible with GSM for voice calls.
BSC The base station controller (BSC) requires a software upgrade and the
installation of new hardware called the packet control unit (PCU). The
PCU directs the data traffic to the GPRS network and can be a
separate hardware element associated with the BSC.
GPRS Support Nodes (GSNs) The deployment of GPRS requires the installation of new core network
elements called the serving GPRS support node (SGSN) and gateway
GPRS support node (GGSN).
Databases (HLR, VLR, etc.) All the databases involved in the network will require software
upgrades to handle the new call models and functions introduced by
GPRS.
New Mobile Station are required to use GPRS services because existing GSM phones do
not handle the enhanced air interface or packet data. A variety of MS can exist, including a high-
speed version of current phones to support high-speed data access, a new PDA device with an
embedded GSM phone, and PC cards for laptop computers. These mobile stations are backward
compatible for making voice calls using GSM.
Each BSC requires the installation of one or more Packet Control Units (PCUs) and a
software upgrade. The PCU provides a physical and logical data interface to the base station
subsystem (BSS) for packet data traffic. The BTS can also require a software upgrade but
typically does not require hardware enhancements.
When either voice or data traffic is originated at the subscriber mobile, it is transported
over the air interface to the BTS, and from the BTS to the BSC in the same way as a standard
GSM call. However, at the output of the BSC, the traffic is separated; voice is sent to the mobile
switching center (MSC) per standard GSM, and data is sent to a new device called the SGSN via
the PCU over a Frame Relay interface.
Following two new components, called GPRS support nodes (GSNs), are added:
The Gateway GPRS Support Node acts as an interface and a router to external networks.
The GGSN contains routing information for GPRS mobiles, which is used to tunnel packets
through the IP based internal backbone to the correct Serving GPRS Support Node. The GGSN
also collects charging information connected to the use of the external data networks and can act
as a packet filter for incoming traffic.
The Serving GPRS Support Node is responsible for authentication of GPRS mobiles,
registration of mobiles in the network, mobility management, and collecting information for
charging for the use of the air interface.
CDMA:
CDMA stands for the Code Division Multiple Access it’s basically the
telecommunication technology that is use by the various radio communicating companies for
accessing the channels in the minimum time. It’s quite different from the other multiplexing
techniques such as TDMA which divided time according to the access frequency. Unlike the
TDMA, CDMA permits the users to share the bandwidth frequencies for sending and receiving
the signals at the same time. Its forms a specific spectrum spread for the signaling. In this way all
the modulated signals after coding increase the high Data Bandwidth instead of direct signal
communication.
CDMA Architecture
Components of CDMA:
Advantages of CDMA
Most efficient use of available bandwidth the foremost advantage is the large band width and its
equivalent effect utilization for sending and receiving the data.
Resource allocation
Another advantage of CDMA is the flexible resource allocation which means that a certain kind
of pin code is provide to the active users to communicate with each other. Fixed time and
bandwidth keeps the simultaneous exchange of message at both sender and receivers end and
specific number of packets with limited length keeps the extra traffic out of the channel.
Disadvantage of CDMA
The main disadvantage of CDMA is that it can’t be used for the multi channel or multiple
transmission paths. All the communication is performed over a single path. This make it fixed
for singular purposes which is main drawback of CDMA technology.
EDGE technology is an extended version of GSM. It allows the clear and fast
transmission of data and information. EDGE is also termed as IMT-SC or single carrier. EDGE
technology is preferred over GSM due to its flexibility to carry packet switch data and circuit
switch data. EDGE technology can help you connect to the internet. This technology supports the
packet switching system. EDGE develops a broadband internet connection for its users. EDGE
technology helps its users to exploit the multimedia services .EDGE technology do not involve
the expense of additional hardware and software technologies. It only requires the base station to
install EDGE technology transceiver. EDGE technology has its edge because it can make use of
both switch circuit technology and packet circuit technology. EDGE technology is also believed
to support EGPRS or in other words enhanced general packet radio service.
EDGE Architecture:
The main new network architecture entities that are needed for the EDGE upgrade are:
• SGSN: GPRS Support Node - this forms a gateway to the services within the network.
• GGSN: Gateway GPRS Support Node which forms the gateway to the outside world.
• PCU: Packet Control Unit which differentiates whether data is to be routed to the packet
switched or circuit switched networks.
A simplified view of the GSM EDGE network architecture can be seen in the diagram below.
From this it can be seen that it is very similar to the more basic GSM network architecture, but
with additional elements.
SGSN
The SGSN or Serving GPRS Support Node element of the GPRS network provides a number of
takes focussed on the IP elements of the overall system. It provides a variety of services to the
mobiles:
GGSN
The GGSN, Gateway GPRS Support Node is one of the most important entities within the GSM
EDGE network architecture.
The GGSN organises the inter-working between the GPRS / EDGE network and external packet
switched networks to which the mobiles may be connected. These may include both Internet and
X.25 networks.
The GGSN can be considered to be a combination of a gateway, router and firewall as it hides
the internal network to the outside. In operation, when the GGSN receives data addressed to a
specific user, it checks if the user is active, then forwarding the data. In the opposite direction,
packet data from the mobile is routed to the right destination network by the GGSN.
PCU
The PCU or Packet Control Unit is a hardware router that is added to the BSC. It differentiates
data destined for the standard GSM network (circuit switched data) and data destined for the
EDGE network (Packet Switched Data). The PCU itself may be a separate physical entity, or
more often these days it is incorporated into the base station controller, BSC, thereby saving
additional hardware costs.
3G Concepts:
Third Generation Partnership Project 2 (TGPP 2) introduced this CDMA 2000. Five
countries Telecommunication standards organization did joint venture to design this technology.
This technology advancement was already entertained by many other systems and serving as 3G
MobileTechnology.
Properties:
W-CDMA stands for Wideband Code Division Multiple Access is a third generation’s
important feature based on radio transmission system. It is designed by ETSI Alpha organization.
It is quite challenging to apply it because of its complex features and versatile properties.
Properties:
WiFi:
Wireless Fidelity – is refers to IEEE 802.11 standard for Wireless Local Area Networks
(WLANs). Wi-Fi network connect computers to each other , to the internet and to the wired
network. It works on physical and datalink layer.
Wi-Fi networks use radio technologies to transmit and receive data at high speed:
• IEEE 802.11b
• IEEE 802.11a
• IEEE 802.11g
IEEE 802.11b:
• Operates at 2.4GHz radio spectrum
• 11 Mbps (theoretical speed) – within 30m range
• 4-6 Mbps (actual speed)
• 100 -150 feet range
• Most popular, Least Expensive
• Interference from mobile phones and Bluetooth devices which can reduce the transmission
speed.
IEEE 802.11a:
• Operates at 5 GHz
• 54 Mbps (theoretical speed)
• 15 – 20 Mbps (actual speed)
• 50 – 75 feet range
• More expensive and not compatible with 802.11b.
IEEE 802.11g:
• Combine the features of both standards (a,b).
• 100 – 150 feet range
• 2.4 GHz radio frequencies and compatible with ‘b’.
Elements of Wi–Fi:
• Access Point (AP) – The AP is a wireless LAN Transceiver or base station that can connect one or
many wireless devices simultaneously to the Internet.
• Wi-Fi cards – They accept the wireless signal and relay information. They can be an internal and
external.
• Safeguards - Firewalls and anti-virus software protect networks from uninvited users and keep
information secure.
➢ AP is not required.
➢ clients can connect to each other directly.
➢ It is useful for setting up a wireless network quickly and easily.
• AP – based topology (Infrastructure Mode):
Hotspots:
A Hotspot is a geographical area that has a readily accessible wireless network. Hotspots
are equipped with Broadband Internet connection and one or more Access Points that allow users
to access the internet wirelessly. It can be setup in any public location that can support an
Internet connection.
Advantages:
➢ Mobility
➢ Ease of Installation
➢ Flexibility
➢ Cost
➢ Reliability
➢ Security
➢ Roaming
➢ Speed
Limitations:
➢ Interference
➢ Degradation in performance
➢ High power consumption
➢ Limitated range
It is a telecommunications protocol that provides fixed and mobile Internet access. The
current WiMAX revision provides up to 40 Mbit/s.
WiMAX is a wireless Internet service designed to cover wide geographical areas serving
large number of users at low cost.
WiMAX is IEEE 802.16 standard defining wide area (Wireless MAN) wireless data
networking.
A WiMAX system consists of two parts:
• A Transmitter
A single WiMAX tower can provide coverage to a very large area – as big as
3,000 sq. miles.
• A Receiver
The receiver and antenna could be a small box or PCMCIA card or they could
built into a laptop as the way Wi-Fi access is today.
A fixed dish antenna points straight at the WiMAX tower from a rooftop
or pole. The line-of-sight connection is stronger and more stable, so it's able to
send a lot of data with fewer errors. Line-of-sight transmissions use higher
frequencies, with ranges reaching a possible 66 GHz. At higher frequencies, there
is less interference and lots more bandwidth.
Advantages:
Disadvantages:
• Line-of-Sight is required for long distance (5-30 mile) connections.
• Heavy rains can disrupt the service.
• Other wireless electronics in the vicinity can interfere with the WiMAX
connection and cause a reduction in data throughput or even a total disconnect.
• Wi-Fi runs on the Media Access Control's CSMA/CA protocol, which is connectionless
and contention based, whereas WiMAX runs a connection-oriented MAC.
• WiMAX and Wi-Fi have quite different quality of service (QoS) mechanisms:
WiMAX uses a QoS mechanism based on connections between the base station
and the user device. Each connection is based on specific scheduling algorithms
Hardware Architecture:
Smart Cards
Smart Card is a plastic card with an embedded microprocessor and a memory large
enough to store programs made by the card-issuing company. The exact structure of a smart card
is specified by international standards: the plastic card must have dimensions of 85.60mm x
53.98mm x 0.80mm and must be able to bend a specified amount without damage for instance. A
printed circuit and an integrated circuit chip (microcontroller) are embedded on the card. As
silicon cannot handle bending very well, the chip must be very small. The printed circuit is a thin
gold plate that provides electrical contacts to the outside world and also protects the chip from
mechanical stress and electrical static.
Smart Cards do not have an internal power source but need power to operate. Therefore
they only operate when in the presence of a Card Accepting Device (CAD) which supplies their
power requirements. Most Smart Cards come into physical contact with CADs while others do
not.
Memory System
There are three main types of memory on cards:
• RAM. 1K. This is needed for fast computation and response. Only a tiny amount is
available.
• EEPROM (Electrically Erasable PROM). Between 1 to 24K. Unlike RAM, its contents
are not lost when power is. Applications can run off and write to it, but it is very slow and
one can only read/write to it so many (100 000) times.
• ROM. Between 8 to 24K. The Operating System and other basic software like encryption
algorithms are stored here.
Input/Output
This is via a single I/O port that is controlled by the processor to ensure that
communications are standardized, in the form of APDUs (A Protocol Data Unit).
In addition to providing the power and clock signals, the reader is responsible for opening a
communication channel between application software on the computer and the operating system
on the card. Nearly all Smart Card readers are actually reader/writers, that is, they allow an
application to write to the card as well as read from it.
The communication channel to a Smart Card is half-duplex. This means that data can either flow
from the IFD to the card or from the card to the IFD but data cannot flow in both directions at the
same time. The receiver is required to sample the signal on the serial line at the same rate as the
transmitter sends it in order for the correct data to be received. This rate is known as the bit rate
or baud rate. Data received by and transmitted from a Smart Card is stored in a buffer in the
Smart Card's RAM. As there isn't very much RAM, relatively small packets (10 - 100 bytes) of
data are moved in each message.
Operating Systems
The operating system found on the majority of Smart Cards implements a standard set of
commands (usually 20 - 30) to which the Smart Card responds. Smart Card standards such as
ISO 7816 and CEN 726 describe a range of commands that Smart Cards can implement. Most
Smart Card manufacturers offer cards with operating systems that implement some or all of these
standard commands (and possibly extensions and additions). The relationship between the Smart
Card reader and the Smart Card is a master/slave relationship. The reader sends a command to
the Smart Card, the card executes the command and returns the result (if any) to the reader and
waits for another command.
Microsoft released a miniaturized version of Windows for Smart Cards in late 1998, and
early versions of a Gnu O/S have been released.
File Systems
Most operating systems also support a simple file system based on the ISO 7816
standard. A Smart Card file is actually just a contiguous block. Files are organized in a
hierarchical tree format. Once a file is allocated, it cannot be extended and so files must be
created to be the maximum size that they are expected to be. Each file has a list of which parties
are authorized to perform which operations on it. There are different types of files: linear, cyclic,
transparent, SIM, etc. The usual create, delete, read, write and update file operations can be
performed on all of them. Certain other operations are supported only on particular types of files.
Type Special Operations Example
credit card account
Linear seek
table
Cyclic read next, read previous transaction log
Transparent read and write binary picture
SIM file encrypt, decrypt cellular telephone
Software
Smart Cards are either Soft-Mask or Hard-Mask, depending on whether most of the
application is in EEPROM or ROM. Hard-Mask cards are more expensive. Some application-
specific data/instructions always needs to be stored on EEPROM. Cards do not as a rule run
anything off RAM.
When programming a Smart Card, it is standard practice to get the program running on a
simulator first for debugging, since EEPROM can only be written to a finite number of times in
its lifetime.
Test-running also happens on a different level: banks commonly use a soft mask card for
pilot testing new applications and then to move on to more customer-resistant hard mask cards
for larger deployments. However, some applications have limited deployments that are never
taken to hard mask, as hard masking is expensive in both time and money. Hard masks also may
not be justified for some applications, such as an employee identification card for small
companies.
Programming Languages
Most SmartCards are currently programmed in low-level languages based on proprietary
SmartCard operating systems. Some of the programming has been done in the chip's native
instruction set (generally Motorola 6805, Intel 8051, or Hitachi H8).
In 1998- 2000, a new type of card has shown up, sometimes called a re-configurable card.
These have a more robust operating system that permits the addition or deletion of application
code after the card is issued. Such cards are generally programmed in Java and are therefore
called Java Cards. Other relatively popular languages relate to Windows for SmartCards or MEL
(the Multos programming language) or even Basic.
All in all smart Cards have a number of advantages over magnetic stripe cards:
• Greater reliability.
• Reduction in tampering and counterfeiting – due to high security mechanisms.
Storage capacity is increased by up to 100 times.
• Smartcards are multi-functional.
• The anticipated working life of a smartcard is ten years compared to that of a magnetic
stripe card at three.
1). How the card data is read and written 2). The type of chip implanted within the card
and its capabilities.
system.
The most immediate areas in which Smart Cards have been establishing their positions include:
• Financial services - Financial institutions are looking to use Smart Cards to deliver
higher value-added services to businesses and consumers at a lower cost per transaction.
These services include money on a card, corporate card programs, and targeted marketing
programs based on analysis of consumers' buying patterns.
• Affinity programs - Airlines, retailers, and other companies that offer a range of ancillary
services and loyalty programs along with their basic product want to use Smart Cards to
deliver these programs with a higher level of service, improved ease of use, and at a
lower cost. For example, airlines want to use Smart Cards not only as a vehicle for
issuing and carrying tickets - even though the single benefit of being able to securely
order/provide a ticket directly to chip cards via the Internet is substantial. Airlines also
want to use the cards to provide tie-ins to their frequent-flyer programs and to cross-
marketing deals with auto rentals and hotels, as well as to provide simplified access to
private airline lounges.
• Cellular phones - Cellular phone services in the United States are losing $1.5 million per
day because of fraud. Although Smart Cards offer a mechanism to secure cellular phones
against fraudulent use, only Java Cards offer the ability to download new functions into a
phone in real time.
• Set-top boxes - Subscription satellite and cable services suffer from fraud problems
similar to those in the cellular phone business. Once again, Java Cards offer security and
the ability to add/update customer functions available to consumers in real time.
• Secure network access - Smart Cards can carry an individual's digital signature. With this
ability, they provide a special mechanism to secure access to computer networks within a
corporation, they help ensure that only individuals with the proper authority can get
access to specific network resources, and they reduce the likelihood that hackers can
break into a system.
SIM:
A SIM is held on a removable SIM card, which can be transferred between different
mobile devices. SIM cards were first made the same size as a credit card (85.60 mm × 53.98 mm
× 0.76 mm). The development of physically smaller mobile devices prompted the development
of a smaller SIM card, the mini-SIM card. Mini-SIM cards have the same thickness as full-size
cards, but their length and width are reduced to 25 mm × 15 mm.
A SIM card contains its unique serial number (ICCID), internationally unique number of
the mobile user (IMSI), security authentication and ciphering information, temporary nformation
related to the local network, a list of the services the user has access to and two passwords (PIN
for usual use and PUK for unlocking).
Design
There are three operating voltages for SIM cards: 5 V, 3 V and 1.8 V. The operating
voltage of the majority of SIM cards launched before 1998 was 5 V. SIM cards produced
subsequently are compatible with 3 V and 5 V or with 1.8 V and 3 V.
Dual SIM phones are now made by some mobile phone manufacturers, which save the
user from carrying around a separate phone for every number. There are two types: the first
allows one to switch between the SIMs, whilst the second allows both SIMs to be active
simultaneously.
SIM operating systems come in two main types: native and Java Card. Native SIMs are
based on proprietary, vendor-specific software, whereas the Java Card SIMs are based on
standards, particularly Java Card, which is a subset of the Java programming language
specifically targeted at embedded devices. Java Card allows the SIM to contain programs that are
hardware independent and interoperable.
Data
ICCID
Each SIM is internationally identified by its Integrated circuit card identifier (ICCID).
ICCIDs are stored in the SIM cards and are also engraved or printed on the SIM card body
during a process called personalization. The ICCID is defined by the ITU-T recommendation
E.118 as the Primary Account Number. The GSM Phase 1 defined the ICCID length as 10 octets
with operator-specific structure.
Check digit
• Single digit calculated from the other digits using the Luhn algorithm.
SIM cards are identified on their individual operator networks by a unique IMSI. Mobile
operators connect mobile phone calls and communicate with their market SIM cards using their
IMSIs. The format is:
The Ki is a 128-bit value used in authenticating the SIMs on the mobile network. Each
SIM holds a unique Ki assigned to it by the operator during the personalization process. The Ki is
also stored in a database (known as Authentication Center or AuC) on the carrier's network.
Authentication process:
1. When the Mobile Equipment starts up, it obtains the International Mobile Subscriber
Identity (IMSI) from the SIM card, and passes this to the mobile operator requesting
access and authentication. The Mobile Equipment may have to pass a PIN to the SIM
card before the SIM card will reveal this information.
2. The operator network searches its database for the incoming IMSI and its associated Ki.
3. The operator network then generates a Random Number (RAND, which is a nonce) and
signs it with the Ki associated with the IMSI (and stored on the SIM card), computing
another number known as Signed Response 1 (SRES_1).
4. The operator network then sends the RAND to the Mobile Equipment, which passes it to
the SIM card. The SIM card signs it with its Ki, producing SRES_2, which it gives to the
Mobile Equipment along with encryption key Kc. The Mobile Equipment passes SRES_2
on to the operator network.
5. The operator network then compares its computed SRES_1 with the computed SRES_2
that the Mobile Equipment returned. If the two numbers match, the SIM is authenticated
and the Mobile Equipment is granted access to the operator's network. Kc is used to
encrypt all further communications between the Mobile Equipment and the network.
Location area identity
The SIM stores network state information, which is received from the Location Area
Identity (LAI). Operator networks are divided into Location Areas, each having a unique LAI
number. When the device changes locations, it stores the new LAI to the SIM and sends it back
to the operator network with its new location. If the device is power cycled, it will take data off
the SIM, and search for the previous LAI. This saves time by avoiding having to search the
whole list of frequencies that the telephone normally would.
Most SIM cards will orthogonally store a number of SMS messages and phone book
contacts. The contacts are stored in simple 'Name and number' pairs: entries containing multiple
phone numbers and additional phone numbers will usually not be stored on the SIM card. When
a user tries to copy such entries to a SIM the handset's software will break them up into multiple
entries, discarding any information that isn't a phone number. The number of contacts and
messages stored depends on the SIM; early models would store as few as 5 messages and 20
contacts while modern SIM cards can usually store over 250 contacts.
Formats
Micro-SIM and mini-SIM, as normally supplied in full-sized carrier cards
SIM cards are available in three standard sizes. The first is the size of a credit card
(85.60 mm × 53.98 mm × 0.76 mm). The newer, most popular version has the same thickness,
but has a length of 25 mm and a width of 15 mm, and has one of its corners truncated
(chamfered) to prevent misinsertion. The newest incarnation, known as the micro-SIM or 3FF,
has dimensions of 15 mm × 12 mm. Most cards of the two smaller sizes are supplied as a credit
card size with the smaller standard card held in place by a few plastic links; it can easily be
broken off to be used in a device that uses the smaller SIM.
The mini-SIM card has the same contact arrangement as the full-size SIM card and is
normally supplied within a full-size card carrier, attached by a number of linking pieces. This
arrangement allows for such a card to be used in a device requiring a full-size card, or to be used
in a device requiring a mini-SIM card after cleanly breaking the scorings manufactured in the
outline of a mini-SIM card.
Even smaller device sizes have prompted the development of a yet smaller card size, the
3FF card or micro-SIM. Micro-SIM cards have the same thickness and contact arrangement
again, but the length and width are further reduced to 15 mm × 12 mm. The specifications for the
3FF card or micro-SIM also include additional functionality beyond changing the physical card
size.
SCHOOL OF COMPUTING
✓ It can run on many different devices from many different manufacturers. Android
includes a software development kit (SDK) that helps you write original code and
assemble software modules to create apps for Android users.
✓ Android also provides a marketplace to distribute apps. All together, Android represents
an ecosystem for mobile apps.
✓ Android is an open source and Linux-based Operating System for mobile devices such as
smartphones and tablet computers. Android was developed by the Open Handset
Alliance, led by Google, and other companies.
✓ Android offers a unified approach to application development for mobile devices which
means developers need only develop for Android, and their applications should be able to
run on different devices powered by Android.
✓ The first beta version of the Android Software Development Kit (SDK) was released by
Google in 2007 where as the first commercial version, Android 1.0, was released in
September 2008.
✓ On June 27, 2012, at the Google I/O conference, Google announced the next Android
version, 4.1 Jelly Bean. Jelly Bean is an incremental update, with the primary aim of
improving the user interface, both in terms of functionality and performance.
✓ The source code for Android is available under free and open source software licenses.
Google publishes most of the code under the Apache License version 2.0 and the rest,
Linux kernel changes, under the GNU General Public License version 2.
Figure 2.1 Features of Android
1 Beautiful UI
2 Connectivity
GSM/EDGE, IDEN, CDMA, EV-DO, UMTS, Bluetooth, Wi-Fi, LTE, NFC and
WiMAX.
3 Storage
4 Media support
H.263, H.264, MPEG-4 SP, AMR, AMR-WB, AAC, HE-AAC, AAC 5.1, MP3,
MIDI, Ogg Vorbis, WAV, JPEG, PNG, GIF, and BMP.
5 Messaging
6 Web browser
7 Multi-touch
Android has native support for multi-touch which was initially made available in
handsets such as the HTC Hero.
8 Multi-tasking
User can jump from one task to another and same time various application can
run simultaneously.
9 Resizable widgets
Widgets are resizable, so users can expand them to show more content or shrink
them to save space.
10 Multi-Language
Supports single direction and bi-directional text.
There are many android applications in the market. The top categories are −
History of Android
1) Initially, Andy Rubin founded Android Incorporation in Palo Alto, California, United States in
October, 2003.
2) In 17th August 2005, Google acquired android Incorporation. Since then, it is in the subsidiary
of Google Incorporation.
3) The key employees of Android Incorporation are Andy Rubin, Rich Miner, Chris
White and Nick Sears.
4) Originally intended for camera but shifted to smart phones later because of low market for
camera only.
5) Android is the nick name of Andy Rubin given by coworkers because of his love to robots.
❖ Java
❖ Kotlin
Developing the Android Application using Kotlin is preferred by Google, as Kotlin is made an
official language for Android Development, which is developed and maintained by JetBrains.
Previously before the Java is considered the official language for Android Development. Kotlin
is made official for Android Development in Google I/O 2017.
While the Android platform provides rich functionality for app development, there are still a
number of challenges you need to address, such as:
✓ Apps: Your apps live at this level, along with core system apps for email, SMS
messaging, calendars, internet browsing, and contacts.
✓ Libraries and Android runtime: Each app runs in its own process, with its own
instance of the Android runtime. Android includes a set of core runtime libraries that
provide most of the functionality of the Java programming language. Many core Android
system components and services are built from native code that require native libraries
written in C and C++. These native libraries are available to apps through the Java API
framework.
This layer provides standard interfaces that expose device hardware capabilities to the
higher-level Java API framework. The HAL consists of multiple library modules, each of
which implements an interface for a specific type of hardware component, such as the
camera or Bluetooth module.
✓ Linux kernel:
The foundation of the Android platform is the Linux kernel. The layers above the Linux
kernel rely on the Linux kernel for threading, low-level memory management, and other
underlying functionality. Using a Linux kernel enables Android to take advantage of
Linux-based security features and allows device manufacturers to develop hardware
drivers for a well-known kernel
✓ Applications: Built-in applications, such as phone, contacts, browser, and more. The
specific applications vary by Android version and manufacturer. Commercial
applications from market places, such as Google Play, Amazon, and more. Side-loaded
applications, including the ones you will build. You install these via USB cable.
✓ Libraries, such as graphics libraries, media libraries, database libraries, sensors, and so
on.
✓ The Android runtime is responsible for executing and managing applications as they
run.
✓ Linux Kernel, including power, file system, drivers, process management, and more.
Android Architecture
1. Linux kernel
2. native libraries (middleware),
3. Android Runtime
4. Application Framework
5. Applications
Figure 2.5. Android Architecture
✓ Applications –
Applications is the top layer of android architecture. The pre-installed applications like home,
contacts, camera, gallery etc and third party applications downloaded from the play store like
chat applications, games etc. will be installed on this layer only.
It runs within the Android run time with the help of the classes and services provided by the
application framework.
✓ Application framework –
Application Framework provides several important classes which are used to create an Android
application. It provides a generic abstraction for hardware access and also helps in managing the
user interface with application resources. Generally, it provides the services with the help of
which we can create a particular class and make that class helpful for the Applications creation.
It includes different types of services activity manager, notification manager, view system,
package manager etc. which are helpful for the development of our application according to the
prerequisite.
✓ Application runtime –
Android Runtime environment is one of the most important part of Android. It contains
components like core libraries and the Dalvik virtual machine(DVM). Mainly, it provides the
base for the application framework and powers our application with the help of the core libraries.
Like Java Virtual Machine (JVM), Dalvik Virtual Machine (DVM) is a register-based virtual
machine and specially designed and optimized for android to ensure that a device can run
multiple instances efficiently. It depends on the layer Linux kernel for threading and low-level
memory management. The core libraries enable us to implement android applications using the
standard JAVA or Kotlin programming languages.
✓ Platform libraries –
The Platform Libraries includes various C/C++ core libraries and Java based libraries such as
Media, Graphics, Surface Manager, OpenGL etc. to provide a support for android development.
✓ Media library provides support to play and record an audio and video formats.
✓ Surface manager responsible for managing access to the display subsystem.
✓ SGL and OpenGL both cross-language, cross-platform application program interface
(API) are used for 2D and 3D computer graphics.
✓ SQLite provides database support and FreeType provides font support.
✓ Web-Kit This open source web browser engine provides all the functionality to display
web content and to simplify page loading.
✓ SSL (Secure Sockets Layer) is security technology to establish an encrypted link
between a web server and a web browser.
✓ Linux Kernel –
Linux Kernel is heart of the android architecture. It manages all the available drivers such as
display drivers, camera drivers, Bluetooth drivers, audio drivers, memory drivers, etc. which are
required during the runtime.
The Linux Kernel will provide an abstraction layer between the device hardware and the other
components of android architecture. It is responsible for management of memory, power, devices
etc.
✓ Security: The Linux kernel handles the security between the application and the system.
✓ Memory Management: It efficiently handles the memory management thereby
providing the freedom to develop our apps.
✓ Process Management: It manages the process well, allocates resources to processes
whenever they need them.
✓ Network Stack: It effectively handles the network communication.
✓ Driver Model: It ensures that the application works properly on the device and hardware
manufacturers responsible for building their drivers into the Linux build.
1. SDK tools
2. Platform tools
1. 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 –
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
7 sqlite3
Lets you access the SQLite data files created and used by Android applications
traceview
8
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.
1. Activities: An application that has a visible user interface is implemented via an activity.
When you select an application from the Home screen or application launcher, an activity
is started.
2. Services: You can use a service for any application that needs to persist for a long time,
such as a network monitor or update-checking application.
3. Content providers: The easiest way to think about content providers is to view them as a
database server. A content provider’s job is to manage access to persisted data, such as
the contacts on a phone. If your application is very simple, you might not necessarily
create a content provider, however if you are building a larger application or one which
makes data available to multiple activities and/or applications, a content provider is the
proscribed means of accessing your data.
OOPs Concepts:
✓ Class
✓ Objects
✓ Data Abstraction
✓ Encapsulation
✓ Inheritance
✓ Polymorphism
✓ Dynamic Binding
✓ Message Passing
Apart from these concepts, there are some other terms which are used in Object-Oriented design:
✓ Coupling
✓ Cohesion
✓ Association
✓ Aggregation
✓ Composition
1. Class:
A class is a user-defined data type. It consists of data members and member functions, which
can be accessed and used by creating an instance of that class. It represents the set of
properties or methods that are common to all objects of one type. A class is like a blueprint
for an object.
For Example: Consider the Class of Cars. There may be many cars with different names
and brands but all of them will share some common properties like all of them will have
4 wheels, Speed Limit, Mileage range, etc. So here, Car is the class, and wheels, speed
limits, mileage are their properties.
2. Object:
3. Data Abstraction:
Data abstraction is one of the most essential and important features of object-oriented
programming. Data abstraction refers to providing only essential information about the data to
the outside world, hiding the background details or implementation. Consider a real-life example
of a man driving a car. The man only knows that pressing the accelerators will increase the speed
of the car or applying brakes will stop the car, but he does not know about how on pressing the
accelerator the speed is increasing, he does not know about the inner mechanism of the car or the
implementation of the accelerator, brakes, etc in the car. This is what abstraction is.
Object Drierrted Programming : Abstraction
Abstraction refers to the quality of dealing with ideas rather than events. It
basically deals with hiding the details and showing the essential things to the
user. If you look at the image here, whenever we get a call, we get an option to
either pick it up or just reject it. But in reality, there is a lot of code that runs in
the background. So you don’t know the internal processing of how a call is
generatecl, thar’s the beauty of abstraction. Therefore, abstraction helps to
reduce complexity. You can achieve abstraction in two ways:
b) Interface
Abstract class: Abstract class in java contains the ’abstract' keyword. Now what does the abstract
keyword mean? If a class is declared abstract, it cannot be instantiated, which means you czinnot
create an object of an abstract EIBSS. Also, an abstract class can contain abstract as well as concrete
methods.
NOte. You Ean achieve 0-100% abstraction using abstract class.
To use an abstract class, you hZlve to inherit it from another class where you have to provide
implementations for the abstract methods there itself, else it will also become an abstract class.
Interface: Interface in java is a blueprint of a class or you can say it is a collection of abstract
methods and static constants. In an interface, each method is publiE and abstract but it does not
contain any constructor. Along with abstraction, interface also helps to achieve multiple inheritanEe
So an interface basically is a group of related methods with empty bodies. Ler us understand
interfaces beEer by taking an example ofa ’ParentCar' interfaEe with its related methods.
An interface is declared by using the interface keyword. It provides total abstraction; means all
the methods in an interface are declared with the empty body, and all the fields are public, static
and final by default. A class that implements an interface must implement all the methods
declared in the interface.
In other words, Interface fields are public, static and final by default, and the methods are
public and abstract.
Figure 2. 10 The relationship between classes and interfaces
As shown in the figure given below, a class extends another class, an interface extends another
interface, but a class implements an interface.
4. Encapsulation:
Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism that
binds together code and the data it manipulates. In Encapsulation, the variables or data of a class
are hidden from any other class and can be accessed only through any member function of their
class in which they are declared. As in encapsulation, the data in a class is hidden from other
classes, so it is also known as data-hiding.
Consider a real-life example of encapsulation, in a company, there are different sections like the
accounts section, finance section, sales section, etc. The finance section handles all the financial
transactions and keeps records of all the data related to finance. Similarly, the sales section
handles all the sales-related activities and keeps records of all the sales. Now there may arise a
situation when for some reason an official from the finance section needs all the data about sales
in a particular month. In this case, he is not allowed to directly access the data of the sales
section. He will first have to contact some other officer in the sales section and then request him
to give the particular data. This is what encapsulation is. Here the data of the sales section and
the employees that can manipulate them are wrapped under a single name “sales section”.
5. Inheritance:
Ctac s B ext:ends A {
2. Multilevel Inheritance:
When a class is derived from a class which is aI5o derived from another class,
i.e. a class having more than one parent class but at different levels, such type
of inheritance is called Multilevel Inheritance
If we talk about the flowchart, class B inherits the properties and behavior of
class A and class C inherits the propenies of class B. Here A is the parent class
for B and class B is the parent class for C. So in this case class C implictly
inherits the properties and methods of class A along with Class B. That’s what is
multilevel inheritance.
C 1as s B ext:ends A{
C 1as s C ext:ends B{
7. Dynamic Binding:
Binding means matching the function call with the correct function definition by the compiler. It
takes place either at compile time or at runtime.
Figure 2. 13. Types of Binding
✓ In early binding, the compiler matches the function call with the correct function
definition at compile time. It is also known as Static Binding or Compile-time Binding.
✓ In the case of late binding, the compiler matches the function call with the correct
function definition at runtime. It is also known as Dynamic Binding or Runtime Binding.
8. Message Passing:
Message Passing is nothing but sending and receiving of information by the objects same as
people exchange information. So this helps in building systems that simulate real life. Following
are the basic steps in message passing.
In OOPs, Message Passing involves specifying the name of objects, the name of the function,
and the information to be sent.
Coupling:
✓ You can use interfaces for the weaker coupling because there is no concrete
implementation.
Cohesion:
✓ Cohesion refers to the level of a component which performs a single well-defined task.
✓ A single well-defined task is done by a highly cohesive method. The weakly cohesive
method will split the task into separate parts.
✓ The java.io package is a highly cohesive package because it has I/O related classes and
interface.
✓ However, the java.util package is a weakly cohesive package because it has unrelated
classes and interfaces.
Association:
✓ Association represents the relationship between the objects. Here, one object can be
associated with one object or many objects.
• One to One
• One to Many
• Many to One, and
• Many to Many
For example, One country can have one prime minister (one to one), and a prime minister can
have many ministers (one to many). Also, many MP's can have one prime minister (many to
one), and many ministers can have many departments (many to many).Association can be
unidirectional or bidirectional.
Aggregation:
✓ Aggregation represents the relationship where one object contains other objects as a part
of its state.
Composition:
✓ Java doesn’t support multiple inheritances but by using composition we can achieve it.
✓ By using composition, we can also change the member objects at run time, to
dynamically change the behavior of your program.
Threads
✓ Threads allow a program to operate more efficiently by doing multiple things at the same
time.
✓ Threads can be used to perform complicated tasks in the background without interrupting
the main program.
1) It doesn't block the user because threads are independent and you can perform
multiple operations at the same time.
✓ A thread is a lightweight sub process, the smallest unit of processing. It is a separate path
of execution.
✓ Threads are independent. If there occurs exception in one thread, it doesn't affect other
threads. It uses a shared memory area.
Multitasking
• Each process has an address in memory. In other words, each process allocates a separate
memory area.
• A process is heavyweight.
• Switching from one process to another requires some time for saving and
loading registers, memory maps, updating lists, etc.
• A thread is lightweight.
• Cost of communication between the thread is low.
A thread can be in one of the five states. According to sun, there is only 4 states in thread life
cycle in java new, runnable, non-runnable and terminated. There is no running state.
But for better understanding the threads, we are explaining it in the 5 states.The life cycle of the
thread in java is controlled by JVM. The java thread states are as follows:
1.New
2.Runnable
3. Running
4.Non-Runnable (Blocked)
5. Terminated
1) New
The thread is in new state if you create an instance of Thread class but before the invocation of
start() method.
2) Runnable
The thread is in runnable state after invocation of start() method, but the thread scheduler has not
selected it to be the running thread.
3) Running
The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.
5) Terminated
✓ If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading.
✓ If we have to perform only one operation, having same name of the methods increases the
readability of the program.
✓ Suppose you have to perform addition of the given numbers but there can be any number
of arguments, if you write the method such as a(int,int) for two parameters, and
b(int,int,int) for three parameters then it may be difficult for you as well as other
programmers to understand the behavior of the method because its name differs.
In this example, we have created two methods, first add() method performs addition of two
numbers and second add method performs addition of three numbers.
In this example, we are creating static methods so that we don't need to create instance for calling
methods.
class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
In this example, we have created two methods that differs in data type. The first add method
receives two integer arguments and second add method receives two double arguments.
class Adder{
static int add(int a, int b){return a+b;}
static double add(double a, double b){return a+b;}
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}
Method overriding in Java.
If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in Java.
In other words, If a subclass provides the specific implementation of the method that has been
declared by one of its parent class, it is known as method overriding.
1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).
Consider a scenario where Bank is a class that provides functionality to get the rate of interest.
However, the rate of interest varies according to banks. For example, SBI, ICICI and AXIS
banks could provide 8%, 7%, and 9% rate of interest.
Figure 2. 15 A real example of Java Method Overriding
✓ The JVM manages system memory and provides a portable execution environment for
Java-based applications.
✓ JVMs are available for many hardware and software platforms (i.e. JVM is platform
dependent). It is:
• Runtime Instance Whenever you write java command on the command prompt
to run the java class, an instance of JVM is created.
• Loads code
• Verifies code
• Executes code
• Memory area
• Class file format
• Register set
• Garbage-collected heap
1) Class Loader The class loader is a subsystem used for loading class files. It performs three
major functions viz. Loading, Linking, and Initialization.
2) Method Area
JVM Method Area stores class structures like metadata, the constant runtime pool, and the code
for methods.
3) Heap
All the Objects, their related instance variables, and arrays are stored in the heap. This memory is
common and shared across multiple threads.
5) PC Registers
PC register store the address of the Java virtual machine instruction which is currently executing.
In Java, each thread has its separate PC register.
Native method stacks hold the instruction of native code depends on the native library. It is
written in another language instead of Java.
7) Execution Engine
It is a type of software used to test hardware, software, or complete systems. The test execution
engine never carries any information about the tested product.
The Native Method Interface is a programming framework. It allows Java code which is running
in a JVM to call by libraries and native applications.
Native Libraries is a collection of the Native Libraries(C, C++) which are needed by the
Execution Engine.
In order to write and execute a software program, you need the following
✓ Editor – To type your program into, a notepad could be used for this
✓ Compiler – To convert your high language program into native machine code
✓ Linker – To combine different program files reference in your main program together.
✓ Loader – To load the files from your secondary storage device like Hard Disk, Flash
Drive, CD into RAM for execution. The loading is automatically done when you execute
your code.
✓ Execution – Actual execution of the code which is handled by your OS & processor.
SCHOOL OF COMPUTING
Development Tools: Installing and using Eclipse with ADT plug-in, Installing Virtual machine for
Android sandwich/Jelly bean (Emulator), configuring the installed tools, creating an android
project – Hello Word, run on emulator, Deploy it on USB-connected Android device. The
manifest file - Layout resource - User Interface Architecture: Application context, intents,
Activity life cycle, multiple screen sizes.
➢ The Android Software Development Kit (Android SDK) contains the necessary tools to
create, compile and package Android applications.
➢ The Android SDK contains the Android debug bridge (adb), which is a tool that allows you
to connect to a virtual or real Android device, for the purpose of managing the device or
debugging your application.
➢ The Android SDK contains a tool called dx which converts Java class files into a .dex
(Dalvik Executable) file.
➢ The Android tooling uses Gradle as build system.
➢ Android Studio includes a debugging tool called the Dalvik Debug Monitor Server (DDMS),
which provides port-forwarding services, screen capture on the device, thread and heap
information on the device, logcat, process, and radio state information, incoming call and
SMS spoofing, location data spoofing, and more.
➢ Android requires that all apps be digitally signed with a certificate before they can be
installed. Android uses this certificate to identify the author of an app, and the certificate
does not need to be signed by a certificate authority.
➢ Android apps often use self-signed certificates. The app developer holds the certificate's
private key.
Android offers a custom plugin for the Eclipse IDE, called Android Development
Tools (ADT). This plugin provides a powerful, integrated environment in which to
develop Android apps. It extends the capabilities of Eclipse to let you quickly set up
new Android projects, build an app UI, debug your app, and export signed (or
unsigned) app packages (APKs) for distribution.
If you need to install Eclipse, you can download it from eclipse.org/mobile.
Note: If you prefer to work in a different IDE, you do not need to install Eclipse or
ADT. Instead, you can directly use the SDK tools to build and debug your
application.
1. Once Eclipse restarts, you must specify the location of your Android SDK
directory:
2. In the "Welcome to Android Development" window that appears, select Use
existing SDKs.
3. Browse and select the location of the Android SDK directory you recently
downloaded and unpacked.
4. Click Next.
5. Your Eclipse IDE is now set up to develop Android apps, but you need to add
the latest SDK platform tools and an Android platform to your environment.
To get these packages for your SDK, continue to Adding Platforms and
Packages.
Troubleshooting Installation
1. If you are having trouble downloading the ADT plugin after following the
steps above, here are some suggestions:
2. If Eclipse can not find the remote update site containing the ADT plugin, try
changing the remote site URL to use http, rather than https. That is, set the
Location for the remote site to:
3. http://dl-ssl.google.com/android/eclipse/
4. If you are behind a firewall (such as a corporate firewall), make sure that you
have properly configured your proxy settings in Eclipse. In Eclipse, you can
configure proxy information from the main Eclipse menu in Window (on
Mac OS X, Eclipse) > Preferences > General > Network Connections.
If you are still unable to use Eclipse to download the ADT plugin as a remote update
site, you can download the ADT zip file to your local machine and manually install
it:
To update your plugin once you've installed using the zip file, you will have to
follow these steps again instead of the default update instructions.
Step 2: Click on new and enter a name and the operating system details for the
virtual machine. Select type as Linux and version as other and click next.
Step 3: Enter the amount of ram you would like to allot for the virtual machine
and click next. Android 4.3 requires at least 1Gb of ram but its not necessary.
Step 4: In the next window select ― Create a virtual hard disk ― and then select VDI .
Step 5: According to your space requirement you can either select dynamically
allocated or fixed size for your storage space . i selected fixed size because i
want to allocate only 8Gb of storage space to android.
Step 6: Your virtual machine is now set. all you need to do is add the location of
the Android 4.3 image file. Click on the settings button in virtualbox. Under the
settings navigate to storage, below the storage tree select empty and click on the
disk image and select ― choose a virtual CD/DVD disk file ― and select the
android 4.3 image. Check the Live CD/DVD box and click ok.
Step 7: Double click on your virtual machine to start it and click OK for all the
dialog boxes . Select Install Android-X86 to hard disk and click OK for all the
dialog boxes .
Step 8: in the next window you have to create a partition for installing Android.
The new partition will not mess up anything with your windows computer. From
now onwards you have to use your up, down, left and right keys on your
keyboard to Select ―create/modify partitions ― and click OK.
Step 9: In the next windows select new > primary and then specify the size of the new
partition
Step 10: Your new partition has been created. Select write and press enter and
type ―yes ― and press enter again when prompted. In the next window select quit
and press enter.
Step 11: In the next window select the Sda1 and press enter. select the et3 file
system and press enter. When prompted to install grub loader select yes. Select
now when prompted to make system directory as read-write.
Step 12: Now android 4.3 is successfully installed on your virtual machine.
select Run Android 4.3 and press enter. click OK for any other dialog boxes that
appear. You will now see the android loading screen.
Step 13: Select your language and enter, now fill in the Gmail details and all the details
that are asked.
Step 14: Now We have successfully installed Android 4.3 on windows computer.
➢ In order to uninstall the android 4.3 virtual box, right click on the virtual machine and
select remove. Next select
―delete all files‖ to remove Android 4.3 completely from PC.
• Using the Work with drop-down menu, select the Google ADT entry that you added in the
previous step
• Wait for the package list to be populated
• Select all the resulting ADT packages
• Click the Next button
• Click the Next button on the Install Details screen that follows
• Select each package in turn from the left-hand pane and accept the respective license
agreement
• Click the Finish button
• Once the installation is complete, click the Restart Now button
• Using the Project Explorer tab in the left-hand pane, right-click an existing project and
select Open Project
• Browse the resulting project file list, right-click tiapp.xml in root of project, select Open
With > TiApp Editor
• Choose your preferred Titanium SDK version from the SDK Version drop-down list
• Check the Android SDK / Target Android Platform section of the Titanium
Compatibility Matrix, to determine which Android versions are compatible with
your chosen Titanium SDK. For example, Titanium SDK 1.6.X is compatible with
Android versions 1.6 to 2.3. This information will be needed for the configuration
in the following steps
• Close tiapp.xml
• From the Studio menu, select Window > Preferences or Studio >
Preference for Mac OS X to open the Preferences dialog
• Navigate to Android
• Click the Browse... button to configure the Android SDK Location
• Select a target Android SDK from the list, ensuring that its version is within the
range compatible with the Titanium SDK you have chosen, as discovered in the
previous step
• Navigate to Studio > Platforms > Android
• Click the Browse... button to configure the Android SDK Home
• Select a target Android SDK from the Default Android SDK drop-down list,
ensuring that its version is within the range compatible with the Titanium SDK you
have chosen, as discovered in the previous step
• Click OK to save preference changes
As explained in the Android SDK / Target Android Platform, if you require
advanced Android features, such Maps, remember to choose a target that includes
the enhanced Google APIs, listed as Google APIs in
the Default
Android SDK
list Launch the
emulator and
app
• Using the Project Explorer, select the project that was opened earlier
• Using the Launch toolbar button, located between the Project Explorer tab and
its file list, select Android Emulator to launch the project app
Add the DDMS perspective button
• While the emulator boots, open the ADT perspective. From the Studio menu bar,
select the Window > Open Perspective > Other...
• Select DDMS (which stands for, Dalvik Debug Monitor Server) from the list of available
perspectives
• To ensure that the perspective is in its default state, select the Window > Reset
Perspective... menu
Click the OK button, when the resulting Do you want to reset the current
DDMS perspective to its defaults?dialog displays
• Click the LogCat viewer tab above the bottom pane, to watch the console output while the
emulator boots
• If you wish, you may relocate this tab to the main pane, next to the File Explorer
tab, using a simple drag and drop gesture
• To show only Ti.API log messages, create a logcat filter using the green plus icon
in the logcat toolbar and set the by Log Tag field to "TiAPI". See Reading and
Writing Logs for more information about logcat filters.
• Once booted, unlock the emulator and wait for the app to launch
• Now that the emulator is running, select it from the list of devices in the left-hand
pane, and inspect it using the tools
• For example, select the File Explorer tab, and navigate to the directory
/data/data/yourAppId
the project was created, as shown in the TiApp Editor (see below)
These are the settings. As of this writing, these settings make Hello World app
compatible with 97% of Android devices active on the Google Play Store.
8. Leave unchecked the Include Instant App support and all other options.
Then click Next. If your project requires additional components for your
chosen target SDK, Android Studio will install them automatically.
9. The Add an Activity window appears. An Activity is a single, focused thing
that the user can do. It is a crucial component of any Android app. An
Activity typically has a layout associated with it that defines how UI elements
appear on a screen. Android Studio provides Activity templates to help you
get started. For the Hello World project, choose Empty Activity as shown
below, and click Next.
10. The Configure Activity screen appears (which differs depending on which
template you chose in the previous step). By default, the empty Activity
provided by the template is named MainActivity. You can change this if you
want, but this lesson uses MainActivity.
11. Make sure that the Generate Layout file option is checked. The
layout name by default is activity_main. You can change this if you want,
but this lesson uses activity_main.
12. Make sure that the Backwards Compatibility (App Compat) option is
checked. This ensures that your app will be backwards-compatible with
previous versions of Android.
13. Click Finish.
below.
3. Click the MainActivity.java tab to see the code editor as shown below.
The manifests folder contains files that provide essential information about your app
to the Android system, which the system must have before it can run any of the app's
code.
1. Expand the manifests folder.
2. Open the AndroidManifest.xml file.
The AndroidManifest.xml file describes all of the components of your Android app.
All components for an app, such as each Activity, must be declared in this XML file.
In other course lessons you will modify this file to add features and feature
permissions. For an introduction, see App Manifest Overview.
➢ RUN ON EMULATOR
1. Lets create an android virtual device (avd). In order to run an emulator on your
computer, you have to create a configuration that describes the virtual device. In
Android Studio, select Tools > Android > AVD Manager, or click the AVD
Manager icon in the toolbar. The Your Virtual Devices screen appears. If
you've already created virtual devices, the screen shows them; otherwise you see a
blank list.
2. Click the +Create Virtual Device. The Select Hardware window appears
showing a list of pre configured hardware devices. For each device, the table
provides a column for its diagonal display size (Size), screen resolution in pixels
(Resolution), and pixel density (Density).
3. Choose a device such as Nexus 5x or Pixel XL, and click Next. The System Image
screen appears.
4. Click the Recommended tab if it is not already selected, and choose which version
of the Android system to run on the virtual device (such as Oreo).Click the link to
start the download, and click Finish when it's done.
5. After choosing a system image, click Next. The Android Virtual Device (AVD)
window appears. You can also change the name of the AVD. Check your
configuration and click Finish.
1. In Android Studio, choose Run > Run app or click the Run icon in the
toolbar.
2. The Select Deployment Target window, under Available Virtual
Devices, select the virtual device, which you just created, and click OK
The emulator starts and boots just like a physical device. Your app builds, and once
the emulator is ready, Android Studio will upload the app to the emulator and run it.
1. Open Settings.
2. Click Security.
3. Enable Unknown sources, that is, check this option. This permits the
device to install apps that do not originate from Google Play.
4. Back out to Settings.
5. Click Developer options.
6. If available: Set the switch in the title bar to on.
7. Enable USB debugging, that is, check this option. This permits the device
to install apps over a USB connection.
8. Optional: Enable Stay awake, that is, check this option. This option keeps
the screen on and disables the lock screen while the device is connected to
USB.
9. Optional: Enable Allow mock locations, that is, check this option. This
option creates fake GPS locations to test location services.
10. Back out of or close Settings.
Connect the Android device to your computer using an USB cord. Note that some
USB cables are only power cables and do not allow communications with the
device. Make sure you use a USB cable that allows a data connection.
For 4.2 devices, an "Allow USB debugging?" dialog will appear once
connected via USB. Click the OK button.
In Studio, first select the project in the Project Explorer view, then in the global
tool bar, select Run from the Launch Mode drop-down list and an Android
device from the Target drop-down list under the Android Application Installer
category. If the Launch Automatically option is enabled under the Target drop-
down list, the application will be automatically launched after the device is
selected. If not, you need to click the Run button to start the build process. Your
app will be built, installed to your device and automatically launched.
➢ APPLICATION CONTEXT
• Android devices come in all shapes and sizes, so your app's layout needs to be flexible.
That is, instead of defining your layout with rigid dimensions that assume a certain
screen size and aspect ratio, your layout should gracefully respond to different screen
sizes and orientations.
• The best way to create a responsive layout for different screen sizes is to use Constraint
Layout as the base layout in your UI. Constraint Layout allows you to specify the
position and size for each view according to spatial relationships with other views in the
layout. This way, all the views can move and stretch together as the screen size changes.
• The easiest way to build a layout with Constraint Layout is to use the Layout Editor in
Android Studio. It allows you to drag new views to the layout, attach their constraints to
the parent view and other sibling views, and edit the view's properties, all without editing
any XML by hand.
• FORM WIDGETS
• Widgets enable users to interact with an Android Studio application page. There are
various kinds of widgets, such as Buttons and TextViews.
• To see all the widgets at your disposal, create a new application project called ―Widgets‖
and select "empty activity". Call your activity ―MainActivity‖.
• There are two components of each Android activity: the XML (Extensible Markup
Language) design (the beauty) and the Java text (the brains).
• On the activity_main.xml page, you can see the full widgets palette underneath the various
layout options.
• As you can see, there are 20 widgets available for you to use. In this guide, we’ll discuss
TextViews and Buttons, which are probably the most common widgets in Android
development.
➢ TEXT FIELDDS
• A text field allows the user to type text into your app. It can be either single line or
multi-line. Touching a text field places the cursor and automatically displays the
keyboard. In addition to typing, text fields allow for a variety of other activities, such as
text selection (cut, copy, paste) and data look-up via auto-completion.
• You can add a text field to you layout with the EditText object. You should usually do
so in your XML layout with a <EditText> element.
• Text fields can have different input types, such as number, date, password, or email address.
➢ LAYOUTS
• A layout defines the visual structure for a user interface, such as the UI for an activity
or app widget. Each layout has a set of attributes which define the visual properties of
that layout. There are few common attributes among all the layouts and there are other
attributes which are specific to that layout. Following are common attributes and will
be applied to all the layouts.
➢ BUTTON CONTROL
• Button is a user interface control which is used to perform an action whenever the user
click or tap on it. Buttons in android will contains a text or an icon or both and perform
an action when user touches it. Different types of buttons available are ImageButton,
ToggleButton, RadioButton.
➢ TOGGLE BUTTONS
• A toggle button allows the user to change a setting between two states. You can add a
basic toggle button to your layout with the Toggle Button object. Android 4.0 (API
level 14) introduces another kind of toggle button called a switch that provides a slider
control, which you can add with a Switch object. Switch Compat is a version of the
Switch widget which runs on devices back to API 7.
➢ SPINNERS / COMBO BOXES
• Spinners provide a quick way to select one value from a set. In the default state, a
spinner shows its currently selected value. Touching the spinner displays a dropdown
menu with all other available values, from which the user can select a new one.
➢ IMAGES
public abstract class Image
extends Object implements AutoCloseable
java.lang.Object
↳ android.media.Image
• single complete image buffer to use with a media source such as a Media Codec or a
CameraDevice.This class allows for efficient direct application access to the pixel data of the
Image through one or more Byte Buffers. Each buffer is encapsulated in a Plane that describes
the layout of the pixel data in that plane. Due to this direct access, and unlike the Bitmap class,
Images are not directly usable as UI resources.
➢ MENU
• In android, Options Menu is a primary collection of menu items for an activity and it is
useful to implement actions that have a global impact on the app, such as Settings,
Search, etc. In case, if we define items for the options menu in both activity or fragment,
then those items will be combine and display in UI.
➢ DIALOG
• A dialog is a small window that prompts the user to make a decision or enter additional
information. A dialog does not fill the screen and is normally used for modal events that
require users to take an action before they can proceed.
• The Dialog class is the base class for dialogs, but you should avoid instantiating Dialog
directly. Instead, use one of the following subclasses:
• Alert Dialog : A dialog that can show a title, up to three buttons, a list of selectable
items, or a custom layout.
• DatePickerDialog or TimePickerDialog : A dialog with a pre-defined UI that allows the
user to select a date or time.
Method Description
onResume() called when activity will start interacting with the user.
onStart() callback method will invoke when an activity entered into Started State by
completing onCreate() method. The onStart() method will make an activity visible to the user and
this method execution will finish very quickly.
an activity entered into Resumed state, the system invokes onResume() call back method.
Resumed state until an another activity happens to take focus away from the app like getting a
phone call or screen turned off
After an activity returned from Paused state to Resumed state, the system again will
call onResume() method
onPause()
Whenever the user leaves an activity or the current activity is being Paused then the system
invokes onPause() method. The onPause() method is used to pause operations like stop playing
the music when the activity is in a paused state or pass an activity while switching from one app to
another app because every time only one app can be focused.
onStop()
The system will invoke onStop() callback method when an activity no longer visible to the user,
the activity will enter into Stopped state. This happens due to current activity entered
into Resumed state or newly launched activity covers complete screen or it’s been destroyed.
onRestart()
The system will invoke onRestart() method when an activity restarting itself after stopping it.
The onRestart() method will restore the state of activity from the time that is being stopped.
Example Program:
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("lifecycle","onCreate invoked");
}
@Override
protected void onStart() {
super.onStart();
Log.d("lifecycle","onStart invoked");
}
@Override
protected void onResume() {
super.onResume();
Log.d("lifecycle","onResume invoked");
}
@Override
protected void onPause() {
super.onPause();
Log.d("lifecycle","onPause invoked");
}
@Override
protected void onStop() {
super.onStop();
Log.d("lifecycle","onStop invoked");
}
@Override
protected void onRestart() {
super.onRestart();
Log.d("lifecycle","onRestart invoked");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d("lifecycle","onDestroy invoked");
}
}
• Main Activity
Each application always has a main activity which serves as the starting point for the application
“setContentView(R.layout.activity_main);” which will help to load all UI components defined
in activity_main.xml file
• Log.d() method is used to generate log messages.
• super keyword refers to superclass (parent) objects. It is used to call superclass methods,
and to access the superclass constructor.
• savedInstanceState is a reference to a Bundle object that is passed into the onCreate
method of every Android Activity.
• R is an Java-class that is auto-generated from your resources by the build process.
The R. layout member is a auto-generated class that contains all IDs for layouts. R.java is
a class (with inner classes, like layout or string) generated during the build process with
references to your app's resources.
• Andorid Toast can be used to display information for the short period of time. A toast
contains message to be displayed quickly and disappears after sometime.
Toast.makeText(getApplicationContext(), “I am onCreate() Method",
Toast.LENGTH_SHORT).show();
• getApplicationContext() method returns the instance of Context .Context as a state of your
Application. It is used to manipulate resources and services used by the application like
database, local files, class loaders, shared preferences.
• Introduction to Intents
• Intents in android are used as message passing mechanism that works both within your
application and between applications.
• Three of the core components of an application — activities, services, and broadcast
receivers are activated through messages, called intents
• Intent for an Activity:
Every screen in Android application represents an activity. To start a new activity
you need to pass an Intent object to startActivity() method. This Intent object helps to start
a new activity and passing data to the second activity.
• Intent for Services:
Services work in background of an Android application and it does not require any user
Interface. Intents could be used to start a Service that performs one-time task (for example:
Downloading some file) or for starting a Service you need to pass Intent to startService()
method.
• Intent for Broadcast Receivers:
There are various message that an app receives, these messages are called as
Broadcast Receivers. (For example, a broadcast message could be initiated to intimate that
the file downloading is completed and ready to use). Android system initiates some
broadcast message on several events, such as System Reboot, Low Battery warning
message etc.
Intents are really easy to handle and it facilitates communication of components
and activities of your application. Moreover, you can communicate to another application
and send some data to another application using Intents.
E.g., Intents can be used to start an activity to send email.
Types of Intents
1. Implicit Intents
2. Explicit Intents
Explicit Intents are used to connect the application internally. Explicit Intent specifies the
component. And intent provides the external class to be invoked. Explicit Intents are used to
connect the application internally. In Explicit we use the name of component which will be
affected by Intent. For Example: If we know class name then we can navigate the app from
One Activity to another activity using Intent. In the similar way we can start a service to
download a file in background process. Explicit Intent work internally within an application to
perform navigation and data transfer.
Syntax or method of intent calling
Intent i= new Intent (FirstActivity.this, SecondActivity.class);
startActivity(i);
If you want pass some information or data to the new Activity you are calling, you can do this
by calling putExtra() method before the startActivity() method. This method accepts key-value
pair as its parameter.
i.putExtra("key1", "I am value1");
i.putExtra("key2", "I am value2");
startActivity(i);
To receive the data in the new Activity and use it accordingly, you need to call
the getIntent() method and then getStringExtra() method in the java class of the Activity you
want to open through explicit intent. getStringExtra() method takes the key as the parameter.
APPLICATION CONTEXT
• Application Context is It is an instance which is the singleton and can be
accessed in an activity via getApplicationContext(). This context is tied to the
lifecycle of an application. The application context can be used where you need a
context whose lifecycle is separate from the current context or when you are passing a
context beyond the scope of an activity.
➢ Activity Context
• This context is available in an activity. This context is tied to the lifecycle of an activity.
The activity context should be used when you are passing the context in the scope of an
activity or you need the context whose lifecycle is attached to the current context.
➢ getContext() in ContentProvider
• This context is the application context and can be used similar to the application context.
This can be accessed via getContext() method.
•
SCHOOL OF COMPUTING
A typical user interface of an android application consists of action bar and the application
content area.
An activity is consist of views. A view is just a widget that appears on the screen. It could be
button e.t.c. One or more views can be grouped together into one GroupView. Example of
ViewGroup includes layouts.
Types of layout
There are many types of layout. Some of which are listed below −
• Linear Layout
• Absolute Layout
• Table Layout
• Frame Layout
• Relative Layout
Linear Layout
Linear layout is further divided into horizontal and vertical layout. It means it can arrange views
in a single column or in a single row. Here is the code of linear layout(vertical) that includes a
text view.
<?xml version=”1.0” encoding=”utf-8”?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:orientation=”vertical” >
<TextView
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”@string/hello” />
</LinearLayout>
AbsoluteLayout
The AbsoluteLayout enables you to specify the exact location of its children. It can be
declared like this.
<AbsoluteLayout
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
xmlns:android=”http://schemas.android.com/apk/res/android” >
<Button
android:layout_width=”188dp”
android:layout_height=”wrap_content”
android:text=”Button”
android:layout_x=”126px”
android:layout_y=”361px” />
</AbsoluteLayout>
TableLayout
The TableLayout groups views into rows and columns. It can be declared like this.
<TableLayout
xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_height=”fill_parent”
android:layout_width=”fill_parent” >
<TableRow>
<TextView
android:text=”User Name:”
android:width =”120dp”
/>
<EditText
android:id=”@+id/txtUserName”
android:width=”200dp” />
</TableRow>
</TableLayout>
RelativeLayout
The RelativeLayout enables you to specify how child views are positioned relative to each
other.It can be declared like this.
<RelativeLayout
android:id=”@+id/RLayout”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
xmlns:android=”http://schemas.android.com/apk/res/android” >
</RelativeLayout>
FrameLayout
The FrameLayout is a placeholder on screen that you can use to display a single view. It can be
declared like this.
<?xml version=”1.0” encoding=”utf-8”?>
<FrameLayout
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_alignLeft=”@+id/lblComments”
android:layout_below=”@+id/lblComments”
android:layout_centerHorizontal=”true” >
<ImageView
android:src = “@drawable/droid”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content” />
</FrameLayout>
Apart form these attributes, there are other attributes that are common in all views and
ViewGroups. They are listed below −
Sr.No View & description
1
layout_width
Specifies the width of the View or ViewGroup
2
layout_height
Specifies the height of the View or ViewGroup
3
layout_marginTop
Specifies extra space on the top side of the View or ViewGroup
4
layout_marginBottom
Specifies extra space on the bottom side of the View or ViewGroup
5
layout_marginLeft
Specifies extra space on the left side of the View or ViewGroup
6
layout_marginRight
Specifies extra space on the right side of the View or ViewGroup
7
layout_gravity
Specifies how child Views are positioned
8
layout_weight
Specifies how much of the extra space in the layout should be allocated to the View
✓ There are given a lot of android widgets with simplified examples such as Button,
EditText, AutoCompleteTextView, ToggleButton, DatePicker, TimePicker, ProgressBar
etc.
✓ Android widgets are easy to learn. The widely used android widgets with examples are
given below:
Here, we are going to create two textfields and one button for sum of two numbers. If user clicks
button, sum of two input values is displayed on the Toast.We can perform action on button using
different types such as calling listener on button or adding onClick property of button in
activity's xml file
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//code
}
});
<Button
android:onClick="methodName"
/>
First of all, drag 2 textfields from the Text Fields palette and one button from the Form Widgets
palette as shown in the following figure.
File: activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="example.javatpoint.com.sumoftwonumber.MainActivity">
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="61dp"
android:ems="10"
android:inputType="number"
tools:layout_editor_absoluteX="84dp"
tools:layout_editor_absoluteY="53dp" />
<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText1"
android:layout_centerHorizontal="true"
android:layout_marginTop="32dp"
android:ems="10"
android:inputType="number"
tools:layout_editor_absoluteX="84dp"
tools:layout_editor_absoluteY="127dp" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText2"
android:layout_centerHorizontal="true"
android:layout_marginTop="109dp"
android:text="ADD"
tools:layout_editor_absoluteX="148dp"
tools:layout_editor_absoluteY="266dp" />
</RelativeLayout>
Activity class
File: MainActivity.java
package example.javatpoint.com.sumoftwonumber;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private EditText edittext1, edittext2;
private Button buttonSum;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButton();
}
public void addListenerOnButton() {
edittext1 = (EditText) findViewById(R.id.editText1);
edittext2 = (EditText) findViewById(R.id.editText2);
buttonSum = (Button) findViewById(R.id.button);
buttonSum.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String value1=edittext1.getText().toString();
String value2=edittext2.getText().toString();
int a=Integer.parseInt(value1);
int b=Integer.parseInt(value2);
int sum=a+b;
Toast.makeText(getApplicationContext(),String.valueOf(sum), Toast.LENGTH_LON
G).show();
}
});
}
}
Output:
✓ Andorid Toast can be used to display information for the short period of time. A toast
contains message to be displayed quickly and disappears after sometime
✓ The android.widget. Toast class is the subclass of java.lang.Object class.
✓ Toast class is used to show notification for a particular interval of time. After sometime it
disappears. It doesn't block the user interaction.
Constant Description
public static final int LENGTH_LONG displays view for the long duration of time.
public static final int LENGTH_SHORT displays view for the short duration of time.
Method Description
public static Toast makeText(Context context, Makes the toast containing text and
CharSequence text, int duration) duration.
public void setMargin (float horizontalMargin, float Changes the horizontal and vertical
verticalMargin) margin difference.
Toast.makeText(getApplicationContext(),"Hello Javatpoint",Toast.LENGTH_SHORT).show();
Another code:
File: MainActivity.java
package example.javatpoint.com.toast;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Displaying Toast with Hello Javatpoint message
Toast.makeText(getApplicationContext(),"Hello Javatpoint",Toast.LENGTH_SHORT).show();
}
}
Output:
Android ToggleButton
✓ Android Toggle Button can be used to display checked/unchecked (On/Off) state on the
button.
✓ It is beneficial if user have to change the setting between two states. It can be used to
On/Off Sound, Wifi, Bluetooth etc.
✓ Since Android 4.0, there is another type of toggle button called switch that provides slider
control.Android ToggleButton and Switch both are the subclasses of CompoundButton
class.
✓ ToggleButton class provides the facility of creating the toggle button.
✓ XML Attributes of ToggleButton class
Method Description
CharSequence Returns the text when button is not in the checked state.
getTextOff()
CharSequence Returns the text for when button is in the checked state.
getTextOn()
activity_main.xml
Drag two toggle button and one button for the layout. Now the activity_main.xml file will look
like this:
File: activity_main.xml
Android Spinner
✓ Android Spinner is like the combox box of AWT or Swing. It can be used to display the
multiple options to the user in which only one item can be selected by the user.
✓ Android spinner is like the drop down menu with multiple values from which the end
user can select only one value.
✓ Android spinner is associated with AdapterView. So you need to use one of the adapter
classes with spinner.
✓ Android Spinner class is the subclass of AsbSpinner class.
In this example, we are going to display the country list. You need to use ArrayAdapter class to
store the country list.
activity_main.xml
Drag the Spinner from the pallete, now the activity_main.xml file will like this:
File: activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/a
pk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="example.javatpoint.com.spinner.MainActivity">
<Spinner
android:id="@+id/spinner"
android:layout_width="149dp"
android:layout_height="40dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.502"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.498" />
</android.support.constraint.ConstraintLayout>
Activity class
File: MainActivity.java
package example.javatpoint.com.spinner;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements
AdapterView.OnItemSelectedListener {
String[] country = { "India", "USA", "China", "Japan", "Other"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Getting the instance of Spinner and applying OnItemSelectedListener on it
Spinner spin = (Spinner) findViewById(R.id.spinner);
spin.setOnItemSelectedListener(this);
//Creating the ArrayAdapter instance having the country list
ArrayAdapter aa = new ArrayAdapter(this,android.R.layout.simple_spinner_item,country);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//Setting the ArrayAdapter data on the Spinner
spin.setAdapter(aa);
}
//Performing action onItemSelected and onNothing selected
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long id) {
Toast.makeText(getApplicationContext(),country[position] , Toast.LENGTH_LONG).show
();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
Output:
✓ Android Option Menus are the primary menus of android. They can be used for
settings, search, delete item etc.
✓ To inflating the menu by calling the inflate() method of MenuInflater class. To perform
event handling on menu items, you need to override onOptionsItemSelected() method of
Activity class.
File: activity_main.xml
File: menu_main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="example.javatpoint.com.optionmenu.MainActivity">
<item android:id="@+id/item1"
android:title="Item 1"/>
<item android:id="@+id/item2"
android:title="Item 2"/>
<item android:id="@+id/item3"
android:title="Item 3"
app:showAsAction="withText"/>
</menu>
Activity class
This class displays the content of menu.xml file and performs event handling on clicking the
menu items.
File: MainActivity.java
package example.javatpoint.com.optionmenu;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.item1:
Toast.makeText(getApplicationContext(),"Item 1 Selected",Toast.LENGTH_LONG).show();
return true;
case R.id.item2:
Toast.makeText(getApplicationContext(),"Item 2 Selected",Toast.LENGTH_LONG).show();
return true;
case R.id.item3:
Toast.makeText(getApplicationContext(),"Item 3 Selected",Toast.LENGTH_how();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
✓ Android context menu appears when user press long click on the element. It is also
known as floating menu.
✓ It affects the selected content while doing action on it.
✓ It doesn't support item shortcuts and icons.
activity_main.xml
File: activity_main.xml
<ListView
android:layout_width="368dp"
android:layout_height="495dp"
android:id="@+id/listView"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
Figure 4.6 Android Context Menu
Android Intent
✓ Android Intent is the message that is passed between components such as activities,
content providers, broadcast receivers, services etc.
✓ It is generally used with startActivity() method to invoke activity, broadcast receivers etc.
✓ The dictionary meaning of intent is intention or purpose. So, it can be described as the
intention to do action.
✓ The LabeledIntent is the subclass of android.content.Intent class.
1. Implicit Intent
2. Explicit Intent
1) Implicit Intent
Implicit Intent doesn't specifiy the component. In such case, intent provides information of
available components provided by the system that is to be invoked.
For example,
intent.setData(Uri.parse("http://www.javatpoint.com"));
startActivity(intent);
2) Explicit Intent
Explicit Intent specifies the component. In such case, intent provides the external class to be
invoked.
Intent i = new Intent(getApplicationContext(), ActivityTwo.class);
startActivity(i);
1. Starting an Activity
You can use the Intents to start a particular activity by using Intents. For example, if you are
having two activities namely LoginActivity and MainActivity then, you can start
the MainActivity by clicking the login button present on the LoginActivity. By using
the startActivity(), you can start the desired Activity using the Intents.
2. Starting a Service
service as a component that will perform a particular task in the background. So, you can use
Intents to start a service also. For API level 21 or higher, you can use Job Scheduler to start a
service. For API level lower than 21, you can use the Service class to achieve the same.
3. Delivering a broadcast
A broadcast is a message that is received by the application from the system. A very common
example of a broadcast can be Device Charging message. So, you can use a broadcast to send
some kind of message to the applications present in the device. This is done by passing an
Intent to sendBroadcast() or to sendOrderedBroadcast().
Adapter View
✓ An Adapter View can be used to display large sets of data efficiently in form of List
or Grid etc, provided to it by an Adapter.
1. It only renders those View objects which are currently on-screen or are about to some on-
screen. Hence no matter how big your data set is, the Adapter View will always load only
5 or 6 or maybe 7 items at once, depending upon the display size. Hence saving memory.
2. It also reuses the already created layout to populate data items as the user scrolls, hence
saving the CPU usage.
There are the some commonly used Adapter in Android used to fill the data in the UI
components.
1. BaseAdapter In Android:
✓ BaseAdapter is a common base class of a general implementation of an Adapter that can
be used in ListView, GridView, Spinner etc.
✓ Whenever we need a customized list in a ListView or customized grids in
a GridView we create our own adapter and extend base adapter in that.
✓ Base Adapter can be extended to create a custom Adapter for displaying a custom list
item.
ArrayAdapter is also an implementation of BaseAdapter.
@Override
public int getCount() {
return 0;
}
@Override
public Object getItem(int i) {
return null;
}
@Override
public long getItemId(int i) {
return 0;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
return null;
}
ArrayAdapter:
• Whenever you have a list of single type of items which is backed by an array, you can
use ArrayAdapter. For instance, list of phone contacts, countries or names.
• By default, ArrayAdapter expects a Layout with a single TextView, If you want to use
more complex views means more customization in grid items or list items, please avoid
ArrayAdapter and use custom adapters.
In the above code snippet is the implementation of a ArrayAdapter. Below is the description of
all the parameters used for the implementation of a ArrayAdapter to show a list of elements in
a list view or in a spinner.
Parameters used in ArrayAdapter:
Lets discuss parameter in ArrayAdapter class:
• context:
The first parameter is used to pass the context means the reference of current class. Here this is a
keyword used to show the current class reference. We can also use getApplicationContext(),
getActivity() in the place of this keyword. getApplicationContext() is used in a Activity and
getActivity() is used in a Fragment.
Below is the example code in which we set the current class reference in a adapter.
• resource:
The second parameter is resource id used to set the layout(xml file) for list items in which you
have a text view.
The third parameter is textViewResourceId which is used to set the id of TextView where you
want to display the actual text.
Below is the example code in which we set the id(identity) of a text view.
• objects:
• The fourth parameter is an array of objects, used to set the array of elements in
the textView. We can set the object of array or array list here.
• Below is the example code in which we set the Animal array in adapter to display the
Animal name’s list.
Notifications
Android Notification provides short, timely information about the action happened in the
application, even it is not running. The notification displays the icon, title and some amount of
the content text.
The properties of Android notification are set using NotificationCompat.Builder object. Some
of the notification properties are mention below:
Android notification message fills up the void in such situations. Android notification is a
message that we can display to the user outside of our application’s normal UI. Notifications in
android are built using NotificationCompat library.
Creating Android Notification
getSystemService(NOTIFICATION_SERVICE);
✓ Notification build() : Combines all of the options that have been set and returns a new
Notification object
✓ NotificationCompat.Builder setAutoCancel (boolean autoCancel) : Setting this flag
will make it such that the notification is automatically canceled when the user clicks it in
the panel
✓ NotificationCompat.Builder setContent (RemoteViews views) : Supplies a custom
RemoteViews to use instead of the standard one
✓ NotificationCompat.Builder setContentInfo (CharSequence info) : Sets the large text
at the right-hand side of the notification
✓ NotificationCompat.Builder setContentIntent (PendingIntent intent) : Supplies a
PendingIntent to send when the notification is clicked
✓ NotificationCompat.Builder setContentText (CharSequence text) : Sets the text
(second row) of the notification, in a standard notification
✓ NotificationCompat.Builder setContentTitle (CharSequence title) : Sets the text (first
row) of the notification, in a standard notification
✓ NotificationCompat.Builder setDefaults (int defaults) : Sets the default notification
options that will be used. An example is;
✓ mBuilder.setDefaults(Notification.DEFAULT_LIGHTS |
Notification.DEFAULT_SOUND)
✓ NotificationCompat.Builder setLargeIcon (Bitmap icon) : Sets the large icon that is
shown in the ticker and notification
✓ NotificationCompat.Builder setNumber (int number) : Sets the large number at the
right-hand side of the notification
✓ NotificationCompat.Builder setOngoing (boolean ongoing) : Sets whether this is an
ongoing notification
✓ NotificationCompat.Builder setSmallIcon (int icon) : Sets the small icon to use in the
notification layouts
✓ NotificationCompat.Builder setStyle (NotificationCompat.Style style) : Adds a rich
notification style to be applied at build time
✓ NotificationCompat.Builder setTicker (CharSequence tickerText) : Sets the text that
is displayed in the status bar when the notification first arrives
✓ NotificationCompat.Builder setVibrate (long[] pattern) : Sets the vibration pattern to
use
✓ NotificationCompat.Builder setWhen (long when) : Sets the time that the event
occurred. Notifications in the panel are sorted by this time
Once you have Builder object, you can set its Notification properties using Builder object as
per your requirement. But this is mandatory to set at least following −
• A small icon, set by setSmallIcon()
• A title, set by setContentTitle()
• Detail text, set by setContentText()
mBuilder.setSmallIcon(R.drawable.notification_icon);
mBuilder.setContentTitle("Notification Alert, Click Me!");
mBuilder.setContentText("Hi, This is Android Notification Detail!");
You have plenty of optional properties which you can set for your notification. To learn more
about them, see the reference documentation for NotificationCompat.Builder.
This is an optional part and required if you want to attach an action with the notification. An
action allows users to go directly from the notification to an Activity in your application, where
they can look at one or more events or do further work.
The action is defined by a PendingIntent containing an Intent that starts an Activity in your
application. To associate the PendingIntent with a gesture, call the appropriate method
of NotificationCompat.Builder. For example, if you want to start Activity when the user clicks
the notification text in the notification drawer, you add the PendingIntent by
calling setContentIntent().
A PendingIntent object helps you to perform an action on your applications behalf, often at a
later time, without caring of whether or not your application is running.
Intent resultIntent = new Intent(this, ResultActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(ResultActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
Finally, you pass the Notification object to the system by calling NotificationManager.notify()
to send your notification. Make sure you call NotificationCompat.Builder.build() method on
builder object before notifying it. This method combines all of the options that have been set
and return a new Notification object.
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
Defining Styles
A style is defined in an XML resource that is separate from the XML that specifies the layout.
This XML file resides under res/values/ directory of your project and will have <resources> as
the root node which is mandatory for the style file. The name of the XML file is arbitrary, but it
must use the .xml extension.
To define multiple styles per file using <style> tag but each style will have its name that
uniquely identifies the style. Android style attributes are set using <item> tag as shown below −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="CustomFontStyle">
<item name="android:layout_width">fill_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:capitalize">characters</item>
<item name="android:typeface">monospace</item>
<item name="android:textSize">12pt</item>
<item name="android:textColor">#00FF00</item>/>
</style>
</resources>
Using Styles
Once your style is defined, you can use it in your XML Layout file using style attribute as
follows −
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/text_id"
style="@style/CustomFontStyle"
android:text="@string/hello_world" />
</LinearLayout>
Style Inheritance
Android supports style Inheritance in very much similar way as cascading style sheet in web
design. You can use this to inherit properties from an existing style and then define only the
properties that you want to change or add.
To implement a custom theme create or edit MyAndroidApp/res/values/themes.xml and add the
following −
<resources>
...
<style name="MyCustomTheme" parent="android:style/Theme">
<item name="android:textColorPrimary">#ffff0000</item>
</style>
...
</resources>
In your AndroidManifest.xml apply the theme to the activities you want to style −
<activity
android:name="com.myapp.MyActivity"
...
android:theme="@style/MyCustomTheme"
/>
Your color resource can then be applied to some theme attributes, such as the window
background and the primary text color, by adding <item> elements to your custom theme.
These attributes are defined in your styles.xml file. For example, to apply the custom color to
the window background, add the following two <item> elements to your custom theme, defined
in MyAndroidApp/res/values/styles.xml file −
<resources>
...
<style name="MyCustomTheme" ...>
<item name="android:windowBackground">@color/my_custom_color</item>
<item name="android:colorBackgroundCacheHint">@color/my_custom_color</item>
</style>
...
</resources>
A nine-patch drawable is a special kind of image which can be scaled in width and height while
maintaining its visual integrity. Nine-patches are the most common way to specify the
appearance of Android buttons, though any drawable type can be used.
The layout design can implementable based on them based colours, for example as following
design is designed based on them colour(blue)
Figure4.10 Above layout has designed based on style.xml file,Which has placed
at res/values/
<resource>
<style name="AppTheme" parent="android:Theme.Material">
<item name ="android:color/primary">@color/primary</item>
<item name ="android:color/primaryDark">@color/primary_dark</item>
<item name ="android:colorAccent/primary">@color/accent</item>
</style>
<resource>
The Android platform provides a large collection of styles and themes that you can use in your
applications. You can find a reference of all available styles in the R.style class. To use the
styles listed here, replace all underscores in the style name with a period
SCHOOL OF COMPUTING
UNIT V
Database: Understanding of SQLite database, connecting with the database. Threads – Maps –
GPS – MMS – Sensors.
✓ Android SQLite is a very lightweight database which comes with Android OS. Android
SQLite combines a clean SQL interface with a very small memory footprint and decent
speed. For Android, SQLite is “baked into” the Android runtime, so every Android
application can create its own SQLite databases.
✓ Android SQLite native API is not JDBC, as JDBC might be too much overhead for a
memory-limited smartphone.
✓ SQLite is a typical relational database, containing tables (which consists of rows and
columns), indexes etc. We can create our own tables to hold the data accordingly. This
structure is referred to as a schema.
Database - Package
The main package is android. database. SQLite that contains the classes to manage your own
databases.
The Database Structure
✓ The first thing needed is the database structure. We create database structure according to
the system. But here we are not building an application, and it is only an example
demonstrating the use of SQLite Database.
In order to create a database, you just need to call this method openOrCreateDatabase with your
database name and mode as a parameter. It returns an instance of SQLite database which you
have to receive in your own object.Its syntax is given below:
SQLiteDatabase mydatabase = openOrCreateDatabase("your database
name",MODE_PRIVATE,null);
Apart from this, there are other functions available in the database package, that does this job.
They are listed below
Sr.No Method & Description
Database - Insertion
To create table or insert data into table using execSQL method defined in SQLiteDatabase class.
Its syntax is given below
mydatabase.execSQL("CREATE TABLE IF NOT EXISTS TutorialsPoint(Username
VARCHAR,Password VARCHAR);");
mydatabase.execSQL("INSERT INTO TutorialsPoint VALUES('admin','admin');");
This will insert some values into our table in our database. Another method that also does the
same job but take some additional parameter is given below
Database - Fetching
We can retrieve anything from database using an object of the Cursor class. We will call a
method of this class called rawQuery and it will return a resultset with the cursor pointing to the
table. We can move the cursor forward and retrieve the data.
Cursor resultSet = mydatbase.rawQuery("Select * from TutorialsPoint",null);
resultSet.moveToFirst();
String username = resultSet.getString(0);
String password = resultSet.getString(1);
There are other functions available in the Cursor class that allows us to effectively retrieve the
data. That includes
1 getColumnCount()
This method return the total number of columns of the table.
2 getColumnIndex(String columnName)
This method returns the index number of a column by specifying the name of the column
3 getColumnName(int columnIndex)
This method returns the name of the column by specifying the index of the column
4 getColumnNames()
This method returns the array of all the column names of the table.
5 getCount()
This method returns the total number of rows in the cursor
6 getPosition()
This method returns the current position of the cursor in the table
7 isClosed()
This method returns true if the cursor is closed and return false otherwise
For managing all the operations related to the database , an helper class has been given and is
called SQLiteOpenHelper. It automatically manages the creation and update of the database. Its
syntax is given below
Example
Here is an example demonstrating the use of SQLite Database. It creates a basic contacts
applications that allows insertion, deletion and modification of contacts.
To experiment with this example, you need to run this on an actual device on which camera is
supported.
Steps Description
1 You will use Android studio to create an Android application under a package
com.example.sairamkrishna.myapplication.
2 Modify src/MainActivity.java file to get references of all the XML components and populate
the contacts on listView.
4 Create a new Activity as DisplayContact.java that will display the contact on the screen
10 Run the application and choose a running android device and install the application on it and
verify the results.
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
obj = (ListView)findViewById(R.id.listView1);
obj.setAdapter(arrayAdapter);
obj.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
// TODO Auto-generated method stub
int id_To_Search = arg2 + 1;
intent.putExtras(dataBundle);
startActivity(intent);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item){
super.onOptionsItemSelected(item);
switch(item.getItemId()) {
case R.id.item1:Bundle dataBundle = new Bundle();
dataBundle.putInt("id", 0);
Intent intent = new Intent(getApplicationContext(),DisplayContact.class);
intent.putExtras(dataBundle);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
TextView name ;
TextView phone;
TextView email;
TextView street;
TextView place;
int id_To_Update = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_contact);
name = (TextView) findViewById(R.id.editTextName);
phone = (TextView) findViewById(R.id.editTextPhone);
email = (TextView) findViewById(R.id.editTextStreet);
street = (TextView) findViewById(R.id.editTextEmail);
place = (TextView) findViewById(R.id.editTextCity);
if(Value>0){
//means this is the view part not the add contact part.
Cursor rs = mydb.getData(Value);
id_To_Update = Value;
rs.moveToFirst();
String nam =
rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_NAME));
String phon =
rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_PHONE));
String emai =
rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_EMAIL));
String stree =
rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_STREET));
String plac =
rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_CITY));
if (!rs.isClosed()) {
rs.close();
}
Button b = (Button)findViewById(R.id.button1);
b.setVisibility(View.INVISIBLE);
name.setText((CharSequence)nam);
name.setFocusable(false);
name.setClickable(false);
phone.setText((CharSequence)phon);
phone.setFocusable(false);
phone.setClickable(false);
email.setText((CharSequence)emai);
email.setFocusable(false);
email.setClickable(false);
street.setText((CharSequence)stree);
street.setFocusable(false);
street.setClickable(false);
place.setText((CharSequence)plac);
place.setFocusable(false);
place.setClickable(false);
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
Bundle extras = getIntent().getExtras();
if(extras !=null) {
int Value = extras.getInt("id");
if(Value>0){
getMenuInflater().inflate(R.menu.display_contact, menu);
} else{
getMenuInflater().inflate(R.menu.menu_main menu);
}
}
return true;
}
phone.setEnabled(true);
phone.setFocusableInTouchMode(true);
phone.setClickable(true);
email.setEnabled(true);
email.setFocusableInTouchMode(true);
email.setClickable(true);
street.setEnabled(true);
street.setFocusableInTouchMode(true);
street.setClickable(true);
place.setEnabled(true);
place.setFocusableInTouchMode(true);
place.setClickable(true);
return true;
case R.id.Delete_Contact:
AlertDialog d = builder.create();
d.setTitle("Are you sure");
d.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase;
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table contacts " +
"(id integer primary key, name text,phone text,email text, street text,place text)"
);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
public boolean insertContact (String name, String phone, String email, String street,String
place) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("phone", phone);
contentValues.put("email", email);
contentValues.put("street", street);
contentValues.put("place", place);
db.insert("contacts", null, contentValues);
return true;
}
public boolean updateContact (Integer id, String name, String phone, String email, String
street,String place) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("phone", phone);
contentValues.put("email", email);
contentValues.put("street", street);
contentValues.put("place", place);
db.update("contacts", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
return true;
}
while(res.isAfterLast() == false){
array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_NAME)));
res.moveToNext();
}
return array_list;
}
}
Following is the content of the res/layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp"
android:text="Data Base" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials Point"
android:id="@+id/textView2"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:textSize="35dp"
android:textColor="#ff16ff01" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true"
android:src="@drawable/logo"/>
<ScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/scrollView"
android:layout_below="@+id/imageView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true">
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" >
</ListView>
</ScrollView>
</RelativeLayout>
Following is the content of the res/layout/activity_display_contact.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context=".DisplayContact" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="370dp"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin">
<EditText
android:id="@+id/editTextName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginTop="5dp"
android:layout_marginLeft="82dp"
android:ems="10"
android:inputType="text" >
</EditText>
<EditText
android:id="@+id/editTextEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editTextStreet"
android:layout_below="@+id/editTextStreet"
android:layout_marginTop="22dp"
android:ems="10"
android:inputType="textEmailAddress" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/editTextName"
android:layout_alignParentLeft="true"
android:text="@string/name"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editTextCity"
android:layout_alignParentBottom="true"
android:layout_marginBottom="28dp"
android:onClick="run"
android:text="@string/save" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/editTextEmail"
android:layout_alignLeft="@+id/textView1"
android:text="@string/email"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/editTextPhone"
android:layout_alignLeft="@+id/textView1"
android:text="@string/phone"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/editTextEmail"
android:layout_alignLeft="@+id/textView5"
android:text="@string/street"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="@+id/editTextCity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/editTextName"
android:layout_below="@+id/editTextEmail"
android:layout_marginTop="30dp"
android:ems="10"
android:inputType="text" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/editTextCity"
android:layout_alignBottom="@+id/editTextCity"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="@+id/editTextEmail"
android:text="@string/country"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="@+id/editTextStreet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editTextName"
android:layout_below="@+id/editTextPhone"
android:ems="10"
android:inputType="text" >
<requestFocus />
</EditText>
<EditText
android:id="@+id/editTextPhone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editTextStreet"
android:layout_below="@+id/editTextName"
android:ems="10"
android:inputType="phone|text" />
</RelativeLayout>
</ScrollView>
Following is the content of the res/value/string.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Address Book</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="Add_New">Add New</string>
<string name="edit">Edit Contact</string>
<string name="delete">Delete Contact</string>
<string name="title_activity_display_contact">DisplayContact</string>
<string name="name">Name</string>
<string name="phone">Phone</string>
<string name="email">Email</string>
<string name="street">Street</string>
<string name="country">City/State/Zip</string>
<string name="save">Save Contact</string>
<string name="deleteContact">Are you sure, you want to delete it.</string>
<string name="yes">Yes</string>
<string name="no">No</string>
</resources>
Following is the content of the res/menu/main_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@+id/item1"
android:icon="@drawable/add"
android:title="@string/Add_New" >
</item>
</menu>
Following is the content of the res/menu/display_contact.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/Edit_Contact"
android:orderInCategory="100"
android:title="@string/edit"/>
<item
android:id="@+id/Delete_Contact"
android:orderInCategory="100"
android:title="@string/delete"/>
</menu>
This is the defualt AndroidManifest.xml of this project
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".DisplayContact"/>
</application>
</manifest>
Threads
✓ Threads are the cornerstone of any multitasking operating system and can be thought of
as 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. Any additional
components that are started within the application will, by default, also run on the main
thread.
✓ Any component within an application that performs a time consuming task using the
main thread will cause the entire application to appear to lock up until the task is
completed. This will typically result in the operating system displaying an “Application is
unresponsive” warning to the user. Clearly, this is far from the desired behavior for any
application. In such a situation, this can be avoided simply by launching the task to be
performed in a separate thread, allowing the main thread to continue unhindered with
other tasks
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.
A. AsyncTask
B. 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.
A. Service
B. Intent Service
For the above two threading components, There are five types of thread are using in Android
C. Main thread
D. UI thread
E. Worker thread
F. Any thread
G. Binder thread
1. Main Thread
Figure 5.2 Example of Main Thread
✓ When an application is launched in Android, it creates the first thread of execution, known
as the “main” thread. The main thread is responsible for dispatching events to the
appropriate user interface widgets as well as communicating with components from the
Android UI toolkit.
✓ To keep your application responsive, it is essential to avoid using the main thread to
✓ Network operations and database calls, as well as loading of certain components, are
common examples of operations that one should avoid in the main thread.
✓ When they are called in the main thread, they are called synchronously, which means that
✓ For this reason, they are usually performed in separate threads, which thereby avoids
blocking the UI while they are being performed (i.e., they have performed asynchronously
✓ The UIThread is the main thread of execution for your application. This is where most of
your application code is run. All of your application components (Activities, Services,
ContentProviders, BroadcastReceivers) are created in this thread, and any system calls to
✓ For instance, application is a single Activity class. Then all of the lifecycle methods and
most of your event handling code is run in this UIThread. These are methods
✓ Additionally, this is where all of the updates to the UI are made. Anything that causes the
UI to be updated or changed HAS to happen on the UI thread. When you explicitly spawn
a new thread to do work in the background, this code is not run on the UIThread.
✓ So what happens if this background thread needs to do something that changes the UI?
✓ Actually you're supposed to use a Handler. It provides these background threads the
✓ They do this by putting the UI-modifying code in a Runnable object and passing it to the
runOnUiThread method.
3. Worker Thread:
Worker threads are background threads. They are the threads that are created separately, other
than the UI thread. Since blocking the UI thread is restricted according to the rule, the user should
Bitmap b = loadImageFromNetwork(“http://example.com/image.png");
mImageView.setImageBitmap(b);}
}).start(); }
✓ In the above example code, the download operation is handled by a second thread other
than the UI thread. But the program violates the second rule.
✓ The imageView from UI thread is manipulating from this worker thread.According to the
second rule, UI could not be accessed from outside the UI thread. The solution for such a
✓ The action will execute immediately if the current thread is in the UI itself. Else the action
3. Any Thread:
@Target([AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER,
AnnotationTarget.PROPERTY_SETTER, AnnotationTarget.CONSTRUCTOR,
AnnotationTarget.CLASS, AnnotationTarget.FILE, AnnotationTarget.VALUE_PARAMETER])
class AnyThread
✓ Denotes that the annotated method can be called from any thread (e.g. it is “thread-safe”.)
If the annotated element is a class, then all methods in the class can be called from any
thread.
✓ The main purpose of this method is to indicate that you believe a method can be called
from any thread; static tools can then check that nothing you call from within this method
5. Binder thread:
✓ Let’s consider an example. Imagine that you have service Process B (see picture).
And you have several applications that communicate with this service B (one of
applications. Thus, you need to run several replicas of Service B for different
applications. Android runs these replicas in different threads of Process B and
There are four different types of Google maps, as well as an optional to no map at all. Each of
them gives different view on map. These maps are as follow:
1. Normal: This type of map displays typical road map, natural features like river and some
features build by humans.
2. Hybrid: This type of map displays satellite photograph data with typical road maps. It
also displays road and feature labels.
3. Satellite: Satellite type displays satellite photograph data, but doesn't display road and
feature labels.
4. Terrain: This type displays photographic data. This includes colors, contour lines and
labels and perspective shading.
5. None: This type displays an empty grid with no tiles loaded.
Google map API provides several methods that help to customize Google map. These methods
are as following:
Methods Description
Copy the URL from google_map_api.xml file to generate Google map key.
Paste the copied URL at the browser. It will open the following page.
activity_maps.xml
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="example.com.mapexample.MapsActivity" />
MapsActivity.java
To get the GoogleMap object in our MapsActivity.java class we need to implement the
OnMapReadyCallback interface and override the onMapReady() callback method.
package example.com.mapexample;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements OnMapReadyCall
back{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
<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" />
AndroidManifest.xml
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the 'MyLocation' functionality.
-->
<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" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<meta-data
android:name="com.google.android.geo.API
_KEY"
android:value="@string/google_maps_key"
/>
<activity
android:name=".MapsActivity"
android:label="@string/title_activity_maps">
<intent-filter>
<action android:name="android.intent.ac
tion.MAIN" />
<category android:name="android.inte
nt.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Short Message Service is one of the killer applications which are one of the most
prominent communication tools. Even a kid knows how to use SMS application. Android comes
with a built-in SMS application that enables us to send and receive SMS messages. However, it
is possible that we would want to integrate SMS application. SMS technology can be used to
send/receive text messages or data messages. Android supports full SMS functionality within our
applications through the SmsManager class. We can use this SMS Manager to replace the native
SMS application to send text messages, respond to incoming texts, or use SMS as a data
transport layer.
Multimedia messaging service (MMS) messages allow users to send and receive messages which
includes multimedia attachments such as videos, photos and audio.
SMSManager manages SMS operations such as sending data, text, and SMS messages. This
object is get by calling the static method getDefault(). The default SMS app is the one which is
selected b the user in system settings. The default SMS app is able to write to the SMS Provider.
SMSProvider are the tables defined within the Telephony class. Only the default SMS app
receives the SMS_DELIVER_ACTION broadcast when the user receives an SMS or
the WAP_PUSH_DELIVER_ACTION broadcast when the user receives an MMS.
Application which wants to behave as the user's default SMS app must be able to handle the
following intents:
Example :
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
<EditText
android:id="@+id/txtPhoneNo"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Message" />
<EditText
android:id="@+id/txtMessage"
android:layout_width="fill_parent"
android:layout_height="150px"
android:gravity="top" />
<Button
android:id="@+id/btnSendSMS"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
</LinearLayout>
We can send sms in android via intent. You need to write only 4 lines of code the send
sms in android.
//Get the SmsManager instance and call the sendTextMessage method to send mess
age
SmsManager sms=SmsManager.getDefault();
sms.sendTextMessage("mobile num", null, "Mobile application", pi,null);
Android Sensor
Sensors can be used to monitor the three-dimensional device movement or change in the
environment of the device.
Types of Sensors
1) Motion Sensors
These are used to measure acceleration forces and rotational forces along with three axes.
2) Position Sensors
These are used to measure the environmental changes such as temperature, humidity etc.
1) SensorManager class
You can get the instance of SensorManager by calling the method getSystemService() and
passing the SENSOR_SERVICE constant in it.
1. SensorManager sm = (SensorManager)getSystemService(SENSOR_SERVICE);
2) Sensor class
The android.hardware.Sensor class provides methods to get information of the sensor such as
sensor name, sensor type, sensor resolution, sensor type etc.
3) SensorEvent class
Its instance is created by the system. It provides information about the sensor.
4) SensorEventListener interface
It provides two call back methods to get information when sensor values (x,y and z) change
or sensor accuracy changes.
1. A sensor example that prints x, y and z axis values. Here, we are going to see
that.
2. A sensor example that changes the background color when device is shuffled.
activity_main.xml
File: activity_main.xml
<RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android
"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="92dp"
android:layout_marginTop="114dp"
android:text="TextView" />
</RelativeLayout>
Activity class
Let's write the code that prints values of x axis, y axis and z axis.
File: MainActivity.java
package com.example.sensorsimple;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
import android.hardware.SensorManager;
import android.hardware.SensorEventListener;
import android.hardware.SensorEvent;
import android.hardware.Sensor;
import java.util.List;
public class MainActivity extends Activity {
SensorManager sm = null;
TextView textView1 = null;
List list;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView1 = (TextView)findViewById(R.id.textView1);
list = sm.getSensorList(Sensor.TYPE_ACCELEROMETER);
if(list.size()>0){
sm.registerListener(sel, (Sensor) list.get(0), SensorManager.SENSOR_DELA
Y_NORMAL);
}else{
Toast.makeText(getBaseContext(), "Error: No Accelerometer.", Toast.LENG
TH_LONG).show();
}
}
@Override
protected void onStop() {
if(list.size()>0){
sm.unregisterListener(sel);
}
super.onStop();
}
}