Friday, May 1, 2015

How to check Network Connection in Android

code snippet to check Network connection in Android :

private boolean haveNetworkConnection() {
    boolean haveConnectedWifi = false;
    boolean haveConnectedMobile = false;

    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo[] netInfo = cm.getAllNetworkInfo();
    for (NetworkInfo ni : netInfo) {
        if (ni.getTypeName().equalsIgnoreCase("WIFI"))
            if (ni.isConnected())
                haveConnectedWifi = true;
        if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
            if (ni.isConnected())
                haveConnectedMobile = true;
    }
    return haveConnectedWifi || haveConnectedMobile;
}

Android Annotation Setup in Android Studio


Android Annotations is an Open Source framework that speeds up Android development. It takes care of the plumbing, and lets you concentrate on what's really important. By simplifying your code, it facilitates its maintenance.

Not much about this step-by-step guide has changed but since there were developer having problems getting everything to work I decided to post an updated version. This is what I did in order to get things running with a new project created in Android Studio (version 1.1.0).

The file we are going to modify is the build.gradle file located in the app folder of your project, not the one found in the root.
Step 1
First we need to apply the android-apt plugin and add a dependency to it. Be sure to add this below the line that applies the android plugin. Note that the order here is important!


Step 2
Now hand it the following arguments. Remember to replace com.example.package.name with the correct package name for your project.



Step 3
Finally add dependencies to AndroidAnnotations.


The contents of app/build.gradle should now look something like this.


Step 4
Now rebuild your project and it should run fine! Now you are all set to start using AndroidAnnotations. And when you do, don’t forget to add that underscore to your Activities in the manifest!


Monday, November 1, 2010

Data Communication and Computer Network

Data Communications and Computer Networks
Data communications has an ancient history, as people have always had an interest in
communicating with each other. Different methods have been used and associated with each
method are various advantages and disadvantages. A major problem with communications is
ensuring that the receiver gets the message sent by the transmitter.
In every form of communication there are common elements:
1. transmitter (sender, source)
2. receiver (destination)
3. message to be communicated
4. medium (how message is carried)

Examples of medium:
Medium                                                            Problem (Noise)

