You are on page 1of 50

Android Concepts and Programming

TUTORIAL 2

Kartik Sankaran
kar.kbc@gmail.com

CS4222 Wireless and Sensor Networks


[2nd Semester 2013-14]

5th February 2014


Agenda

PART 1: Overview of DTN and Social-Proximity Apps


PART 2: Using the DTN Middleware’s API
- Simple DTN App: BroadcastApp

2
Recap…
Last tutorial –
1. Introduction to Android
2. Installation Steps
(Everyone has a machine? Everyone finished installing?)
3. First Android App with a button + text view

3
Your first Android program
Adding GUI ‘widgets’:
- EditText: User can enter text here
- Button: Pressing it triggers an action
- TextView: Displays some text

1. Enter text here

2. Press the button

3. Text gets appended here

4
Your first Android program
res/layout/main.xml : (add Button and EditText widgets)
<LinearLayout ...>
<EditText android:id="@+id/EditText_Message"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="" /> Widgets have IDs
“@” Referring to a resource
<Button android:id="@+id/Button_Send" “+” Adds this ID to the R class
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Send Message" />
<TextView
android:id="@+id/TextView_Message"
... />
</LinearLayout> GUI layout defined using XML
5
Your first Android program
HelloWorldActivity.java :
public class HelloWorldActivity extends Activity {
/** Called when the activity is first created. */
public void onCreate( Bundle savedInstanceState ) {
...
}

GUI widgets in Java code


// Text View (displays messages)
private TextView textView_Message;
// Edit Text (user enters message here)
private EditText editText_Message;
// Button to trigger an action
private Button button_Send;
}
6
Your first Android program
HelloWorldActivity.java :
public class HelloWorldActivity extends Activity {
/** Called when the activity is first created. */
public void onCreate( Bundle savedInstanceState ) {
...
// Get references to the GUI widgets
textView_Message =
(TextView) findViewById( R.id.TextView_Message );
editText_Message =
(EditText) findViewById( R.id.EditText_Message );
button_Send =
(Button) findViewById( R.id.Button_Send );
}
}
7
Your first Android program
HelloWorldActivity.java :
public void onCreate( Bundle savedInstanceState ) {
...
// Set the button's click listener
button_Send.setOnClickListener(
new View.OnClickListener() {
public void onClick( View v ) {
// Change the text view
String newText = textView_Message.getText() +
"\n New Message: " +
editText_Message.getText();
textView_Message.setText ( newText );
}
} );
} 8
Some explanation of this Java syntax …
Anonymous inner classes:
Tedious way to create listeners
interface OnClickListener {
void onClick();
}
OnClickListener listener =
new OnClickListener() {
class MyListener
public void onClick() {
implements OnClickListener { ===>
// ...
public void onClick() {
}
// ...
};
}
}
MyListener listener; Easier way using
anonymous inner classes

button.setOnClickListener( listener );
9
Overview of DTN and Social-Proximity Apps
Smartphones enable diverse information-sharing applications
Overview of DTN and Social-Proximity Apps
Recently, there is a rise of social-proximity applications:
Users exchange information with others in the vicinity

11
Overview of DTN and Social-Proximity Apps
Recently, there is a rise of social-proximity applications:
Are any of my friends also at
Changi airport now?

Wonder if anyone nearby


wants to chat with me?
12
Overview of DTN and Social-Proximity Apps
Recently, there is a rise of social-proximity applications:

Watching Ice Age 4 in the sitting area

Anyone wants to share a taxi with me?


13
Overview of DTN and Social-Proximity Apps
Problems with existing Social-proximity applications:
Cell tower is overloaded

14
Overview of DTN and Social-Proximity Apps
Problems with existing Social-proximity applications:
Battery power is wasted
Location Privacy Issues

These problems can be avoided:


- No need to always pull information from the internet
- Mobiles are producers of information

