Android Networking - and - Connectivity
Android Networking - and - Connectivity
Networking
and
Connec1vity
CTT06209
Android
and
Networking
• Smartphones
in
general
and
Android
in
par1cular
provide
several
means
of
being
connected
– Telephony
connec1ons
for
voice
communica1on,
the
primary
use
of
the
smartphone
– Support
for
SMS
services
– Connec1vity
to
networks
and
Internet
through
WiFi
and
UMTS/GPRS
– Bluetooth
connec1vity
to
devices
and
peer-‐to-‐peer
connec1ons
among
smartphones
• Let
us
review
each
of
these
connec1vity
features
briefly
Networking 2
Android
Telephony
• Basic
access
to
informa1on
about
the
telephony
services
available
on
the
device
is
obtained
through
the
TelephonyManager
class
telManager
=
(TelephonyManager)
getSystemService(TELEPHONY_SERVICE);
– Use
the
methods
of
this
class
to
determine
telephony
services
and
states:
getDeviceID(),
getLine1Number(),
getNetworkOperator()
etc.
– Register
listener
to
receive
no1fica1on
of
telephony
state
changes
using
the
listen()
method
– [Link](newTelListener(),
PhoneStateListener.LISTEN_CALL_STATE);
Networking 3
Android
SMS
• Full
access
to
SMS
func1onality
using
the
SMSManager
class
• Need
to
set
permission
in
the
Manifest
file:
<uses-‐permission
android:name=“[Link].SEND_SMS”
/>
• Get
an
instance
of
the
SMS
manager:
SmsManager
mySMS
=
[Link]();
• Sending
SMS
messages
String
dest
=
“12345678”;
//
des1na1on
tel
number
String
mess
=
“Hello,
SMS!”
//
message
[Link](dest,
null,
mess,
null,
null);
• Can
create
interes1ng
applica1ons
to
respond
to
received
SMS
and
auto
respond
Networking 4
Android
Connec1vity
• Android
provides
the
Connec1vityManager
class
to
monitor
network
connec1vity
state,
sehng
preferred
network
connec1ons
and
managing
connec1vity
failover
• Get
access
to
the
Connec1vityManager
by:
Connec1vityManager
myNetMan
=
(Connec1vityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
• Set
permission
in
the
Manifest
file:
<uses-‐permission
android:name=“[Link].ACCESS_NETWORK_STATE”
/>
• Connec1vity
Manager
provides
methods
like
getNetworkInfo(),
getAc1veNetworkInfo(),
and
getAllNetworkInfo()
etc.
– These
methods
return
the
NetworkInfo
object
– Can
use
methods
within
this
object
like
isAvailable(),
isConnected,
isConnectedorConnec1ng(),
getState(),
etc.
Networking 5
Android
Connec1vity
• If
you
are
using
the
network
access
in
your
applica1on,
it
is
always
a
good
idea
to
check
if
the
network
connec1vity
exists,
and
take
ac1on
accordingly
• Example
public
boolean
isOnline()
{
Connec1vityManager
cm
=
(Connec1vityManager)
getSystemService
(Context.CONNECTIVITY_SERVICE);
return
cm.getAc1veNetworkInfo().isConnectedOrConnec1ng();
}
Networking 6
Android
WiFi
• WiFi
connec1vity
service
provided
through
the
WiFi
manager:
WifiManager
wifi
=
(WifiManager)
getSystemService(Context.WIFI_SERVICE);
• Permissions
to
be
set
in
Manifest
file:
<uses-‐permission
android:name="[Link].ACCESS_WIFI_STATE"/
>
<uses-‐permission
android:name="[Link].CHANGE_WIFI_STATE"/>
• Enabling
WiFi:
if
(!wifi.isWifiEnabledf))
if
(wifi.getWifiState()
!=
WifiManager.WIFI_STATE_ENABLING)
wifi.setwifiEnabled(true);
• WiFi
Manager
provides
means
for
scanning
for
hotspots,
crea1ng
and
managing
WiFI
network
configura1ons
Networking 7
Bluetooth/IEEE
802.15
• Widely
used
connec1on
technology
for
short-‐range
communica1on
(~
10-‐100
m)
S
P
Networking 8
Android
and
Bluetooth
• Support
for
the
Bluetooth
network
stack
• Bluetooth
APIs
allow
applica1ons
to:
– Scan
for
other
Bluetooth
devices
– Query
the
local
Bluetooth
adapter
for
paired
Bluetooth
devices
– Establish
RFCOMM
channels
– Connect
to
other
devices
through
service
discovery
– Transfer
data
to
and
from
other
devices
– Manage
mul1ple
connec1ons
• Supported
through
the
[Link]
package
• Need
to
set
permissions
in
Manifest
file
<uses-‐permission
android:name=“[Link]”
/>
<uses-‐permission
android:name=“[Link].BLUETOOTH_ADMIN”
/>
• Larer
needed
if
we
need
to
manipulate
Bluetooth
sehngs
or
ini1ate
device
discovery
Networking 9
Android
and
Bluetooth
• Four
main
classes
in
the
[Link]
package
– BluetoothAdapter:
represents
the
local
bluetooth
adapter;
used
to
discover
and
instan1ate
devices
and
create
BluetoothServerSocket
– BluetoothDevice:
represents
the
remote
Bluetooth
device;
use
BluetoothSocket
to
ini1ate
connec1on
to
remote
device
– BluetoothSocket:
represents
the
interface
for
a
Bluetooth
socket;
connec1on
point
allowing
data
exchange
with
another
device
– BluetoothServerSocket:
represents
an
open
server
socket
to
listen
for
incoming
connec1on
requests.
One
device
needs
to
open
a
server
socket
for
communica1on
– BluetoothClass:
describes
the
general
characteris1cs
and
capabili1es
of
a
Bluetooth
device
Networking 10
Android
and
Bluetooth
• To
turn
on
Bluetooth
connec1vity
on
your
device:
BluetoothAdapter
mBluetoothAdapter
=[Link]();
if
(mBluetoothAdapter
==
null)
{
//
Device
does
not
support
Bluetooth
}
• Then
enable
Bluetooth:
if
(![Link]())
{
Intent
enableBtIntent
=
new
Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startAc1vityForResult(enableBtIntent,
REQUEST_ENABLE_BT);
}
Networking 11
Android
and
Bluetooth
• Finding
Bluetooth
devices:
Use
the
BluetoothAdapter
class
– Device
discovery:
scan
the
local
area
for
Bluetooth
enabled
devices,
use
the
startDiscovery()
method
• Returns
immediately
indica1ng
whether
discovery
started
successfully
• Discovery
process
takes
a
while:
inquiry
scan
of
about
12
sec
followed
by
page
scan
of
each
found
device
– Register
a
BroadcastReceiver
for
the
ACTION_FOUND
Intent
to
receive
informa1on
about
each
device
discovered
Networking 12
Android
and
Bluetooth
//
Create
a
BroadcastReceiver
for
ACTION_FOUND
private
final
BroadcastReceiver
mReceiver
=
new
BroadcastReceiver()
{
public
void
onReceive(Context
context,
Intent
intent)
{
String
ac1on
=
intent.getAc1on();
//
When
discovery
finds
a
device
if
(BluetoothDevice.ACTION_FOUND.equals(ac1on))
{
//
Get
the
BluetoothDevice
object
from
the
Intent
BluetoothDevice
device
=
[Link](BluetoothDevice.EXTRA_DEVICE);
//
Add
the
name
and
address
to
an
array
adapter
to
show
in
a
ListView
[Link]([Link]()
+
"\n"
+
[Link]());
}
}
};
//
Register
the
BroadcastReceiver
IntentFilter
filter
=
new
IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver,
filter);
//
Don't
forget
to
unregister
during
onDestroy
Networking 13
Android
and
Bluetooth
• Allowing
your
device
to
be
discovered
Intent
discoverableIntent
=
new
Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
[Link](BluetoothAdapter.EXTRA_DISCOVERABLE_D
URATION,
300);
startAc1vity(discoverableIntent);
– Required
to
make
your
device
discoverable
if
you
are
hos1ng
the
server
– Not
needed
if
you
are
ini1a1ng
a
connec1on
Networking 14
Android
and
Bluetooth
• Querying
paired
devices
Set<BluetoothDevice>
pairedDevices
=
[Link]();
//
If
there
are
paired
devices
if
([Link]()
>
0)
{
//
Loop
through
paired
devices
for
(BluetoothDevice
device
:
pairedDevices)
{
//
Add
the
name
and
address
to
an
array
adapter
to
show
in
a
ListView
[Link]([Link]()
+
"\n"
+
[Link]());
}
}
Networking 15
Android
and
Bluetooth
• If
you
are
implemen1ng
an
applica1on
with
Bluetooth
for
communica1on,
you
have
to
implement
both
the
server-‐side
and
client-‐side
mechanisms
– Server
side
opens
a
listening
socket
– Client
side
must
ini1ate
the
connec1on
to
the
server
– Connec1on
established
if
both
server
and
client
have
a
connected
BluetoothSocket
on
the
same
RFCOMM
channel
– Familiar
socket
programming
approach
– Client
will
receive
the
socket
when
it
opens
an
RFCOMMchannel
to
the
server
– Server
will
receive
a
socket
when
an
incoming
connec1on
is
accepted
• Pairing
may
be
ini1ated
if
the
two
devices
have
not
been
previously
paired
Networking 16
Android
and
Bluetooth
• Server
side
setup:
1. Get
a
BluetoothServerSocket
2. Start
listening
for
connec1on
requests
by
calling
accept()
• Accept()
is
a
blocking
call.
Do
not
do
it
in
the
UI
thread
3. Call
close()
if
you
wish
to
accept
no
more
addi1onal
connec1ons
• Client
side
setup:
1. Using
the
BluetoothDevice,
get
a
BluetoothSocket
2. Ini1ate
the
connec1on
by
calling
connect()
Networking 17
Android
and
Bluetooth
private
class
AcceptThread
extends
Thread
{
public
void
run()
{
private
final
BluetoothServerSocket
mmServerSocket;
BluetoothSocket
socket
=
null;
//
Keep
listening
un1l
excep1on
occurs
or
a
socket
is
public
AcceptThread()
{
returned
//
Use
a
temporary
object
that
is
later
assigned
to
while
(true)
{
mmServerSocket,
try
{
//
because
mmServerSocket
is
final
socket
=
[Link]();
BluetoothServerSocket
tmp
=
null;
}
catch
(IOExcep1on
e)
{
try
{
break;
//
MY_UUID
is
the
app's
UUID
string,
also
used
by
}
the
client
code
//
If
a
connec1on
was
accepted
tmp
=
if
(socket
!=
null)
{
[Link]
(NAME,
MY_UUID);
//
Do
work
to
manage
the
connec1on
(in
a
separate
thread)
}
catch
(IOExcep1on
e)
{
}
manageConnectedSocket(socket);
mmServerSocket
=
tmp;
[Link]();
}
break;
}
}
}
/**
Will
cancel
the
listening
socket,
and
cause
the
thread
to
finish
*/
public
void
cancel()
{
try
{
[Link]();
}
catch
(IOExcep1on
e)
{
}
}
}
Networking 18
Android
and
Bluetooth
private
class
ConnectThread
extends
Thread
{
public
void
run()
{
private
final
BluetoothSocket
mmSocket;
//
Cancel
discovery
because
it
will
slow
down
the
connec1on
private
final
BluetoothDevice
mmDevice;
[Link]();
public
ConnectThread(BluetoothDevice
device)
{
try
{
//
Use
a
temporary
object
that
is
later
assigned
to
mmSocket,
//
Connect
the
device
through
the
socket.
This
will
block
//
because
mmSocket
is
final
//
un1l
it
succeeds
or
throws
an
excep1on
BluetoothSocket
tmp
=
null;
[Link]();
mmDevice
=
device;
}
catch
(IOExcep1on
connectExcep1on)
{
//
Unable
to
connect;
close
the
socket
and
get
out
//
Get
a
BluetoothSocket
to
connect
with
the
given
try
{
BluetoothDevice
[Link]();
try
{
}
catch
(IOExcep1on
closeExcep1on)
{
}
//
MY_UUID
is
the
app's
UUID
string,
also
used
by
the
server
return;
code
}
tmp
=
[Link](MY_UUID);
//
Do
work
to
manage
the
connec1on
(in
a
separate
thread)
}
catch
(IOExcep1on
e)
{
}
manageConnectedSocket(mmSocket);
mmSocket
=
tmp;
}
}
/**
Will
cancel
an
in-‐progress
connec1on,
and
close
the
socket
*/
public
void
cancel()
{
try
{
[Link]();
}
catch
(IOExcep1on
e)
{
}
}
}
Networking 19
Android
and
Bluetooth
• Once
connec1on
established:
1. Get
the
InputStream
and
OutputStream
that
handle
transmissions
through
the
soclet,
via
getInputStream()
and
getOutputStream()
2. Read
and
write
data
to
the
streams
with
read(byte[])
and
write(byte[])
Networking 20
Android
and
Bluetooth
private
class
ConnectedThread
extends
Thread
{
public
void
run()
{
private
final
BluetoothSocket
mmSocket;
byte[]
buffer
=
new
byte[1024];
//
buffer
store
for
the
stream
private
final
InputStream
mmInStream;
int
bytes;
//
bytes
returned
from
read()
private
final
OutputStream
mmOutStream;
//
Keep
listening
to
the
InputStream
un1l
an
excep1on
occurs
public
ConnectedThread(BluetoothSocket
socket)
{
while
(true)
{
mmSocket
=
socket;
try
{
InputStream
tmpIn
=
null;
//
Read
from
the
InputStream
OutputStream
tmpOut
=
null;
bytes
=
[Link](buffer);
//
Send
the
obtained
bytes
to
the
UI
Ac1vity
//
Get
the
input
and
output
streams,
using
temp
objects
because
[Link](MESSAGE_READ,
bytes,
-‐1,
buffer)
//
member
streams
are
final
.sendToTarget();
try
{
}
catch
(IOExcep1on
e)
{
tmpIn
=
[Link]();
break;
tmpOut
=
[Link]();
}
}
catch
(IOExcep1on
e)
{
}
}
}
mmInStream
=
tmpIn;
mmOutStream
=
tmpOut;
/*
Call
this
from
the
main
Ac1vity
to
send
data
to
the
remote
device
*/
}
public
void
write(byte[]
bytes)
{
try
{
[Link](bytes);
}
catch
(IOExcep1on
e)
{
}
}
/*
Call
this
from
the
main
Ac1vity
to
shutdown
the
connec1on
*/
public
void
cancel()
{
try
{
[Link]();
}
catch
(IOExcep1on
e)
{
}
}
}
Networking 21
Android
and
HTTP
• Android
has
Apache
HTTP
components
library
built
into
the
framework
– HrpClient
component
enables
handling
of
HTTP
requests
on
your
behalf,
issuing
HTTP
requests
and
dealing
with
the
response
– You
can
layer
a
SOAP/XML-‐RPC
layer
atop
this
library
or
use
it
"straight"
for
accessing
REST-‐style
web
services
• Android
also
includes
three
parsers
for
XML
and
a
parser
for
JSON
– the
tradi1onal
W3C
DOM
parser
([Link]),
a
SAX
parser
([Link]),
and
the
XML
pull
parser
– JSON
parser
([Link])
• Also
consider
the
use
of
third-‐party
libraries
to
deal
with
specific
formats
like
RSS/Atom
parser
Networking 22
Android
and
HTTP
• Simple
usage
example
of
HTTPGet():
HrpClient
client
=
new
DefaultHrpClient();
HrpGet
request
=
new
HrpGet();
[Link](new
URI("hrp://[Link]/"));
HrpResponse
response
=
[Link](request);
in
=
new
BufferedReader
(new
InputStreamReader(response.getEn1ty().getContent()));
Networking 23
Android
and
HTTP
• Simple
usage
of
HTTP
Post:
HrpClient
hrpclient
=
new
DefaultHrpClient();
HrpPost
hrppost
=
new
HrpPost(url);
if
(kvPairs
!=
null
&&
[Link]()
==
false)
{
List<NameValuePair>
nameValuePairs
=
new
ArrayList<NameValuePair>([Link]());
String
k,
v;
Iterator<String>
itKeys
=
[Link]().iterator();
while
([Link]())
{
k
=
[Link]();
v
=
[Link](k);
[Link](new
BasicNameValuePair(k,
v));
}
hrppost.setEn1ty(new
UrlEncodedFormEn1ty(nameValuePairs));
}
HrpResponse
response;
response
=
[Link](hrppost);
Networking 24