08-networkingx

Download Report

Transcript 08-networkingx

Messaging and Networking
Chap 27. Broadcast Intents1
Chap 23. HTTP & Background Tasks1
Chap 7. WeatherViewer App2
1Bill
Philips, et al., Android Programming: the Big Nerd Ranch
Guide, 2nd edition, Big Nerd Ranch Guides, 2015. Ebook.
2Deitel, et al, Android 6 for Programmers: An App-Driven
Approach, 3rd edition, Prentice Hall, 2015. Ebook.
Objectives
• Send SMS messages using the Messaging app
• Send SMS messages programmatically from within
your app
• Receive and consume incoming SMS messages
=> Understand BroadCastReceiver
• Send e-mail messages from your app
• Connect to the web using HTTP
• Consume Web service
• Write TCP/IP socket-based network apps
2
Outline
• SMS messaging
• Sending messages
• BroadcastReceiver
• Receiving messages
• Sending E-mail messages
• Network programming
3
SMS Messaging
• Can send SMS messages programmatically or using
a built-in Messaging app.
• Can receive feedback after sending SMS messages
• Use PendingIntent
• Use BroadcastReceiver to receive a notification
4
Sending SMS Messages Using
Messaging Apps
• Use an intent to start a built-in messaging app
• Specify the MIME* type “vnd.android-dir/mms-sms”
• Can send to multiple recipients
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
intent.putExtra("address", "1234; 5678; 2345"); // multiple addresses
intent.putExtra("sms_body", "Hello!");
intent.setType("vnd.android-dir/mms-sms"); // MIME type
startActivity(intent);
*MIME: Multipurpose Internet Mail Extensions
5
Sending SMS Programmatically
• Use android.telephony.SmsManager
• Need a SEND_SMS permission in AndroidManifest.xml, e.g.,
<uses-permission android:name="android.permission.SEND_SMS"/>
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(“123-456-7890", null, "Hello!", null, null);
void sendTextMessage(
String destAddress, // phone number
String scAddress, // service center or null for default SMSC
String text,
PendingIntent sentIntent,
PendingIntent deliveryIntent)
sentIntent: broadcast upon message sending
deliveryIntent: broadcast upon message delivery
6
Getting Feedback After Sending
• Can monitor the status of the SMS message
sending process, i.e.,
• Whether the message was sent
• Whether the message was delivered
• Use broadcast pending intents along with callbacks
• PendingIntent: description of an Intent and target action
to perform with it, typically, at later time, e.g., a
broadcast PendingIntent that will perform a broadcast
• BroadcastReceiver: receive intents broadcasted, e.g.,
sent by sendBroadcast()
7
Broadcasting Intents
• A way for activities to communicate with each
other by:
• Broadcasting intents
• Receiving broadcasted intents (using BroadcastReceiver)
Activity 1
broadcastIntent(i)
Intent i
Activity 2
registerBroadcastReceiver(receiver)
8
SMS Sent/Delivery Intents
• Specify broadcast PendingIntent when sending an
SMS message, e.g.,
sms.sendMessage("123-456-7890", null, "Hello",
PendingIntent.getBroadcast(this, 0, new Intent("SMS_SENT"), 0),
PendingIntent.getBroadcast(this, 0, new Intent("SMS_DELIVERED"), 0));
getBroadcast: Retrieve an existing or create a new PendingIntent that will
perform a broadcast, e.g., by calling Context.sendBroadcast().
this: context in which the broadcast is performed
0: private request code --- currently not used
0: flag --- supply additional control information
9
Receiving Sent/Delivery Intents
• Create broadcast receivers and register them
• BroadcastReceiver: class to receive intents
broadcasted across apps
registerReceiver(new BroadcastReceiver() {
/** Called when receiving a broadcast. */
public void onReceive(Context c, Intent i) {
// c: Context in which the receiver is running; i: received intent
switch (getResultCode()) { // result code set by the sender
case Activity.RESULT_OK: ...
case SmsManager.RESULT_ERROR_GENERIC_FAILURE: ...
...
}
}
}, new IntentFilter("SMS_SENT"));
10
registerReceiver(new BroadCastReceiver() {
public void onReceive(Context c, Intent i) {
switch (getResultCode()) {
case Activity.RESULT_OK: ...
case SmsManager.RESULT_CANCELED: ...
}
}
}, new IntentFilter("SMS_DELIVERED"));
11
Outline
SMS Messaging
Sending SMS messages
BroadcastReceiver
• Receiving SMS messages
• Sending E-mail messages
• Network programming
12
Receiving SMS Messages
• Can receive incoming SMS messages from within an
app to perform an action for a certain messages, e.g.,
tracking the location of your (lost/stolen) phone
• Use BroadcastReceiver to listen for incoming messages
In manifest file:
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<application ...>
<receiver android:name=".SmsReceiver">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>
...
</application>
13
// SmsReceiver.java
public class SmsReceiver extends BroadcastReceiver {
public void onReceive(Context ctx, Intent i) {
Bundle bundle = i.getExtras();
if (bundle != null) {
StringBuilder builder = new StringBuilder();
for (Object pdu: (Object[]) bundle.get(“pdus”)) {
SmsMessage msg = SmsMessage.createFromPdu((byte[]) pdu);
builder.append(“From “+ msg.getOriginatingAddress());
builder.append(“ :” + msg.getMessageBody().toString() + “\n”);
}
… builder.toString() …
}
}
To test, use DDMS (Dalvik Debug Monitor Server) Emulator Control
to send a message to the emulator (or use another emulator).
Android Studio: Tools > Android > Android Device Monitor
14
Consuming Messages Completely
• By default, all interested apps will receive messages
• Solution
• Make your receiver handle it first (by setting its priority high)
• Call abortBroadcast() method in your receiver.
In manifest file:
<receiver android:name="SmsReceiver">
<intent-filter android:priority="100">
...
15
Communicating with Activities
• Updating activity from BroadcastReceiver
• Can send received messages to activity
• Use sendBroadcast(Intent) method along with callbacks,
registerReceiver(BroadCastReceiver, IntentFilter) in onResume()
unregisterReceiver(BroadCastReceiver) in onPause()
• Invoking activity from BroadcastReceiver
• Can invoke activity upon receiving messages
Intent i = new Intent(context, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
16
In-Class (Pair)
• Create a simple app that receives all incoming
messages and displays only those messages that
start with a word "URGENT:".
• P1: Write a broadcast receiver listening for incoming
messages and printing them as toast messages.
• P2: Filter incoming messages for the word "URGENT:".
• P3: Invoke an activity to display the filtered messages.
17
Sending Email Messages
• Can launch built-in email application using intent
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setData(Uri.parse("mailto:"));
intent.putExtra(Intent.EXTRA_EMAIL, "[email protected]");
intent.putExtra(Intent.EXTRA_CC, "[email protected]");
intent.putExtra(Intent.EXTRA_SUBJECT, "Android");
intent.putExtra(Intent.EXTRA_TEXT, "Hello from android");
intent.setType("message/rfc822");
startActivity(Intent.createChooser(intent, "Email"));
18
Network Programming
• Same APIs as Java, but no networking operation on UI
threads
• Connecting to the Web (HTTP)
• Can download binary data such as bitmap
• Can download text data
• Consuming Web services (XML and JSON)
• Use Java API for XML such as DOM and SAX
• Use JSON
• JavaScript Object Notation,
• Lightweight data-interchange format (no tags; use bracket and
braces)
• Socket programming (TCP/IP)
19
Making HTTP Connection
• Use URL.openConnection()
URL url = new URL("http://www.cs.utep.edu/cheon/cs4330");
URLConnection conn = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
if (HttpURLConnection.HTTP_OK == httpConn.getResponseCode()) {
InputStream in = httpConn.getInputStream();
... read from in ...
}
20
Review: Socket Programming
• Sockets
• Ends points of two-way communications, i.e., logical connections
between hosts
• Can be used to send and receive data
• Supported by most languages and platforms
• Server vs. client sockets
• Stream (TCP/IP) vs. datagram (UDP/IP) sockets
sockets (end points)
logical connection
21
Server vs. Client Sockets
• Server sockets
• Wait for requests to come in over the network
• Implemented by java.net.ServerSocket class
• Client sockets
• Used to send and receive data
• Can be thought of as a pair of input and output streams
• Implemented by java.net.Socket class
and java.net.DatagramSocket class
22
Server Sockets
• To implement servers
try {
ServerSocket server = new ServerSocket(8000);
while (true) {
Socket incoming = server.accept(); // obtain a client socket
// handle client request by creating a new thread
// and reading from and writing to the socket
// …
}
} catch (IOException e) {
// handle exception on creating a server socket
}
23
Client Sockets
• To send and receive data
• Pair of input and output streams
try {
Socket s = new Socket(“www.cs.utep.edu”, 8000);
PrintWriter out =
new PrintWriter(new OutputStreamWriter(s.getOutputStream()));
BufferedReader in =
new BufferedReader(new InputStreamReader(s.getInputStream()));
… use out and in to send and receive data …
} catch (IOException e) {
// handle exception …
}
24
In-Class (Pair): AndyChat
• Create a simple chat application using TCP/IP
sockets (see handout)
25
In-Class (Pair): Bluetooth API
• Learn the Bluetooth API (for the homework)
• Write an app incrementally to send and receive one
line of text message over Bluetooth
1.
2.
3.
4.
Enable Bluetooth
Discover other devices and pair with them
Query paired devices
Connect devices (RFCOMM protocol)
• Connecting as a server (BluetoothServerSocket)
• Connecting as a client (BluetoothSocket)
5. Send and receive messages
26
1. Checking If Bluetooth Is On
• Create an app consisting of a single button labeled
“Enabled?” to check if Bluetooth is enabled. Toast a
message, say “Bluetooth on” or “Bluetooth off”.
In AndroidManifest.xml file:
<uses-feature
android:name="android.hardware.bluetooth"
android:required="false" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
/** Return true if Bluetooth is supported and enabled. */
private boolean isBluetoothEnabled() {
BluetoothAdapter bt = BluetoothAdapter.getDefaultAdapter();
return bt != null && bt.isEnabled();
}
27
2. Enabling Bluetooth
• Create a button labeled “Enable” to turn on Bluetooth
• Programmatically or
• Invoking the built-in Settings app.
BluetoothAdapter bt = BluetoothAdapter.getDefaultAdapter();
bt.enable();
or
/** Enable Bluetooth by invoking the built-in Settings activity. */
private void enableBluetooth() {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
//intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
28
3. Discovering And Pairing
• Can do programmatically by:
• Setting your device discoverable: intent with action named
BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE
• Discovering other devices: startDiscovery() and
BroadcastReceiver
• Can invoke the built-in Settings app
29
4. Querying Paired Devices
• Create a button labeled “Devices” to show all the paired
devices.
BluetoothAdapter bt = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> devices = bt.getBondedDevices();
for (BluetoothDevice device: devices) {
Log.d("Bluetooth", "paired with " + device.getName());
}
30
5. Connecting Devices
• Create a button labeled “Server” to connect as a server.
• Must be done in a background thread.
final String MY_NAME = "Battleship";
// generate your own UUID with uuidgen or online UUID generator
final UUID MY_UUID
= UUID.fromString("f3019744-096d-4a1e-b1de-53e234e49444");
BluetoothAdapter bt = BluetoothAdapter.getDefaultAdapter();
try {
BluetoothServerSocket serverSocket
= bt.listenUsingRfcommWithServiceRecord(MY_NAME, MY_UUID);
BluetoothSocket socket = serverSocket.accept();
...
socket.close();
serverSocket.close();
} catch (IOException e) {}
31
5. Connecting Devices (Cont.)
• Create a button labeled “Client” to connect as a client.
• Must be done in a background thread.
BluetoothDevice device = /* assign a paired device */;
BluetoothSocket socket = null;
try {
socket = device.createRfcommSocketToServiceRecord(MY_UUID);
socket.connect();
....
socket.close();
} catch (IOException e) {
}
32
6. Sending/Receiving Messages
• Send and receive one line of text.
BluetoothSocket socket = /* created earlier */;
// send a message
PrinterWriter out =
new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
out.println(“Hi from BT”);
out.flush();
// receive a message
BufferedReader in =
new BufferedReader(new InputStreamReader(socket.getInputStream()));
String msg = in.readLine();
…
33