15
Overview of DTN and Social-Proximity Apps
One solution: Phone-to-phone communication
But reaches users only one hop away

?
? ?

? ?

16
Understanding what a ‘DTN’ is
Solution: DTN = Delay/Disruptive Tolerant Network
Network with frequent disruption in connectivity,
for example due to mobility of users.

STEVE

ALICE BOB

17
Understanding what a ‘DTN’ is
Note: This is not a MANET!
Information gets spread as people move about: expect delays
(no real-time applications)

STEVE STEVE

Think differently from


normal Socket
programming

ALICE BOB
But you can still connect
to the internet
occasionally
18
Overview of DTN and Social-Proximity Apps
Some examples of Social-Proximity Apps on Google Play:
Application Description Downloads Rating
Badoo Chatting, dating, making 10m+ 4.5
friends with people nearby
Skout Discovering and meeting new 10m+ 4.1
people around
Circles Finding people nearby with 5m+ 4.4
mutual interests
Sonar Connect with friends and like- 1m+ 4.1
minded people nearby

Also, see –
IBEACONS:
http://en.wikipedia.org/wiki/IBeacon
LTE DIRECT:
http://www.qualcomm.com/solutions/wireless-networks/technologies/lte/lte-direct
PROXIMITY-BASED SOCIAL NETWORKING:
http://research.gigaom.com/report/proximity-based-mobile-social-networking-outlook-and-analysis/ 19
Overview of DTN and Social-Proximity Apps
Some examples of Social-Proximity Apps on Google Play:

20
Overview of DTN and Social-Proximity Apps

Last year FYP project: Flitby (de-centralized version of Facebook)

Last year’s CS4222 projects:


http://www.comp.nus.edu.sg/~kartiks/nusdtn/cs4222/project.html

21
Break
DTN Middleware
The framework helps you in –
1. Multi-hop mobile communication
2. Talk with mobiles nearby (one hop away)

http://www.comp.nus.edu.sg/~kartiks/nusdtn/
(username: nusdtn, password: dtnmiddleware)

1. Download the documentation:


http://www.comp.nus.edu.sg/~kartiks/nusdtn/Downloads/MiddlewareDocs.zip
2. Tutorial (covered today):
http://www.comp.nus.edu.sg/~kartiks/nusdtn/Tutorials/tutorial1.html
3. Download binary jars:
http://www.comp.nus.edu.sg/~kartiks/nusdtn/downloads.html
23
Using the framework
Learn by example –
Writing a simple app to broadcast
text messages to other users,
even those multiple hops away.
(BROADCASTAPP)

2. Press the button to


1. Enter message here
broadcast it to everyone

3. Received messages appear here


(What’s that weird number?)

24
Using the framework
- The framework (middleware) runs as a background service
- The framework runs multi-hop protocols
- Your App can use two APIs:
1. FORWARDING LAYER API (for multi-hop communication)
a. Send/Receive messages to/from a particular user
- Possibly large delays, and is not reliable
b. Broadcast messages to all users
2. LINK LAYER API (for single-hop communication)
a. Discover neighboring mobiles
b. Communicate (two-way) with them
For this App,
(See the Javadocs on the website) we use only Broadcast

25
Broadcast App
Download the following 5 library jar files to the ‘libs’ folder:
http://www.comp.nus.edu.sg/~kartiks/nusdtn/downloads.html

Binary jar is used only later on…

