Mobile Computing Lab Manual Updated On 20th March 2018
Mobile Computing Lab Manual Updated On 20th March 2018
ENGINEERING
LAB MANUAL OF
MOBILE COMPUTING LAB
ETIT 452
2
MAHARAJA AGRASEN INSTITUTE OF TECHNOLOGY
Vision of the Institute
To nurture young minds in a learning environment of high academic value and imbibe
spiritual and ethical values with technological and management competence.
Mission of the Institute
The Institute shall endeavor to incorporate the following basic missions in the teaching
methodology:
Engineering Hardware – Software Symbiosis
Practical exercises in all Engineering and Management disciplines shall be carried out by
Hardware equipment as well as the related software enabling deeper understanding of
basic concepts and encouraging inquisitive nature.
Life – Long Learning
The Institute strives to match technological advancements and encourage students to
keep updating their knowledge for enhancing their skills and inculcating their habit of
continuous learning.
Liberalization and Globalization
The Institute endeavors to enhance technical and management skills of students so that
they are intellectually capable and competent professionals with Industrial Aptitude to
face the challenges of globalization.
Diversification
The Engineering, Technology and Management disciplines have diverse fields of studies
with different attributes. The aim is to create a synergy of the above attributes by
encouraging analytical thinking.
Digitization of Learning Processes
The Institute provides seamless opportunities for innovative learning in all Engineering
and Management disciplines through digitization of learning processes using analysis,
synthesis, simulation, graphics, tutorials and related tools to create a platform for multi-
disciplinary approach.
Entrepreneurship
The Institute strives to develop potential Engineers and Managers by enhancing their
skills and research capabilities so that they become successful entrepreneurs and
responsible citizens.
3
Vision of the Department:
PEO1: To train students to have successful careers in computer engineering field or to be able to
successfully pursue advanced degrees.
PEO3: Train students to communicate effectively, work collaboratively and exhibit high levels
of professionalism and ethical responsibility.
4
1. Introduction to Mobile Computing Lab
1.1 Objective
The objective of the Mobile Computing lab course is to introduce CSE students to the
field of Mobile Apps development and cellular networks simulations using various open
source tools. It would give them hands-on experience through a set of experiments using
NS3, Android and XML.
452.1) To provide guidelines, design principles and experience in developing applications for
small, mobile devices, including an appreciation of context and location aware services
452.4) To understand the use of NS3 in simulating various types, topologies of Wireless
networks
452.5) To appreciate the social and ethical issues of mobile computing, including privacy.
452.6) Gain an understanding of performance issues in advanced wireless and mobile networks.
5
2. Lab requirements (details of H/W & S/W to be used)
Hardware
Requirements:
Software
Requirements: Linux( Fedora/Ubuntu), Android Studio, NS3 3.24 and above
6
3. LIST OF EXPERIMENTS
1. Write a WML program to print a formatted Text on the mobile Screen using various
tags.
2. Write a WML program to connect multiple cards from same desk.
3. Write WML program to display table with three columns Image name, Image and third
column contain hyperlink to open another card.
4. Write a WML program to create a form with multiple options.
5. Write a WML program to use the time control and to trigger On pick event
6. Write a WML script to find maximum out of two numbers with help of inbuilt function
Lang.Max() and to find absolute value with help of inbuilt function Lang.abs()
7. Write a Program in NS3 to Simulate OLSR
8. Write a Program in NS3 to Simulate AODV
9. Make an application of your choice using WML or Android.
10.Write a Android Program design an application using Hybrid Approach.
7
4. LIST OF EXPERIMENTS
(Beyond Curricula)
8
5 FORMAT OF THE LAB RECORD TO BE
PREPARED BY THE STUDENTS
The front page of the lab record prepared by the students should have a cover page as displayed below.
MOBILE COMPUTING
ETIT 452
Font should be (Size 20”, italics bold, Times New Roman)
Roll No.:
Semester:
9
6. Experiments according to the lab syllabus
Ex Experiment Name Date of Date of Marks Signature
p. performance checking
no
10
7.MARKING SCHEME FOR THE PRACTICAL EXAMS
Total Marks: 40
Timely
Submission
4 2 On time submission Late submission
of Lab
Record
Each experiment will be evaluated out of 10 marks. At the end of the semester average of 8 best
performed practical will be considered as marks out of 40.
11
EXTERNAL PRACTICAL EXAM
It is taken by the concerned lecturer of the batch and by an external examiner. In this exam
student needs to perform the experiment allotted at the time of the examination, a sheet will
be given to the student in which some details asked by the examiner needs to be written and
at the last viva will be taken by the external examiner.
Total Marks: 60
2. Viva Voice: 15
3. Experiment performance: 15
4. File submitted: 10
NOTE:
12
8. Introduction to WML
WML is a markup language designed especially for specifying and displaying content on WAP
(Wireless Application Protocol) devices. WML is part of the WAP application environment,
which requires the use of WML.
WML is the wireless equivalent of HTML for the Web. WML is based on XML and derived
from xHTML (the XML version of HTML). There are many differences between WML and
HTML. For example, WML has a different mechanism for linking between its pages called
“cards” as compared to linking between HTML pages. WML browsers are stricter than HTML
browsers by not being tolerant of errors. WML browsers enforce the WML requirement of
matching closing “tags”, an XML characteristic.
WML works with the WAP micro browsers found on WAP devices. This browser is cognizant
of the limited capabilities of WAP devices such as
small displays,
limited processing power,
limited memory,
narrow bandwidth connection,
limited battery use without recharging
To address the limitations of WAP devices, WML uses the metaphor of card decks, and each
page is referred to as a card. The card is the basic unit of navigation and user interface. The user
can view only card at a time. WML browsers read the whole deck (complete document) from the
server to minimize interaction with the server. Consequently, when flipping (navigating)
between the cards in a deck, the browser does not contact the server. This eliminates delays
(because each card contains very little text and users are likely to move quickly from one card to
another).
A WAP deck is the equivalent of a Web page, the card being the portion of the Web page that
can be seen on the screen. Navigation within the cards of a deck is done within the WAP device
just as scrolling a Web page is done within the Web device. (without contacting servers in both
cases).
An HTML writer does not worry about screen or display boundaries. Instead, the Web browser
manages issues relating to the screen boundaries. But a WML writer must be aware of screen
boundaries of WAP devices when writing code for cards.
Web server requests are routed through WAP gateways (proxies). A Web server may generate
WML content for WAP devices or it may simply dish out HTML (XML).
In case the Web server generates HTML (XML), the WAP gateways must convert the HTML
(XML) to WML. Before sending the WML to the WAP device, the gateway compresses it to
WMLC (the C in WMLC is for compressed). If the WML generated by the Web sever is
WMLC, then the compression step is skipped. Incidentally, converting HTML automatically to
WML typically does not produce good or even usable results. For best results, Web servers
should generate WML for WAP devices.
Advantages of WML
13
Like HTML, WML is easy to use. However, compared to HTML, WML has the following
advantages in the context of wireless:
Disadvantages of WML:
Like HTML, WML does specify how the content is to be displayed. Thus micro browsers
on different WAP devices are likely to display the WML content differently.
WAP devices such as WAP phones will not accept large decks (1.4K for some WAP
phones).
There are many variations between WAP phones, for example Screen sizes, keypads, and
soft keys can be different. Consequently, WML decks should be tested on at least the
important WAP devices. This variation is similar to the variation found with Web
browsers and their platforms. The problem is harder in case of WML because there are
many more WAP devices than Web browsers and their platforms. Also, it is harder to
figure out the “least common denominator”, i.e., set of features that will work reasonably
well on all or most WAP devices.
14
Text Elements
WML Elements Purpose
Image Elements
WML Elements Purpose
Anchor Elements
WML Elements Purpose
15
Event Elements
WML Elements Purpose
Task Elements
Input Elements
WML Elements Purpose
16
Variable Elements
WML Elements Purpose
17
9. Introduction to NS3
Some of basic steps involved in making programs in NS3 are list below:
Simple client-server communication
1. Create a simple topology of two nodes (Node1, Node2) separated by a point-to-point link.
2. Setup a UdpClient on one Node1 and a UdpServer on Node2. Let it be of a fixed data rate
Rate1.
3. Start the client application, and measure end to end throughput whilst varying the latency of
the link.
4. Now add another client application to Node1 and a server instance to Node2. What do you
need to configure to ensure that there is no conflict?
5. Repeat step 3 with the extra client and server application instances. Show screenshots of
pcap traces which indicate that delivery is made to the appropriate server instance.
TCP variants
1. Create a simple dumbbell topology, two client Node1 and Node2 on the left side of the
dumbbell and server nodes Node3 and Node4 on the right side of the dumbbell. Let Node5
and Node6 form the bridge of the dumbbell. Use point to point links.
2. Install a TCP socket instance on Node1 that will connect to Node3.
3. Install a UDP socket instance on Node2 that will connect to Node4.
4. Start the TCP application at time 1s.
5. Start the UDP application at time 20s at rate Rate1 such that it clogs half the dumbbell
bridge's link capacity.
6. Increase the UDP application's rate at time 30s to rate Rate2 such that it clogs the whole of
the dumbbell bridge's capacity.
7. Use the ns-3 tracing mechanism to record changes in congestion window size of the TCP
instance over time. Use gnuplot/matplotlib to visualise plots of cwnd vs time.
8. Mark points of fast recovery and slow start in the graphs.
9. Perform the above experiment for TCP variants Tahoe, Reno and New Reno, all of which
are available with ns-3.
18
TCP and router queues
1. Create a simple dumbbell topology, two client Node1 and Node2 on the left side of the
dumbbell and server nodes Node3 and Node4 on the right side of the dumbbell. Let Node5
and Node6 form the bridge of the dumbbell. Use point to point links.
2. Add drop tail queues of size QueueSize5 and QueueSize6 to Node5 and Node6,
respectively.
3. Install a TCP socket instance on Node1 that will connect to Node3.
4. Install a TCP socket instance on Node2 that will connect to Node3.
5. Install a TCP socket instance on Node2 that will connect to Node4.
6. Start Node1--Node3 flow at time 1s, then measure it's throughput. How long does it take to
fill link's entire capacity?
7. Start Node2--Node3 and Node2--Node4 flows at time 15s, measure their throughput.
8. Measure packet loss and cwnd size, and plot graphs throughput/time, cwnd/time and packet
loss/time for each of the flows.
9. Plot graph throughput/cwnd and packet loss/cwnd for the first flow. Is there an optimal
value for cwnd?
10. Vary QueueSize5 and QueueSize6.
Routing (Optimised Link State Routing)
1. Create a wireless mobile ad-hoc network with three nodes Node1, Node2 and Node3. Install
the OLSR routing protocol on these nodes.
2. Place them such that Node1 and Node3 are just out of reach of each other.
3. Create a UDP client on Node1 and the corresponding server on Node3.
4. Schedule Node1 to begin sending packets to Node3 at time 1s.
5. Verify whether Node1 is able to send packets to Node3.
6. Make Node2 move between Node1 and Node3 such that Node2 is visible to both A and C.
This should happen at time 20s. Ensure that Node2 stays in that position for another 15s.
7. Verify whether Node1 is able to send packets to Node3.
8. At time 35s, move Node2 out of the region between Node1 and Node3 such that it is out of
each other's transmission ranges again.
9. Verify whether Node1 is able to send packets to Node3.
10. To verify whether data transmissions occur in the above scenarios, use either the tracing
mechanism or a RecvCallback() for Node3's socket.
11. Plot the number of bytes received versus time at Node3.
12. Show the pcap traces at Node 2's Wifi interface, and indicate the correlation between
Node2's packet reception timeline and Node2's mobility.
19
Wifi RTS/CTS
1. Setup a 5x5 wireless adhoc network with a grid. You may use examples/wireless/wifi-
simple-adhoc-grid.cc as a base.
2. Install the OLSR routing protocol.
3. Setup three UDP traffic flows, one along each diagonal and one along the middle (at high
rates of transmission).
4. Setup the ns-3 flow monitor for each of these flows.
5. Now schedule each of the flows at times 1s, 1.5s, and 2s.
6. Now using the flow monitor, observe the throughput of each of the UDP flows.
Furthermore, use the tracing mechanism to monitor the number of packet collisions/drops at
intermediary nodes. Around which nodes are most of the collisions/drops happening?
7. Now repeat the experiment with RTS/CTS enabled on the wifi devices.
8. Show the difference in throughput and packet drops if any.
Wifi Channels
1. Setup a 2-nodes wireless adhoc network. Place the nodes at a fixed distance in a 3d
scenario.
2. Install all the relevant network stacks, up to and including UDP.
3. Setup a CBR transmission between the nodes, one acting as a server and one as a client.
Take the iperf[1] behaviour as an example.
4. Setup counters and outputs for packets sent and received.
5. Schedule the simulation to run for enough time to obtain statistically relevant results
(suggestion: analyze some test results and reduce the simulation time accordingly).
6. Repeat the simulation varying the distance between the nodes from a minimum of 1meter to
the point where the nodes can't transmit/receive anymore.
7. Repeat the above varying the channel models and the transmission/receive parameters like node's
position above the ground, transmission power, etc.
8. Show the differences between the various channel models, and comment them. Identify the
channel model that is more appropriate for each case (indoor, outdoor, LoS, NLoS, etc.).
20
10. Experiment No 1
AIM: Write a WML program to print a formatted Text on the mobile Screen using
various tags
a. Syntax
<p>
..text..
..images..
..links..
</p>
b. WML Tags and Attributes
10.2 Write a WML program to display your name in bold, italic, small, big and emphasize
format.
OUTPUT:
21
10.3 Short Questions
22
11. Experiment No 2
AIM: Write a WML program to connect multiple cards from same desk
The <anchor>...</anchor> tag pair is used to create an anchor link. It is used together with other
WML elements called <go/>, <refresh> or <prev/>. These elements are called task elements and
tell WAP browsers what to do when a user selects the anchor link
You can enclose Text or image along with a task tag inside <anchor>...</anchor> tag pair.
Attributes:
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.2//EN"
"http://www.wapforum.org/DTD/wml12.dtd">
<wml>
<card title="Anchor Element">
<p>
<anchor>
<go href="nextpage.wml"/>
</anchor>
</p>
<p>
<anchor>
<prev/>
</anchor>
</p>
</card>
</wml>
23
11.2 Write a WML program to declare three cards and provide Hyper Link to move from one
card to another card.
Output:
24
11.3 Short Questions
25
12. Experiment No.3
AIM: Write WML program to display table with three columns Image name, Image
and third column contain hyperlink to open another card
Introduction about WML Tags:
The <table> element along with <tr> and <td> is used to create a table in WML. WML does not
allow the nesting of tables
Attributes:
<wml>
<card title="WML Tables">
<p>
<table columns="3" align="LCR">
<tr>
<td>Col 1</td>
<td>Col 2</td>
<td>Col 3</td>
</tr>
<tr>
<td>A</td>
<td>B</td>
<td>C</td>
26
</tr>
<tr>
<td>D</td>
<td>E</td>
<td>F</td>
</tr>
</table>
</p>
</card>
</wml>
OUTPUT:
12.1: Write WML program to display user personal information like Id, Name, Address,
Phone No and pass same information on another deck.
The <input/> element is used to create input fields and input fields are used to obtain
alphanumeric data from users.
Attributes:
OUTPUT:
28
12.3 Short Questions:
29
13. Experiment No.4
AIM: Write a WML program to create a form with multiple options
Attributes:
iname text Names the variable that is set with the index result
of the selection
name text Names the variable that is set with the result of the
selection
tabindex number Sets the tabbing position for the select element
title text Sets a title for the list
value text Sets the default value of the variable in the "name"
attribute
xml:lang language_code Sets the language used in the element
class class data Sets a class name for the element.
id element ID A unique ID for the element.
<wml>
<card title="Selectable List">
<p> Select a Tutorial :
<select>
<option value="htm">HTML Tutorial</option>
<option value="xml">XML Tutorial</option>
<option value="wap">WAP Tutorial</option>
30
</select>
</p>
</card>
</wml>
For Multiple Options:
<wml>
<card title="Selectable List">
<p> Select a Tutorial :
<select multiple="true">
<option value="htm">WML Tutorial A</option>
<option value="xml">WML Tutorial B</option>
<option value="wap">WML Tutorial C</option>
</select>
</p>
</card>
</wml>
OUTPUT:
Output:
31
13.4 Short Questions:
Q.No.2 List out the Databases used to store Data of WML pages?
32
14. Experiment No. 5
AIM: Write a WML program to use the time control and to trigger On pick event
The ontimer event is used to trigger an event after a given time period. Suppose students wants
to display a message after 5 seconds of loading a card then you can use this event to do so.
A task to be performed.
</onevent>
<timer value="50"/>
OUTPUT:
When you load this program, it shows you the following screen:
If you do not select given Enter option then after 5 seconds you will be directed to welcome page
and following screen will be displayed automatically.
33
14.1 Write a WML program to trigger On pick event
The onpick attribute is a great shortcut if you are using a select menu. Instead of writing a lot of
code that allows the user to go to another card if an option is selected, you can simply place the
destination into the onpick attribute.
Select a tutorial :
<select title="tutorials" name="selection_list">
<option onpick="#xhtml">XHTML Tutorial</option>
<option onpick="#wap">WAP Tutorial</option>
</select>
Output:
34
14.3 Short Questions:
Q.No.1 Does WAP run over GPRS?
35
15. Experiment No. 6
AIM : Write a WML script to find maximum out of two numbers with help of
inbuilt function Lang.Max() and to find absolute value with help of inbuilt
function Lang.abs()
The Lang.max function compares two given numbers and then returns the larger value. If the
two numbers prove to be equal, the first number is selected. The value and type (floating-point
or integer) of the selected number is not changed.
36
WMLBrowser.go("MaxExample.wml#card2");
};
OUTPUT:
Syntax: Lang.abs(value)
Value: The mandatory value parameter can be any positive or negative single-precision floating-
point number or any positive or negative integer number (including zero). The floating-point
number must reside on or between the largest number and the smallest nonzero number
supported by the browser. These boundary values can be determined using the Float.maxFloat
and Float.minFloat functions.
Output:
37
15.3 Short Questions:
4.What is the process where WML cards request the device to access WAP? - WMLScript
6.What is the process of adding the client side logic to WAP using WMLScript?
38
16. Experiment No. 7
AIM: Write a Program in NS3 to Simulate OLSR
16.1 STEPS:
1. Create a wireless mobile ad-hoc network with three nodes Node1, Node2 and Node3. Install the
OLSR routing protocol on these nodes.
2. Place them such that Node1 and Node3 are just out of reach of each other.
3. Create a UDP client on Node1 and the corresponding server on Node3.
4. Schedule Node1 to begin sending packets to Node3 at time 1s.
5. Verify whether Node1 is able to send packets to Node3.
6. Make Node2 move between Node1 and Node3 such that Node2 is visible to both A and C. This
should happen at time 20s. Ensure that Node2 stays in that position for another 15s.
7. Verify whether Node1 is able to send packets to Node3.
8. At time 35s, move Node2 out of the region between Node1 and Node3 such that it is out of
each other's transmission ranges again.
9. Verify whether Node1 is able to send packets to Node3.
10. To verify whether data transmissions occur in the above scenarios, use either the tracing
mechanism or a RecvCallback() for Node3's socket.
11. Plot the number of bytes received versus time at Node3.
12. Show the pcap traces at Node 2's Wifi interface, and indicate the correlation between Node2's
packet reception timeline and Node2's mobility.
Network topology
// n0
\ 5 Mb/s, 2ms
\ 1.5Mb/s, 10ms
n2 -------------------------n3---------n4
/
/ 5 Mb/s, 2ms
n1
// - all links are point-to-point links with indicated one-way BW/delay
// - CBR/UDP flows from n0 to n4, and from n3 to n1
// - UDP packet size of 210 bytes, with per-packet interval 0.00375 sec.
// (i.e., DataRate of 448,000 bps)
// - DropTail queues
// - Tracing of queues and packet receptions to file "simple-point-to-point-olsr.tr"
16.2 Program:
39
#include <iostream>
#include <fstream>
#include <string>
#include <cassert>
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/internet-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/applications-module.h"
#include "ns3/olsr-helper.h"
#include "ns3/ipv4-static-routing-helper.h"
#include "ns3/ipv4-list-routing-helper.h"
NS_LOG_COMPONENT_DEFINE ("SimplePointToPointOlsrExample");
int
main (int argc, char *argv[])
{
// Users may find it convenient to turn on explicit debugging
// for selected modules; the below lines suggest how to do this
#if 0
LogComponentEnable ("SimpleGlobalRoutingExample", LOG_LEVEL_INFO);
#endif
// Allow the user to override any of the defaults and the above
// DefaultValue::Bind ()s at run-time, via command-line arguments
CommandLinecmd;
cmd.Parse (argc, argv);
// Enable OLSR
40
NS_LOG_INFO ("Enabling OLSR Routing.");
OlsrHelperolsr;
Ipv4StaticRoutingHelper staticRouting;
Ipv4ListRoutingHelperlist;
list.Add (staticRouting, 0);
list.Add (olsr, 10);
InternetStackHelper internet;
internet.SetRoutingHelper (list); // has effect on the next Install ()
internet.Install (c);
AsciiTraceHelper ascii;
p2p.EnableAsciiAll (ascii.CreateFileStream ("simple-point-to-point-olsr.tr"));
p2p.EnablePcapAll ("simple-point-to-point-olsr");
return 0;
}
AIM: Write a program to show the introduction of multi point relay set as a subset of the
neighbor set does not destroy the connectivity properties of the network
16.3 Output:
42
43
16.4 Short Questions:
44
17. Experiment No. 8
AIM: Write a Program in NS3 to Simulate AODV
17.1 Introduction
Ad hoc On-Demand Distance Vector (AODV) [1] is a routing protocol for mobile ad-hoc
net- works. AODV is a reactive routing protocol which means that routes are
discovered when necessary, routes are also maintained as long as necessary. Every node
maintains its monoton- ically increasing sequence number which increases every time the
node notices change in the neighborhood topology. Routing tables are used to store
routing information where data is stored as follows:
life_time gets updated every time the route is used (If not used within its life_time,
route expires).
AODV Routing Protocol works as follows: Assuming in the network in the figure
below we need to discover route between S and D.
It works as follows:
45
5. Node C receives RREQ
(b) It has a route to D, and the seq # for route to D is >= D 0 s seq # in
RREQ (c) C creates a Route Reply (RREP)
17.2 Program
Source Code:
#include "ns3/aodv-module.h"
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/internet-module.h"
#include "ns3/mobility-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/wifi-module.h"
#include "ns3/v4ping-helper.h"
#include <iostream>
#include <cmath>
46
class AodvExample
{
public:
AodvExample ();
bool Configure (int argc, char **argv);
void Run ();
void Report (std::ostream & os);
private:
// parameters
uint32_t size;
doublestep;
doubletotalTime;
boolpcap;
boolprintRoutes;
// network
NodeContainernodes;
NetDeviceContainerdevices;
Ipv4InterfaceContainerinterfaces;
private:
void CreateNodes ();
void CreateDevices ();
void InstallInternetStack ();
void InstallApplications ();
};
test.Run ();
test.Report (std::cout);
return 0;
}
//-----------------------------------------------------------------------------
AodvExample::AodvExample () :
size (10),
step (100),
totalTime (10),
pcap (true),
printRoutes (true)
{
}
bool
47
AodvExample::Configure (int argc, char **argv)
{
// Enable AODV logs by default. Comment this if too noisy
// LogComponentEnable("AodvRoutingProtocol", LOG_LEVEL_ALL);
SeedManager::SetSeed (12345);
CommandLinecmd;
void
AodvExample::Run ()
{
// Config::SetDefault ("ns3::WifiRemoteStationManager::RtsCtsThreshold", UintegerValue
(1)); // enable rts cts all the time.
CreateNodes ();
CreateDevices ();
InstallInternetStack ();
InstallApplications ();
void
AodvExample::Report (std::ostream &)
{
}
void
AodvExample::CreateNodes ()
{
std::cout <<"Creating "<< (unsigned)size<<" nodes "<<step<<" m apart.\n";
nodes.Create (size);
// Name nodes
for (uint32_t i = 0; i <size; ++i)
{
std::ostringstream os;
os <<"node-"<< i;
Names::Add (os.str (), nodes.Get (i));
48
}
// Create static grid
MobilityHelpermobility;
mobility.SetPositionAllocator ("ns3::GridPositionAllocator",
"MinX", DoubleValue (0.0),
"MinY", DoubleValue (0.0),
"DeltaX", DoubleValue (step),
"DeltaY", DoubleValue (0),
"GridWidth", UintegerValue (size),
"LayoutType", StringValue ("RowFirst"));
mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel");
mobility.Install (nodes);
}
void
AodvExample::CreateDevices ()
{
WifiMacHelper wifiMac;
wifiMac.SetType ("ns3::AdhocWifiMac");
YansWifiPhyHelper wifiPhy = YansWifiPhyHelper::Default ();
YansWifiChannelHelper wifiChannel = YansWifiChannelHelper::Default ();
wifiPhy.SetChannel (wifiChannel.Create ());
WifiHelperwifi;
wifi.SetRemoteStationManager ("ns3::ConstantRateWifiManager", "DataMode",
StringValue ("OfdmRate6Mbps"), "RtsCtsThreshold", UintegerValue (0));
devices = wifi.Install (wifiPhy, wifiMac, nodes);
if (pcap)
{
wifiPhy.EnablePcapAll (std::string ("aodv"));
}
}
void
AodvExample::InstallInternetStack ()
{
AodvHelper aodv;
// you can configure AODV attributes here using aodv.Set(name, value)
InternetStackHelperstack;
stack.SetRoutingHelper (aodv); // has effect on the next Install ()
stack.Install (nodes);
Ipv4AddressHelperaddress;
address.SetBase ("10.0.0.0", "255.0.0.0");
interfaces = address.Assign (devices);
if (printRoutes)
{
Ptr<OutputStreamWrapper> routingStream = Create<OutputStreamWrapper>
("aodv.routes", std::ios::out);
aodv.PrintRoutingTableAllAt (Seconds (8), routingStream);
}
49
}
void
AodvExample::InstallApplications ()
{
V4PingHelper ping (interfaces.GetAddress (size - 1));
ping.SetAttribute ("Verbose", BooleanValue (true));
Output:
50
17.3 Short Questions
51
18. Experiment No. 9
18.1 Steps:
After you have successfully installed the Android SDK, it is time to configure it. After installing
the Android SDK, you will get a window like this:
52
Just de-select the Documentation for Android SDK and Samples for SDKpackages if you want
to reduce the installation size and time. Click on Install 7packages to continue with the
installation. You will get a dialogue box like this:
It will take some time to install, Once it is done, you can close the SDK manager.
54
Just click on the Add button as shown in the picture and add https://dl-
ssl.google.com/android/eclipse/ as the location. When you press OK, Eclipse will start to search
for the required plug-in and finally it will list the found plug-ins.
The last step is to create Android Virtual Device, which students will use to test your Android
applications. To do this, open Eclipse and Launch Android AVD Manager from options Window
55
> AVD Manager and click on New which will create a successful Android Virtual Device. Use
the screenshot below to enter the correct values.
Before we write the code, you need to know how to take input from the user. The most efficient
way of taking input from the user is to use the Scanner class, which is found in the java.io
package as it is just a two-step process.
56
/* or String input = (new
Scanner(System.in)).next(); */
Students are recommended using the Scanner class because it works equally well on command
line as well as with Eclipse that we will use to make the Rock Paper Scissors app.
import java.util.Scanner;
import java.util.Random;
String response;
System.out.println();
computerInt = generator.nextInt(3)+1;
computerPlay = "R";
else if (computerInt == 2)
computerPlay = "P";
else if (computerInt == 3)
computerPlay = "S";
// stored as a string
personPlay = scan.next();
personPlay = personPlay.toUpperCase();
if (personPlay.equals(computerPlay))
System.out.println("It's a tie!");
else if (personPlay.equals("R"))
if (computerPlay.equals("S"))
else if (computerPlay.equals("P"))
else if (personPlay.equals("P"))
if (computerPlay.equals("S"))
else if (computerPlay.equals("R"))
58
else if (personPlay.equals("S"))
if (computerPlay.equals("P"))
else if (computerPlay.equals("R"))
else
Now calling the Java code in Eclipse is a tricky process and it helps to pay attention while you're
doing this. Launch Eclipse and click File > New > Java Project
When the Create a Java Project box appears, it's time to give your project a name. Click on
Finish to save it and it should appear in the Package Explorer window. Then we are supposed to
add a package which will contain all our package files. Click on New Java Package icon to do
this, as shown in the screenshot below.
59
Name your project and then click Finish.
Now we need to add a Java Class, which is as easy as adding a Java Package.
60
After giving it a name, make sure that the following options are checked:
61
After you create a new class, it will show up in the Work Space where you can write or copy the
code.
Now you need to build the application and to do this, Right Click on your Android Project and
select Android Tools->Export Signed Application Package. After selecting the export button,
select Create new keystore and it will take you to the location where you want to save it, so give
it a name and save it. Fill in all the required fields that are self-explanatory and save it. You have
successfully exported the apk file to your computer and you can test the app it on your android
device.
8. Testing
62
Testing is as important as developing the app because your app will be of no use if it doesn't run
properly or shows errors. Luckily, there is an integrated testing framework in Android
Framework, which you can use to test all the aspects of your application. SDK tools can also
help set up and test applications. SDK will help you test different aspects of your app no matter
if you are planning on running your tests within an emulator or any Android device.
It is recommended using ADT for the testing process, as it is comparatively easier than the other
tools. Using ADT, you can easily create a test project and link it to the application under test.
The great thing about the ADT is that it automatically adds the
necessary <instrumentation> element in the test package's manifest file.
Launch Eclipse from the Start Menu and click on File > New > Other and from the drop-down
menu, click on Android Test Project, then at the bottom of the dialog click Next. Enter any name
you want and in the Test Target panel, set An Existing Android Project and browse to the Rock
Paper Scissors app you made. Now you should be able to see the wizard completing the Test
Target Package, Application Name, and Package Name fields for you.
Choose the Android SDK platform from the Build Target Panel that the application to be tested
is using. Click the Finish button to complete the Wizard and if it is disabled, look for error
messages at the top to fix any problems.
63
18.3 Short Questions:
64
19. Experiment No. 10
AIM: Write a Android Program to create list view, grid view and database
connectivity
Introduction: GRID VIEW
In android GridView is a view group that display items in two dimensional scrolling grid (rows
and columns), the grid items are not necessarily predetermined but they are automatically
inserted to the layout using a ListAdapter. Users can then select any grid item by clicking on it.
GridView is default scrollable so we don’t need to use ScrollView or anything else with
GridView.
Adapter Is Used To Fill Data In Gridview: To fill the data in a GridView we simply use adapter
and grid items are automatically inserted to a GridView using an Adapter which pulls the content
from a source such as an arraylist, array or database. You can read full Adapter tutorial here.
GridView in Android Studio: Gridview is present inside Containers. From there you can drag
and drop on virtual mobile screen to create it. Alternatively you can also XML code to create it.
android:id="@+id/simpleGridView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:numColumns="3"/>
65
Introduction: LIST VIEW
List of scrollable items can be displayed in Android using ListView. It helps you to displaying
the data in the form of a scrollable list. Users can then select any list item by clicking on it.
ListView is default scrollable so we do not need to use scroll View or anything else with
ListView.
ListView is widely used in android applications. A very common example of ListView is your
phone contact book, where you have a list of your contacts displayed in a ListView and if you
click on it then user information is displayed.
Adapter: To fill the data in a ListView we simply use adapters. List items are automatically
inserted to a list using an Adapter that pulls the content from a source such as
an arraylist, array or database.
ListView in Android Studio: Listview is present inside Containers. From there you can drag and
drop on virtual mobile screen to create it. Alternatively you can also XML code to create it.
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/simpleListView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context="abhiandroid.com.listexample.MainActivity">
</ListView>
66
Introduction: Database Connectivity
SQLite
Like other RDBMSs, data is accessed in a SQLite database by using Structured Query Language
(SQL).
Cursor: a class provides access to the results of a database query. Its methods include:
getCount(): returns the number of rows contained within the result set.
move(): moves by a specified offset from the current position in the result set.
get<type>() (such as getInt(), getDouble(), so on): returns the value of the specified <type>
contained at the specified column index of the row at the current cursor position.
SQLiteDatabase: provides the primary interface between the application code and underlying
SQLite database. Its methods include:
query(): performs a specified database query and returns matching results via a Cursor object.
execSQL(): executes a single SQL Statement that does not return result data.
rawQuery(): executes an SQL query statement and returns matching results in the form of a
Cursor object.
SQLiteOpenHelper : is designed to make it easier to create and update databases. Its methods
include:
onCreate(): called when the database is created for the first time.
onUpgrade(): called in the event that the application code contains a more recent database
version number reference.
ContentValues : allows key/value pairs to be declared consisting of table column identifiers and
the values to be stored in each column. Its methods include:
For Example: Creating a Data Application, we have to follow certain steps as follows.
My application will interact with a database named StudentDB.db, which contains a single table
named Student. The Student table schema will look like this:
The application will consist of an activity and a database handler class (MyDBHandler class).
The database handler will be a subclass of SQLiteOpenHelper and will provide an abstract layer
between the underlying SQLite database and the activity class. A third class (Student class) will
need to be implemented to hold the database entry data as it is passed between the activity and
the handler. My application model can be shown in the following figure:
68
Data Model Class
The Student class contains fields, constructors, and properties as follows:
We create the Student class in the Android Studio by selecting app > java.
69
Right-click the myfirstdatabase package and selecting New > Java Class.
Type Student in the Name item, maintain the default options, and click the OK button:
70
// properties
public void setID(int id) {
this.studentID = id;
}
public int getID() {
return this.studentID;
}
public void setStudentName(String studentname) {
this.studentName = studentname;
}
public String getStudentName() {
return this.studentName;
}
}
71
Steps for creating the MyDBHandler class like the Student class and its code can look like this:
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.content.Context;
import android.content.ContentValues;
import android.database.Cursor;
Initialize the Database
The database can be initialized in the constructor of the MyDBHandler class. The code of this
constructor looks like this:
72
CREATE TABLE table_name(
column1 datatype,
column2 datatype,
column3 datatype,
....
);
We need to convert the SQL statement to a string and implement it by using the execSQL()
method of a SQLiteDatabase object. All of these statements will be put inside the onCreate
method of the handler class, as follows:
Load Data
The result of above SQL statement is a table. We use the rawQuery() method of a
SQLiteDatabase object to implement SQL statement and display result via a Cursor object. The
following code will demonstrate the loadHandler method:
73
Add a New Record
To add a new record to the database, we must use the ContentValues object with the put()
method that is used to assign data to ContentsValues object and then use insert() method of
SQLiteDatabase object to insert data to the database. The addHandler method can look like this:
74
19.3 Short Questions:
75
20. Experiment 11 (Beyond Curricula)
AIM: Write a program to design a calling application.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_call);
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.call, menu);
return true;
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
76
// Call a Number
Output:
77
21. Experiment 12 (Beyond Curricula)
a. Source Code:
package
com.example.emailapp;
import android.os.Bundle;
import android.app.Activity;
import
android.content.Intent;
import android.view.Menu;
import android.view.View;
import
android.view.View.OnClickListener;
import android.widget.EditText;
import
android.widget.ImageButton;
import android.widget.Toast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_email);
et1 = (EditText)
findViewById(R.id.editText1); et2 =
(EditText)
findViewById(R.id.editText2); et3 =
(EditText)
findViewById(R.id.editText3);
ib1.setOnClickListener(this);
@Override
public boolean onCreateOptionsMenu(Menu menu) {
78
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.email, menu);
return true;
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
79
22. Experiment 13 (Beyond Curricula)
AIM: Write a program to display the latitude and longitude of a user
Program
MainActivity.java
package com.gpslocationtracker;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import
android.view.MenuItem;
import
android.widget.TextView;
{ TextView textview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (gpsTracker.canGetLocation())
{
String stringLatitude = String.valueOf(gpsTracker.latitude);
textview = (TextView)findViewById(R.id.fieldLatitude);
textview.setText(stringLatitude);
String stringLongitude =
String.valueOf(gpsTracker.longitude); textview =
(TextView)findViewById(R.id.fieldLongitude);
textview.setText(stringLongitude);
}
else
{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
80
gpsTracker.showSettingsAlert();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in
AndroidManifest.xml. int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
a. GPSTracker.java
package com.gpslocationtracker;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder; import
android.provider.Settings; import
android.util.Log;
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
81
}
Location location;
double latitude;
double longitude;
82
if (!isGPSEnabled && !isNetworkEnabled)
{
// no network provider is enabled
}
else
{
this.canGetLocation = true;
83
//First get location from Network Provider if
(isNetworkEnabled)
{
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES,
this);
Log.d("Network", "Network"); if
(locationManager != null)
{
location =
locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
updateGPSCoordinates();
}
}
if (locationManager != null)
{
location =
locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
updateGPSCoordinates();
}
}
}
}
}
catch (Exception e)
{
//e.printStackTrace();
Log.e("Error : Location", "Impossible to connect to LocationManager", e);
84
}
return location;
}
return latitude;
}
return longitude;
}
}
);
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
//On pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
dialog.cancel();
}
});
alertDialog.show();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
86
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
return null;
OUTPUT
87
23. Experiment 14 (Beyond Curricula)
package com.example.multipleactivities;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
bt1.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.first, menu);
return true;
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
88
if(name.equals("") || number.equals("")){
Toast.makeText(this, "Please Enter Values",
Toast.LENGTH_SHORT).show();
}else {
Intent next = new Intent(this, SecondActivity.class);
next.putExtra("NAME", name);
next.putExtra("NUMBER", number);
startActivity(next);
finish();
}
}
}
a. SecondActivity.java
package com.example.multipleactivities;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
bt1.setOnClickListener(this);
bt2.setOnClickListener(this);
89
String number = receive.getStringExtra("NUMBER");
tv1.setText(name);
tv2.setText(number);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.button_main:
Intent main = new Intent(this, FirstActivity.class); startActivity(main);
finish(); break;
case R.id.button_exit:
Toast.makeText(this, "Bye !", Toast.LENGTH_SHORT).show(); finish();
break;
}
}
}
90
91
24. Experiment 15 (Beyond Curricula)
Aim: Write a program to design a contacts application.
a. Source Code:
DatabaseActivity.java
package com.example.contactsapp;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_database);
bt1.setOnClickListener(this);
bt2.setOnClickListener(this);
bt3.setOnClickListener(this);
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
92
getMenuInflater().inflate(R.menu.database, menu);
return true;
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.button_save:
break;
case R.id.button_view:
case R.id.button_exit:
finish();
break;
}
b. DBHelper.java
package com.example.contactsapp;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
93
94 Mobile Computing ETIT 452
public static final String createQuery = "CREATE TABLE " + DB_TABLE + "(" + DB_CNAME + "
TEXT, " + DB_CNUMBER + " TEXT);" ;
context;
private SQLiteDatabase db;
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(createQuery);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Department of Computer Science & Engineering, MAIT
94 Mobile Computing ETIT 452
}
return result;
}
}
c. ViewActivity.java
package com.example.contactsapp;
import android.app.Activity; import
android.content.Intent; import
android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener; import
android.widget.Button;
import android.widget.TextView;
TextView tv;
Button bt1, bt2;
super.onCreate(savedInstanceState); setContentView(R.layout.view_activity);
bt1.setOnClickListener(this);
bt2.setOnClickListener(this);
tv.setText(result);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.button_home:
case R.id.button_exit1:
finish(); break;
}
}
}