Presentation is loading. Please wait.

Presentation is loading. Please wait.

Messaging and Networking. Objectives Send SMS messages using the Messaging app Send SMS messages programmatically from within your app Receive and consume.

Similar presentations


Presentation on theme: "Messaging and Networking. Objectives Send SMS messages using the Messaging app Send SMS messages programmatically from within your app Receive and consume."— Presentation transcript:

1 Messaging and Networking

2 Objectives Send SMS messages using the Messaging app Send SMS messages programmatically from within your app Receive and consume incoming SMS messages Send e-mail messages from your app Connect to the web using HTTP Consume Web service Write TCP/IP socket-based network apps 2

3 Outline SMS messaging Sending messages BroadcastReceiver Receiving messages Sending E-mail messages Network programming 3

4 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

5 Sending SMS Messages Using Messaging Apps Use an intent to start a built-in messaging app Specify the MIME (Multipurpose Internet Media Extension) type “vnd.android-dir/mms-sms” Can send to multiple recipients 5 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);

6 Sending SMS Programmatically Use android.telephony.SmsManager Need a SEND_SMS permission in AndroidManifest.xml, e.g., 6 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

7 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

8 Broadcasting Intents A way for activities to communicate with each other by: Broadcasting intents Receiving broadcasted intents (using BroadcastReceiver) 8 Activity 1 Activity 2 Intent i broadcastIntent(i) registerBroadcastReceiver(receiver)

9 SMS Sent/Delivery Intents 9 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 Specify broadcast PendingIntent when sending an SMS message, e.g.,

10 Receiving Sent/Delivery Intents 10 registerReceiver(new BroadcastReceiver() { public void onReceive(Context c, Intent i) { // c: Context in which the receiver is running switch (getResultCode()) { case Activity.RESULT_OK:... case SmsManager.RESULT_ERROR_GENERIC_FAILURE:...... } }, new IntentFilter("SMS_SENT")); Create broadcast receivers and register them BroadcastReceiver: class to receive intents broadcasted across apps

11 11 registerReceiver(new BroadCastReceiver() { public void onReceive(Context c, Intent i) { switch (getResultCode()) { case Activity.RESULT_OK:... case SmsManager.RESULT_CANCELED:... } }, new IntentFilter("SMS_DELIVERED"));

12 Outline SMS Messaging Sending SMS messages BroadcastReceiver Receiving SMS messages Sending E-mail messages Network programming 12

13 Receiving SMS Messages 13 In manifest file:... 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

14 14 // 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

15 Consuming Messages Completely 15 In manifest file:... 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.

16 Communicating with Activities 16 Intent i = new Intent(context, MainActivity.class); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(i); 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 BroadcastReceive Can invoke activity upon receiving messages

17 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

18 Sending Email Messages 18 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, "xxxx@utep.edu"); intent.putExtra(Intent.EXTRA_CC, "xxxx@utep.edu"); intent.putExtra(Intent.EXTRA_SUBJECT, "Android"); intent.putExtra(Intent.EXTRA_TEXT, "Hello from android"); intent.setType("message/rfc822"); startActivity(Intent.createChooser(intent, "Email"));

19 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

20 Making HTTP Connection 20 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... }

21 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 21 logical connection sockets (end points)

22 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

23 Server Sockets 23 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 }

24 Client Sockets 24 To send and receive data Pair of input and output streams try { Socket s = new Socket(“www.cs.utep.edu”, 80); 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 … }

25 In-Class (Pair) Create a simple chat application using TCP/IP sockets (see handout) 25


Download ppt "Messaging and Networking. Objectives Send SMS messages using the Messaging app Send SMS messages programmatically from within your app Receive and consume."

Similar presentations


Ads by Google