26
Broadcast App
BroadcastAppActivity.java :
public void onCreate( Bundle savedInstanceState ) {
... ‘Context’ is used to access
// Start the middleware service Android services
(such as Sensors)
middleware =
new DtnMiddlewareProxy( getApplicationContext() );
middleware.start( new MiddlewareListener() {
public void onMiddlewareEvent( MiddlewareEvent event ) {
// Get the Fwding Layer API...
}
Android services do not start
} ); instantly! You will be notified
} when it has started
private DtnMiddlewareInterface middleware;
private ForwardingLayerInterface fwdLayer;
27
Broadcast App
BroadcastAppActivity.java :
public void onMiddlewareEvent ( MiddlewareEvent event ) {
// Get the fwd layer API
fwdLayer = new ForwardingLayerProxy( middleware );
Use this to get the IMEI
// Get a descriptor for this user number (which is unique)
// Typically, the user enters the username
// But here we simply use IMEI number
TelephonyManager tm = (TelephonyManager)
getSystemService( Context.TELEPHONY_SERVICE );
descriptor = fwdLayer.getDescriptor( "nus.dtn.app.broadcast" ,
Like a socket descriptor in C tm.getDeviceId() );
} (used in sending and receiving)
Tablets may not have IMEI
private Descriptor descriptor;
number!
28
Broadcast App
BroadcastAppActivity.java :
public void onMiddlewareEvent ( MiddlewareEvent event ) {
// ...
// Set the broadcast address
fwdLayer.setBroadcastAddress( "nus.dtn.app.broadcast" ,
"everyone" );
Use anything you
want as broadcast
// Register a listener for received messages address

ChatMessageListener messageListener =
new ChatMessageListener();
fwdLayer.addMessageListener ( descriptor , messageListener );
}

This class is defined later on

29
Broadcast App
BroadcastAppActivity.java :
public void onCreate( Bundle savedInstanceState ) {
// Set the send button's click listener
button_Send.setOnClickListener( new View.OnClickListener() {
public void onClick( View v ) {
Get the text entered by the user
// Construct the DTN message
String chatMessage =
editText_Message.getText().toString();
DtnMessage message = new DtnMessage();
message.addData() // Create data chunk
.writeString( chatMessage ); // Chat message
}
} ); DtnMessage class is explained
} later on
30
Broadcast App
BroadcastAppActivity.java :
public void onCreate( Bundle savedInstanceState ) {
// Set the send button's click listener
button_Send.setOnClickListener( new View.OnClickListener() {
public void onClick( View v ) {
// ...
// Broadcast the message using the fwd layer interface
fwdLayer.sendMessage ( descriptor , // Descriptor you got
message , // Message
"everyone" , // Broadcast Address
null ); // Params (null)
}
} );
}
31
Broadcast App
BroadcastAppActivity.java :
private class ChatMessageListener implements MessageListener {
public void onMessageReceived( String source ,
String destination ,
DtnMessage message ) {
// Read the DTN message
// Data part
message.switchToData();
String chatMessage = message.readString();

...
DtnMessage class is explained
} later on
}

32
Broadcast App
BroadcastAppActivity.java :
private class ChatMessageListener implements MessageListener {
public void onMessageReceived( ... ) {
// Append to the list of messages
final String newText =
textView_Message.getText() + "\n" +
source + " says: " + chatMessage;
// Update the text view in the Main UI thread
handler.post( new Runnable() {
public void run() {
textView_Message.setText ( newText );
}
} );
}
Handlers are explained in next tutorial
} 33
Broadcast App
What is DtnMessage?
- Used to create messages
DtnMessage message = new DtnMessage(); // Empty message
- Each message contains any number of headers/data-chunks/trailers
message.addHeader();
message.addData();
- Each header/data-chunk/trailer can be of any length
- Read/Write basic data types (files too)
message.writeString( "Chat message" );
message.writeInt( 20 );
boolean boolValue = message.readBoolean();

At a given time, you are reading/writing


from/to the header OR data OR trailer
34
Broadcast App
What is DtnMessage?
- You can random access (like files in C)
message.rewind(); // Goto beginning of header/data/trailer
message.seek( 4 , RelativePosition.CURRENT );
// Go 4 bytes ahead
- Switch between reading/writing to header/data/trailer
message.switchToHeader(); // Switch to last added header
message.switchToData(); // Switch to last added data
- You can chain writes together
message.writeString( "Chat message" )
.writeInt( 20 ); // Chain two writes together