Smoke signals                                                    Fog, Darkness
Tomtom drum                                                    Thunder
Pony express                                                     Bandits
Carrier pigeon                                                    Hunter
Post                                                                   Strike, Loss
Telegraph                                                           Broken wires
Telephone                                                         Electrical
Computer Cable                                                Electrical
Anything that interferes with the message is technically called Noise.
Convergence of Computing and Communications:
Communication facilities have an ancient history, but we tend to think of the advent of the
telegraph and later the telephone as the beginning of modern communications. Extensive
telegraph and telephone networks were established all over the world, decades before the
emergence of computers.
The first public telephone exchange was opened in the U.S. in 1878 and operators were used to
connect subscribers. Strowger invented the automatic exchange (switch) in 1891 and this system
remained in use until the 1960s when crossbar switches were introduced. The connection
between two exchanges is called a trunk and trunk switches in each exchange route calls. The
connection between a subscriber and the local exchange is called the local loop. In the 1970’s
computer controlled switches were introduced and digital switching began. Here, voice signals
are converted to digital signals.
In the telegraph network text was transmitted using codes, beginning with Morse, and then
Baudot codes. These were predecessors of the modern ASCII code, which is frequently used in
computers to represent text.
The concept of a start-stop code system was developed to tell a receiver that a character was
being transmitted. Seven pulses were transmitted on the line. Five were used to represent the
character. A start pulse indicated that a character was to be transmitted and a stop pulse that the
character was finished.
This idea is the basis of the RS232 serial interface. The serial interface is the communications
interface used between computers and devices such as modems, printers and computer terminals.
RS232 is the name of the standard that defines the interface (e.g. how many wires are used, what
each wire is used for and so on).
This type of transmission is asynchronous. Characters are transmitted independently of each
other as opposed to synchronous transmission where blocks of characters are transmitted and
precise timing is critical.
Computer Networks
Definition
A computer network is an interconnected collection of autonomous computers.
The goals of a computer network include:
• Resource sharing: programs (O.S., applications), data, equipment (printers, disks) are
available to all users of the network regardless of location.
• High reliability: By replicating files on different machines and having spare cpus, users
are more immune from hardware/software failure.
• Less cost: Small machines have about 1/10 the power of a mainframe but 1/1000 the
cost. By using such machines with file server machine(s), a local area network LAN can
be cheaply installed. It is easy to increase the capacity by adding new machines.
• Communications medium: Users have access to email and the Internet
Comp 1001 – Networks 3
Wide Area Networks (WANs)
When the computers in a networks are separated by long distances (from a few Kms to global
distances) the network is called a WAN.
LANs can carry data at varying speeds depending on the communications medium used. If they
are based on the telephone network this speed may range from 56 Kbps to less than 10 Mbps.
However, if they are based on optical fibre, much higher speeds are possible.
WANs are widely used in banking. The financial markets are also heavily dependent on wide
area computer networks.
They provide for remote database access, which is the basis for airline reservations and home
banking. They also provide electronic mail or e-mail.
Local Area Networks (LANs)
When the computers in a network are located close together (usually less than 1or 2 Kms), the
network is called a LAN.
LANs are used in many offices, schools, colleges and hospitals. They are suitable for networking
within a building or campus area. Because of the short distances involved they are typically
(though not necessarily) faster than WANs in that it is cheap to use high quality communications
media such as coaxial cable and optical fibre. They can carry data at very high speeds e.g. from
10 Mbps to 100 Mbps being very common speeds, while speeds of up to 1000 Mbps are
possible.
Client-Server Model of Computer Systems
Networks often provide services on one or more machines for all users of the network. The
machines providing the service are called servers. The machines (users) using the service are
called clients. Several servers may be used so that if one crashes, users can still access their data
and the network services. This is a decentralised computing system whereby users can avail of
local processing on their own machines as well as the shared services of the network.
A good example is a LAN with a file server. The users store files access software on the file
server, but use their own PCs for processing. Dedicated servers may also be used for email or for
printing: mail servers and print servers.
Mainframe-Terminal Model of Computer Systems
This is the traditional centralised computing system, whereby a single central mainframe
provides all the processing for users who are connected to it via computer terminals. A computer
terminal is simply a screen and keyboard although a PC may be used to act as a terminal via
terminal emulation software.
Comp 1001 – Networks 4
The terminals may be local (on same site) or remote and connected via a modem. Response
time varies according to the number of users logged on and so is not readily predictable. A major
disadvantage is that all processing terminates in the event of a mainframe crash.
Network Configuration.
The user machines in a network are called hosts. The hosts are connected by a subnet which
carries messages between hosts. The subnet is made up of transmission lines (trunks, channels,
circuits) and switching elements (computers). Transmission lines carry bits and the switching
elements connect the transmission lines.
The shape of a computer network can vary conceptually from a single straight line, usually
referred to as a bus, to a many sided polygon with each node connected to all the others.
There are two types of subnet design:
1. Broadcast subnets: In this system a message is broadcast over the network and all
machines have the possibility of receiving the message. LANs usually use broadcast
subnets. Each machine has its own unique address and typically will only "listen" to
messages that are sent to this address.
2. Point to Point subnets: Here, a message is transmitted from one computer to another
computer and so until the destination computer is reached. This is analogous to the postal
system where a letter is transferred from post-office to post-office. WANs usually use
point to point subnets
Broadcast Sub-networks
These are typically configured as either a bus or a ring network. They can be further classified
as Static or Dynamic.
In a static broadcast subnet each computer gets a chance to transmit and can only broadcast a
message when it's turn comes around. This is a rather inefficient use of network time, since if the
computer, whose turn it is to transmit, has nothing to transmit, then the network is left idle. It has
the advantage that two stations can never transmit a message simultaneously. A simultaneous
transmission of messages causes a collision where the messages get corrupted and so are not
received. They must be re-transmitted.
A dynamic broadcast subnet makes more efficient use of the network. This system allows any
station to transmit at any time the network is free of traffic. In this case, when a computer wishes
to transmit, it follows the following protocol:

1. Listen to see if the network is free (Carrier Sense)
2. If the network is free, transmit the message otherwise wait for a small amount of time and
repeat from step 1.
3. Check to see if the message is still on the network (Collision Detect). Two machines
could have carried out step 1 at same time, found the network free and proceeded to
transmit their messages, thus causing a collision. If a collision is detected then wait for a
random but small amount of time and repeat from step 1.
In the event of a collision, both computers will wait for random time periods so that it is unlikely
that they will cause another collision. The likelihood of collisions is directly related to the
number of active users on the network i.e. the network traffic.
The above protocol is referred to as CSMA/CD, which stands for Carrier Sense Multiple
Access/Collision Detect. Multiple Access means that many users can access the network at any
time.
Point to Point Networks
The second type of subnet, the point to point subnet, is mainly found in Wide Area Networks
(WANs).
If possible, the point to point subnet transmits directly to the relevant station. If no direct route is
available, it will send the message to a "switch" which re-transmits the message to the
destination. The best known example of this type of network is the telephone network (Public
Switched Telephone Network or PSTN. also referred to as the Plain Old Telephone System or
POTS)
Network Topologies.
Computer networks can be configured in a number of ways as shown below. The ring and bus
topology are used in broadcast subnets. Messages are broken into smaller units called packets
for transmission on a network.
With the ring configuration each packet of information is sent off around the ring on its own.
The same applies to a bus. The packets travel out to the ends of the line where they will
encounter a device called a terminator. It serves the network as a refuse collector, intercepting
and absorbing any signal that reaches the end of the bus and prevents it from being reflected
back.
The complete network, which is a point to point subnet, differs from the others. In this
configuration each station is connected directly to every other station on the network. Its biggest
advantage is speed, however it is not very practical because of the number of connections that
would be required.