35
Broadcast App
What is DtnMessage?
- Make sure you maintain consistency of reads and writes!
// Sender side
DtnMessage message = new DtnMessage();
message.addData()
.writeInt( 20 )
.writeString( "Chat message" );

Oops! Wrong order :-P


// Receiver side
message.switchToData();
String chat = message.readString();
int num = message.readInt();
- Check the Javadocs

36
Broadcast App
These are declared in the AndroidManifest.xml file:
<?xml version="1.0" encoding="utf-8"?>
<manifest ... >
<application android:icon="@drawable/app_icon.png" ... >
<activity android:name="ExampleActivity"
android:label="@string/example_label"
android:screenOrientation="portrait" ... >
</activity>
...
</application> Make sure your App is in
‘Portrait’ mode
<uses-permission
android:name="android.permission.READ_PHONE_STATE" />
</manifest>

You need this permission


to get the IMEI number
37
Running the Broadcast App
Step 1: Install the middleware apk on all phones
- Using command line Downloads page in the
website
$ adb install –r DtnMiddleware-debug.apk
- Using Astro App
a. Transfer the apk file to the phone’s sdcard (just like a USB stick)
b. Settings  Security  Allow installation from unknown sources

c. Navigate to the apk file in Astro, choose it, and install it


http://www.youtube.com/watch?v=9D2Ooh_A898

38
Running the Broadcast App
Step 2: Install the Broadcast App on all phones
- Using command line
$ adb install –r BroadcastApp-debug.apk
- Using your IDE’s Deploy button

39
Running the Broadcast App
Step 3: Choose what Protocols to use
In the DtnComponents/install/ folder of the sdcard:
a. Put the following API binary (deploy) Jar files

b. Put the following Protocol binary (deploy) Jar files

Use AdhocTcpLinkLayer_Deploy.jar Don’t put


for PA2 ‘Source’ jar files!!
40
Running the Broadcast App
Step 3: Choose what Protocols to use
Use the DDMS (Monitor) tool to add/remove jar files:

Button to add files

41
Setting up the Bluetooth Link Layer
- You need Android version 4.0 or later
Otherwise, cannot make a device discoverable for more than 2 min
- Settings  Bluetooth ON  Menu 
Set visibility timeout  Never time out

Bluetooth is
automatically turned ON
and OFF by the protocol

Number of connections
is limited by hardware

Discovery takes place


every 2 minutes

42
Setting up the Adhoc (Hotspot) Link Layer
- You need to create your own secure WiFi hotspot
Don’t use NUS WiFi !!
a. Connectify on Windows
http://www.connectify.me/
b. Google for how to on Mac/Linux
c. Hotspot using your phone
Hotspot protocol will
not start if phone is not
connected to WiFi

You can use Wireshark to


check if packets are sent

UDP can be used for


small data
43
Changing Protocols and Configurations
- You can change the protocols dynamically
(even while your App is running)
- You can change the configuration of a protocol dynamically
Change the config file, and put it in the install folder

Eg: nus.dtn.component.adhoc.udp.AdhocLinkLayerActivator.cfg
# Hello Interval (millisec):
helloInterval=5000
# Down Time (millisec):
downTime=15000
# Port Number:
port=10041
44
Separate your experiments from other groups!
- For Hotspot:
Create your own hotspot (or change to another port number)

- For Bluetooth:
Get your own UUID here:
http://www.famkruithof.net/uuid/uuidgen
Set the UUID in the Bluetooth config file:
# UUID:
uuid=88f8a530-8003-11e2-9e96-0800200c9a66

45
Demo
What if things go wrong??
Use DDMS:
- Don’t get scared by the deluge of Exceptions! (most are harmless)
- Email me/come to the lab COM2-B1-03

Set the log level


to “info”

47
Android Basics

Start learning and coding yourself, don’t wait for me to teach you!

48
Questions?
Thank You!

You might also like