The loop is the next configuration design for a point to point network. Each packet is transmitted
along the line until it encounters a computer. The computer at this point in the network then
holds the packet, and any other that is transmitted, until it has accumulated the entire message.
Only when the intercepting computer has collected and reassembled the entire message is that
message forwarded on to the next computer. This process is continued station by computer until
the entire message reaches its final destination. This is called store and forward.
The principles for the tree, intersecting loop and star configurations are the same as those
discussed in the loop. The telephone network is based on the tree topology. A terminalmainframe
model has a star topology.
Network Topology
a) Ring b) Bus
c) Complete d) Loop
e) Tree f) Intersecting Loop
g) Star
Data Transmission
There is a maximum limit to the amount of data that can be transmitted using any transmission
medium (Shannon’s Law). Each medium has its own maximum.
Data is transmitted as signals. The number of signals per second is the frequency of the signal.
This is measured in Hertz (Hz). One cycle per second is 1 Hz. One million cycles per second is
1 MHz.
Bandwidth
The maximum range of frequencies that can be transmitted is the bandwidth of the medium.
This determines the maximum amount of data that can be transmitted. A coaxial cable might
have a bandwidth of 10 to 100 MHz. An optic fibre has a bandwidth of up to 108 MHz.
The higher the bandwidth the more data that can be transmitted per second, hence the popularity
of optic fibres. In fact, computers cannot yet utilise the full capacity of optic fibres i.e. they
cannot transmit at the speed which the fibre is capable of carrying.
Transmission Media
• Copper Wires
o Twisted Pair (tp)
o Coaxial Cable (coax)
• Fibre Optic
• Wireless
o Microwave
o Infrared
o Radio
Twisted Pairs (tp)
They are used by telephones for the local loop (connection between your home phone and the
local telephone exchange). They carry electrical signals. A tp consists of two insulated copper
wires (1mm diameter) twisted to reduce electrical interference.
Capacity: dependent on the distances involved but can be up to several Mbps over a few Kms.
For example ISDN (Integrated Services Digital Network) lines offer speeds from 64Kbps to over
1 Mbps and have been available to home users for Internet access, for several years. More
recently (2003), DSL (Digital Subscriber Line) and in particular ADSL (Asymmetric DSL) lines
are available to home users with speeds of 1.5 to 6 Mbps. ISDN and ADSL both use digital
Comp 1001 – Networks 9
transmission and so must use a digital line unlike the standard analog telephone line where a
modem is used. You must install an ISDN card or an ADSL card into your PC to use an ISDN or
ADSL line.
TPs may be shielded (stp) or unshielded (utp) with the shielded having extra insulation.
However, it is the rate of twisting (number of twists per inch) that is the most important
characteristic. They are also classified into Category-5 (CAT-5) and Category-6 (CAT-6).
CAT-5 can carry 10 or 100 Mbps (10/100Mbps) over short distances e.g. up to 100 metres
approx. The communications standard used in this case is called 10/100-Base-T.
This is the type of cable that is often used in building to connect PCs to a LAN. Usually, the
CAT-5 cable connects to a device know as a hub which is less than 100 metres from each PC.
There may be a hub for each floor/laboratory in a building.
CAT-6 cable operates at 100/1000Mbps (Gigabit Ethernet) and is typically used to interconnect
hubs. It is more expensive than CAT-5 cable.
Large organisations frequently have a so-called "backbone" network that interconnects separate
LANs in different buildings/rooms as in the diagram below. Over short distances CAT-6 cable
may be used but optic fibre is also often used as it can cover longer distances.
Three floor Building with CAT-6 Cable Backbone connecting LANs on each floor
Hub
Hub
CAT-6
Backbone
UPS
Duct to carry Servers
cable
Hub
PCs to hub
via CAT-5
PCs
First Floor
Third Floor
The UPS is an Uninterruptible Power Supply that usually consists of some form of battery
backup power system. This will keep the system powered on, in the event of a mains electricity
failure. Depending on the UPS, it may be able to provide power for periods of several minutes to
several hours and at least long enough for the system to be shut down in a controlled fashion so
that files get saved and so on.
Coaxial (Coax) Cable
Carry electrical signals. It consists of a copper core surrounded by 3 outer layers of insulation. It
has a high bandwidth and good noise immunity.
The original Ethernet standard was based on 10 Mbps coaxial cable. Ethernet is the most
popular LAN standard and was developed at Rank Xerox (who also developed the mouse, laser
printer and Graphical User Interface (GUI) software. Ethernet LANs can be based on tp, coax or
optic fibre.
There are two forms of coax:
Thick Coaxial: operates over distances of up to 500m based on 10-Base-5 standard.
Thin Coaxial: operates over distances of up to 200m based on 10-Base-3 standard.
Capacity
10 to 100 Mbps for distances of up to 1 km. Frequently used in LANs but is being replaced by
utp/stp in most LANs.
Optic Fibre
Uses light to carry data and has a huge bandwidth. Very thin glass fibres used. To date capacity
of 1000 Mbps over 1 km is feasible.
It is used in WANs, LANs for interconnecting hubs and also for linking telephone exchanges.
Excellent noise immunity as it does not suffer from electrical interference and is therefore
suitable for harsh environments such as factory floor.
Wireless
Line of Sight: Infrared and Microwave
Physical cables have a major problem if you have to cross private or public property where it
may be difficult or very expensive to get permission, in addition to the costs of laying the cable.
Using line of sight transmitters avoids this problem.
Microwaves can be used over long distances e.g. A 100m tower can transmit data for distances
over 100 km. Cheaper than digging a trench. Relatively high speeds of 10 Mbps upwards are
possible.
Satellite: operate in same fashion as microwaves where the satellite operates as a ‘Big
microwave repeater in the sky’!! Satellite communication has a high bandwidth giving up 50
Mbps speeds and a given satellite may be able to have many "channels" at this speed.
Wireless
Radio LANs or wireless (wi-fi) LANs are becoming common in offices, universities, hotels,
restaurants and airports. A wireless LAN enables users to connect to the Internet from a laptop
computer with a wireless network card. In UCD, Commerce students use such laptops with
wireless cards to connect to the college network, for course work and email.
LANs and WANs continued
As noted above it, LANs in the same building (or different buildings) may be connected by hubs.
It is also possible to connect LANs together using either repeaters or bridges. When two LANs
are connected using a repeater, all the traffic on one LAN is simply copied to the second LAN
even though it may not addressed to a machine on the second LAN. So, I the figure below, all
traffic on LAN A in Building 1 is repeated on LAN B. This can lead to increased message
collision frequency.
A bridge on the other hand only passes traffic from one LAN to another LAN if the traffic is
addressed to a machine on the second LAN. This leads to more efficient usage of the network.
So, traffic from LAN B below will only be routed to LAN C via the bridge, if that traffic is
destined for a machine on LAN C.
Another possible configuration is to connect LANs in different buildings to a site-wide or
backbone LAN using bridges. This enables communication between all buildings. The bridges
ensure that only traffic addressed to a LAN in a given building will enter that building. This
means that the LANs in each building will not be swamped with network traffic that is intended
for other buildings. The site wide backbone would typically be a fibre optic connection.
LAN A
R
LAN B
LAN C
B
B
Site-wide
Backbone
LAN X
R
B LAN Y
Stations ( Mainframes or PCs or servers)
B Bridge R Repeater
Building 1
Building 4
Wide Area Networks
The type of data communications facility used is a function of the nature of the application, the
number of computers involved and the distance between them. Two computers in the same
room can be simply linked with a point-to-point wire link:
Computer A Computer B
Interface
If the computers are different locations (cities, countries) then public carrier facilities
may be used. One common technique is to use the public switched telephone network
(PSTN) and a modem which enables you connect computers to the PSTN:
Computer A Computer B
Modem Modem
PSTN
The model above is the typical method that a home user employs to connect to the Internet,
where Computer A represents the user's computer and Computer B represents the Internet server
of the user's ISP (Internet Service Provider e.g. Eircom in Ireland). The ISP server would have a
high-speed connection to the Internet which is shared among the users.
In the case of a number of computers to be connected which are separated by long distances then
two possibilities for networking present themselves: the use of private data networks and the
use of public data networks. Both e public and private networks are connected to the Internet.
The earliest computer networks made use of the PSTN (telephone network) for data transmission
between user equipment located at different locations as shown in an earlier diagram. The data
rates using the PSTN are typically less than 56,000 bps and the cost is based on connection time.
Together these factors make the PSTN unattractive for large-scale data communications and led
large organisations to develop private data networks.
Private data networks were set up using leased lines from the telephone authorities to connect a
connect a number of switching nodes or multiplexers. ISDN lines allows speeds from 64 kbps to
several Mbps. Since it very expensive to set up such networks, they are used by very large
organisations such as banks. They are known as private enterprise-wide networks. Such
organisations would install their own switching system which can handle both voice and data
communications.
A device known as a PBX (Private Branch Exchange) or a PABX (Private Automatic Branch
Exchange) may be used to connect telephones, terminals and computers in a building or a
campus. The exchange routes internal calls directly and is connected to the PSTN for external
calls. The IMUX is an intelligent Multiplexer (see later) that allows a single high-speed line to be
shared by a number of users at the same time. A DSE (Data Switch Exchange) allows computers
exchange data over the lines.
IMUX
PBX
DSE
IMUX
PBX
DSE
IMUX
PBX
DSE
Site A Site B
Site C
Leased Lines
Enterprise-wide
Network
Phones
Computers
DSE Data Switching
Exchange
PBX Private Branch
Exchange
IMUX Intelligent
Multiplexer
Private Network
Data Transmission: Analog and Digital
Analog Transmission:
Dominated the last 100 years and is here for a while yet. Network designers made use of the
existing telephone network which was aimed at voice transmission. This is actually very poor for
computer networking. For example 2 computers connected by a direct cable can achieve a data
rate of up to 100 Mbps with very low error rate. Using phone lines, 56 Kbps is the maximum
transmission speed with a relatively high error rate. It is approximately 10 orders of magnitude
worse: the cost of bus ticket to town versus a moon landing is same order of magnitude.
Modems
Phone lines deal with frequencies of 300 to 3000 Hz. A computer outputs a serial stream of bits
(1’s, 0’s). A modem is a device that accepts such a bit stream and converts it to an analog signal,
using modulation. It also performs the inverse conversion. Thus two computers can be connected
using two modems and phone line.
Using a modem, a continuous signal (tone) is sent in the range 1000 to 2000 Hz. To transmit
information, this carrier signal is modulated. Its amplitude, frequency, phase or a combination
can be modulated .
DC SIGNALS
FROM TERMINAL
OR COMPUTER
MODEM
MODEM
DC SIGNALS
TO A TERMINAL
OR COMPUTER
This diagram illustrates the carrier signal always present between two modems.
One common form of modulation Frequency Modulation (FM).
FREQUENCY MODULATION
0 1 1 0 0 1 0
This is the most common form of modulation used for data transmission. In FM, the carrier
signal is modulated between two different frequencies (say 1200Hz and 2200Hz) without
affecting the amplitude in accordance with the digital signal that it must send.
The serial interface between the modem and computer is governed by the RS-232 standard (also
known as the CCITT V24 standard).
Digital Transmission
Digital transmission takes place in the form of pulses representing bits (1’s and 0’s). This is the
type of communication used internally in computers. The high-speed trunks linking central
phone exchanges use digital transmission. It has a lower error rate than analog transmission.
The local loop (from phone to exchange) is still analog. This must be converted at the exchange
to digital. A device called a Codec (coder/decoder) does this. It samples the analog signal 8000
times per second and encodes the signal digitally by representing each sample as a binary
number. The technique used is called Pulse Coded Modulation or PCM.
Types of Transmission
There are three types of transmission.
1. Simplex: information is transmitted in one direction only and the roles of transmitter and
receiver are fixed. This form is not used for conventional data transmission.
2. Half Duplex (HDX): transmission is allowed in both directions but in only one direction
at a time. Data communication systems that use the telephone network usually transmit in
HDX.
3. Full Duplex (FDX): sender/receiver can transmit and receive from each other at the same
time. In order to transmit in FDX, the user usually has private direct lines.
SIMPLEX
HALF DUPLEX
FULL DUPLEX
Multiplexing
With high bandwidth channels it is possible to share the channel so that a number of users can
use the channel at the same time. This is called multiplexing.
For example 4 users could each operate terminals at 10,000 bps connected to mainframe over a
single 40,000 bps line as shown in the figure below. The 4 lines from the terminals are connected
to a multiplexer which is connected to another multiplexer by the 40,000 bps line. The second
multiplexer de-multiplexes the signal onto 4 separate lines for the computer. This gives us
efficient line usage and saves money.
Multiplexing is also used for voice transmission where optic fibres and microwave cable can
handle from 8000 to 16000 simultaneous conversations. There are a number of types of
multiplexing. Two common ones are Time Division Multplexing (TDM) and Frequency
Division Multiplexing (FDM).
Standards and Protocols
Standards and protocols are required to govern the physical and logical connections between
terminals, computers and other equipment. They are vital for data communications and computer
networking
Typically standards fall into two groups: official standards (from national standards bodies) and
de facto standards established by common usage.
An early official standard was the EIA RS-232-C for data transfer over wires. (Electronic
Industries Association Recommended Standard)
Co
mput
er
MUX
MUX
High
Speed
Line
Terminals
Another set of standards was the V series e.g. V-24 from the CCITT body which is a part of the
U.N.
Standards for LANs (local area networks) were proposed by the American Institute of Electrical
and Electronics Engineers (IEEE), an influential organisation.
A recommendation for standards called X-25 for access to and transmission methods for packet
switched data networks (PSDNs) were proposed by the CCITT.
The existence of different standards bodies regulating data communications is obviously a
handicap for global standardisation. In addition, manufacturers have developed their own
standards to maintain their market position e.g. Digital’s Decnet standards. (The Digital
corporation was taken over by Compaq which in turn has been taken over by Hewlett-Packard).
The International Standards Organisation (ISO) took an initiative to develop universal data
communication standards to unite standards bodies, computer and telecommunications
manufacturers and users. The ISO Open Systems Interconnection (OSI ) reference model was
put forward as a framework to develop standards for data communication products. An open
system is one that is prepared to communicate with any other open system by using agreed rules
or protocols on how the communication should take place.
ARPANET:
ARPANET was one of the first WANs and a forerunner of the Internet.
It used a network protocol called IP (Internet Protocol) to handle the interconnection of WANs
to LANs. It used a transport protocol call TCP (Transmission Control Protocol) to govern
transmission of data. The two are often referred to as TCP/IP and the major protocols of the
Internet. It also provided protocols for file transfer (FTP), remote login (TELNET) and e-mail
(SMTP). These three protocols are still very important and widely used protocols
Internetworking is the term used for the connection of two networks. The growth of
internetworking between LANs and WANs and WANs and WANs led to what is now referred to
as the Internet. A computer that provides for the interconnection of two different networks is
called a gateway.