12 2 Android Intents Part 2 InterProcess Communication

  • Slides: 29
Download presentation
12 -2 Android Intents Part 2 Inter-Process Communication Using Bundles Notes are based on:

12 -2 Android Intents Part 2 Inter-Process Communication Using Bundles Notes are based on: Android Developers http: //developer. android. com/index. html

 12. Android – Intents – Part 2 Android intents An activity usually presents

12. Android – Intents – Part 2 Android intents An activity usually presents a single visual user interface from which a number of actions could be performed. Moving from one activity to another is accomplished by having the current activity start the next one through so called intents. Activity-1 start. Activity. For. Result … on. Activity. Result() … Intent {action + data} Activity-2 request. Code request. Result [ optional data ] on. Result() … … 2

 12. Android – Intents – Part 2 IPC Inter-Process Communication Hầu hết các

12. Android – Intents – Part 2 IPC Inter-Process Communication Hầu hết các ngôn ngữ lập trình hỗ trợ khái niệm IPC method-calling (gọi phương thức giữa các tiến trình khác nhau) với các tham số truyền theo hai chiều giữa phương thức gọi (caller) và phương thức bị gọi (callee – invoked method). Ở Android, một activity phát lệnh gọi một activity khác bằng cách sử dụng một đối tượng Intent. Lưu ý: Trong Android, caller không dừng lại đợi activity được gọi trả về kết quả. Thay vào đó, nên dùng một phương thức nghe (listening-method) [on. Activity. Result(. . . ) ]. 3

 12. Android – Intents – Part 2 Android Bundles Thay vì dùng các

12. Android – Intents – Part 2 Android Bundles Thay vì dùng các danh sách tham số/đối số truyền thống, Android dùng cơ chế Intent để xác lập liên lạc giữa các tiến trình (Interprocess-communication - IPC). Để phục vụ mục đích trao đổi dữ liệu, Intent thường mang theo một danh sách các đối số được đặt tên, hay còn gọi là bundle. 4

 12. Android – Intents – Part 2 Android Bundles Cấu trúc Bundle là

12. Android – Intents – Part 2 Android Bundles Cấu trúc Bundle là một cơ chế đơn giản dùng để truyền dữ liệu giữa các activity. Mỗi Bundle là một collection dạng cặp <name, value>. Có một tập các phương thức put. XXX và get. XXX để lưu vào bundle và lấy ra các giá trị (đơn hoặc mảng) thuộc các kiểu dữ liệu cơ bản. Ví dụ Bundle my. Bundle = new Bundle(); my. Bundle. put. Double (“var 1”, 3. 1415); . . . Double v 1 = my. Bundle. get. Double(“var 1”); 5

 12. Android – Intents – Part 2 Android Intents & Bundles Activity 1:

12. Android – Intents – Part 2 Android Intents & Bundles Activity 1: Sender Activity 2: Receiver Intent my. Intent. A 1 A 2 = new Intent (Activity 1. this, Activity 2. class); Bundle my. Bundle 1 = new Bundle(); my. Bundle 1. put. Int (“val 1”, 123); my. Intent. A 1 A 2. put. Extras(my. Bundle 1); start. Activity. For. Result(my. Intent. A 1 A 2, 1122); INTENT Sender class / Receiver class request. Code (1122) result. Code Extras: { val 1 = 123 } 6

 12. Android – Intents – Part 2 Android Intents & Bundles Activity 1:

12. Android – Intents – Part 2 Android Intents & Bundles Activity 1: Sender Activity 2: Receiver Intent my. Local. Intent 2 = get. Intent(); Bundle my. Bundle = my. Local. Intent. get. Extras(); INTENT int val 1 = my. Bundle. get. Int(“val 1"); Sender class / Receiver class request. Code (1122) result. Code Extras: { val 1 = 123 } 7

 12. Android – Intents – Part 2 Android Intents & Bundles Activity 1:

12. Android – Intents – Part 2 Android Intents & Bundles Activity 1: Sender Activity 2: Receiver my. Bundle. put. String("val 1", 456 ); my. Local. Intent. put. Extras(my. Bundle); INTENT set. Result(Activity. RESULT_OK, my. Local. Intent); Sender class / Receiver class request. Code (1122) result. Code (OK) Extras: { val 1 = 456 } 8

 12. Android – Intents – Part 2 Bundle’s methods Available at: http: //developer.

12. Android – Intents – Part 2 Bundle’s methods Available at: http: //developer. android. com/reference/android/os/Bundle. html 9

 12. Android – Intents – Part 2 Tutorial. Activity Exchange Activity 1 lấy

12. Android – Intents – Part 2 Tutorial. Activity Exchange Activity 1 lấy hai giá trị từ UI của nó và gọi Activity 2 tính tổng rồi gửi kết quả lại cho Activity 1. 10

 12. Android – Intents – Part 2 Tutorial. Activity Exchange Step 1. Create

12. Android – Intents – Part 2 Tutorial. Activity Exchange Step 1. Create GUI for Activity 1(main 1. xml) Note. The element android: input. Style indicates the first value could be numeric, with optional decimals and sign. <? xml version="1. 0" encoding="utf-8"? > <Linear. Layout xmlns: android="http: //schemas. android. com/apk/res/android" android: orientation="vertical" android: layout_width="fill_parent" android: layout_height="fill_parent" > <Text. View android: text="Activity 1" android: text. Size="22 sp" android: background="#ff 0000 ff" android: layout_width="fill_parent" android: layout_height="wrap_content" /> <Edit. Text android: hint="Enter first value (a signed double)" android: id="@+id/Edit. Text 01" android: layout_width="fill_parent" android: layout_height="wrap_content" android: input. Type="number. Decimal|number. Signed|number" /> <Edit. Text android: hint="Second value (a positive integer)" android: id="@+id/Edit. Text 02" android: layout_width="fill_parent" android: layout_height="wrap_content" android: input. Type="number" /> <Button android: text="Add Values" android: id="@+id/btn. Add" android: layout_width="wrap_content" android: layout_height="wrap_content" /> <Text. View android: background="#ff 0000 ff" android: text="Sum is. . . " android: text. Size="28 sp" android: id="@+id/Text. View 01" android: layout_width="fill_parent" android: layout_height="wrap_content" /> </Linear. Layout> 11

 12. Android – Intents – Part 2 Tutorial. Activity Exchange Step 2. Create

12. Android – Intents – Part 2 Tutorial. Activity Exchange Step 2. Create GUI for Activity 2(main 2. xml) <? xml version="1. 0" encoding="utf-8"? > <Linear. Layout xmlns: android="http: //schemas. android. com/apk/res/android" android: orientation="vertical" android: layout_width="fill_parent" android: layout_height="fill_parent" android: background="#ff 888888"> <Text. View android: text="Activity 2" android: text. Size="22 sp" android: background="#ff 0000 ff" android: layout_width="fill_parent" android: layout_height="wrap_content" /> <Edit. Text android: text="Data reveived. . . " android: id="@+id/et. Data. Received" android: layout_width="fill_parent" android: layout_height="wrap_content" /> <Button android: text="Done - Callback" android: id="@+id/btn. Done" android: layout_width="wrap_content" android: layout_height="wrap_content" /> </Linear. Layout> 12

 12. Android – Intents – Part 2 Tutorial. Activity Exchange Step 3. Activity

12. Android – Intents – Part 2 Tutorial. Activity Exchange Step 3. Activity 1. Sau khi click button, dữ liệu từ UI được ghi vào một bundle và gửi cho Activity 2. Một listener đang đợi kết quả từ activity được gọi. package cis 493. matos. intents 6; // Activity 1 // get input data from user, call Activity 2, show result import android. app. Activity; import android. content. Intent; import android. os. Bundle; import android. view. View. On. Click. Listener; import android. widget. Button; import android. widget. Edit. Text; import android. widget. Text. View; public class Edit. Text. View Button Activity 1 extends Activity { txt. Val 1; txt. Val 2; lbl. Result; btn. Add; @Override public void on. Create(Bundle saved. Instance. State) { super. on. Create(saved. Instance. State); set. Content. View(R. layout. main 1); txt. Val 1 = (Edit. Text)find. View. By. Id(R. id. Edit. Text 01); txt. Val 2 = (Edit. Text)find. View. By. Id(R. id. Edit. Text 02); lbl. Result = (Text. View) find. View. By. Id(R. id. Text. View 01); btn. Add = (Button) find. View. By. Id(R. id. btn. Add); btn. Add. set. On. Click. Listener(new On. Click. Listener() { @Override public void on. Click(View v) { // get values from the UI Double v 1 = Double. parse. Double(txt. Val 1. get. Text(). to. String()); Double v 2 = Double. parse. Double(txt. Val 2. get. Text(). to. String()); // create intent to call Activity 2 Intent my. Intent. A 1 A 2 = new Intent (Activity 1. this, Activity 2. class); // create a container to ship data Bundle my. Data = new Bundle(); // add <key, value> data items to the container my. Data. put. Double("val 1", v 1); my. Data. put. Double("val 2", v 2); // attach the container to the intent my. Intent. A 1 A 2. put. Extras(my. Data); // call Activity 2, tell your local listener to wait response start. Activity. For. Result(my. Intent. A 1 A 2, 101); }//on. Click }); }//on. Create ////////////////////////////////// / local listener receiving callbacks from other activities @Override protected void on. Activity. Result(int request. Code, int result. Code, Intent data) { super. on. Activity. Result(request. Code, result. Code, data); try{ if ((request. Code == 101 ) && (result. Code == Activity. RESULT_OK)){ Bundle my. Results = data. get. Extras(); Double vresult = my. Results. get. Double("vresult"); lbl. Result. set. Text("Sum is " + vresult); } } catch (Exception e) { lbl. Result. set. Text("Oops! - " + request. Code + " " + result. Code); } }//on. Activity. Result }//Activity 1 13

 12. Android – Intents – Part 2 Tutorial. Activity Exchange Step 4. Activity

12. Android – Intents – Part 2 Tutorial. Activity Exchange Step 4. Activity 2. Được gọi từ Activity 1. Lấy input từ đối tượng bundle gắn với intent. Thực hiện tính toán tại chỗ. Đưa kết quả vào bundle. Trả về OK signal. package cis 493. matos. intents 6; import import android. app. Activity; android. content. Intent; android. os. Bundle; android. view. View. On. Click. Listener; android. widget. Button; android. widget. Edit. Text; public class Activity 2 extends Activity implements On. Click. Listener{ Edit. Text data. Received; Button btn. Done; @Override protected void onsuper. on. Create(saved. Instance. State); set. Content. View(R. layout. main 2); data. Received = (Edit. Text) find. View. By. Id(R. id. et. Data. Received); btn. Done = (Button) find. View. By. Id(R. id. btn. Done); btn. Done. set. On. Click. Listener(this); Create(Bundle saved. Instance. State) { // add to the bundle the computed result my. Bundle. put. Double("vresult", v. Result); // attach updated bumble to invoking intent my. Local. Intent. put. Extras(my. Bundle); // return sending an OK signal to calling activity set. Result(Activity. RESULT_OK, my. Local. Intent); }//on. Create @Override public void on. Click(View v) { // close current screen - terminate Activity 2 finish(); }//on. Click }//Activity 2 // pick call made to Activity 2 via Intent my. Local. Intent = get. Intent(); // look into the bundle sent to Activity 2 for data items Bundle my. Bundle = my. Local. Intent. get. Extras(); Double v 1 = my. Bundle. get. Double("val 1"); Double v 2 = my. Bundle. get. Double("val 2"); // operate on the input data Double v. Result = v 1 + v 2; // for illustration purposes. show data received & result data. Received. set. Text("Data received is n" + "val 1= " + v 1 + "nval 2= " + v 2 + "nnresult= " + v. Result); 14

 12. Android – Intents – Part 2 Tutorial. Activity Exchange Step 5. Update

12. Android – Intents – Part 2 Tutorial. Activity Exchange Step 5. Update manifest của ứng dụng. Thêm thẻ <activity> mới cho “Activity 2“ <? xml version="1. 0" encoding="utf-8"? > <manifest xmlns: android="http: //schemas. android. com/apk/res/android" package="cis 493. matos. intents 6" android: version. Code="1" android: version. Name="1. 0"> <application android: icon="@drawable/icon" android: label="@string/app_name"> <activity android: name=". Activity 1" android: label="@string/app_name"> <intent-filter> <action android: name="android. intent. action. MAIN" /> <category android: name="android. intent. category. LAUNCHER" /> </intent-filter> </activity> <activity android: name=". Activity 2"> </activity> add </application> <uses-sdk android: min. Sdk. Version="4" /> </manifest> 15

 12. Android – Intents – Part 2 Intents This example is similar to

12. Android – Intents – Part 2 Intents This example is similar to previous. You may want to skip it. Example: Activity 1 invokes Activity 2 using an Intent. A bundle containg a set of values is sent back-and-forth between both activities. 16

 12. Android – Intents – Part 2 Intents Example: Activity 1 invokes Activity

12. Android – Intents – Part 2 Intents Example: Activity 1 invokes Activity 2 using an Intent. A bundle conating a set of values is sent back-and-forth between both activities (see 12 Intent. Demo 3. zip). //Activity 1: Invoking a user-defined sub-activity //sending and receiving results from the sub-activity package cis 493. intents; import android. app. Activity; import android. content. Intent; import android. os. Bundle; import android. view. View. On. Click. Listener; import android. widget. *; public class Activity 1 extends Activity { Text. View label 1; Text. View label 1 Returned; Button btn. Call. Activity 2; private final int IPC_ID = 1122; 17

 12. Android – Intents – Part 2 Intents Example: Activity 1 invokes Activity

12. Android – Intents – Part 2 Intents Example: Activity 1 invokes Activity 2 using an Intent. A bundle conating a set of values is sent back-and-forth between both activities. @Override public void on. Create(Bundle saved. Instance. State) { super. on. Create(saved. Instance. State); try { set. Content. View(R. layout. main); label 1 = (Text. View) find. View. By. Id(R. id. label 1); label 1 Returned = (Text. View) find. View. By. Id(R. id. label 1 Returned); btn. Call. Activity 2 = (Button) find. View. By. Id(R. id. btn. Call. Activity 2); btn. Call. Activity 2. set. On. Click. Listener(new Clicker 1()); // for demonstration purposes- show in top label 1. set. Text("Activity 1 (sending. . . ) nn" + "my. String 1: Hello Android" + "n" + "my. Double 1: 3. 141592 " + "n" + "my. Int. Array: {1 2 3} "); } catch (Exception e) { Toast. make. Text(get. Base. Context(), e. get. Message(), Toast. LENGTH_LONG). show(); } }// on. Create 18

 12. Android – Intents – Part 2 Intents Example: Activity 1 invokes Activity

12. Android – Intents – Part 2 Intents Example: Activity 1 invokes Activity 2 using an Intent. A bundle conating a set of values is sent back-and-forth between both activities. private class Clicker 1 implements On. Click. Listener { @Override public void on. Click(View v) { try { // create an Intent to talk to Activity 2 Intent my. Intent. A 1 A 2 = new Intent(Activity 1. this, Activity 2. class); // prepare a Bundle and add the data pieces to be sent Bundle my. Data = new Bundle(); my. Data. put. String("my. String 1", "Hello Android"); my. Data. put. Double("my. Double 1", 3. 141592); int[] my. Little. Array = { 1, 2, 3 }; my. Data. put. Int. Array("my. Int. Array 1", my. Little. Array); // bind the Bundle and the Intent that talks to Activity 2 my. Intent. A 1 A 2. put. Extras(my. Data); // call Activity 2 and wait for results start. Activity. For. Result(my. Intent. A 1 A 2, IPC_ID); } catch (Exception e) { Toast. make. Text(get. Base. Context(), e. get. Message(), Toast. LENGTH_LONG). show(); } }// on. Click }// Clicker 1 19

 12. Android – Intents – Part 2 Intents Example: Activity 1 invokes Activity

12. Android – Intents – Part 2 Intents Example: Activity 1 invokes Activity 2 using an Intent. A bundle conating a set of values is sent back-and-forth between both activities. @Override protected void on. Activity. Result(int request. Code, int result. Code, Intent data) { super. on. Activity. Result(request. Code, result. Code, data); try { switch (request. Code) { case IPC_ID: { //OK. This is the place to process the results sent back from the subactivity //see next slide } else { // user pressed the BACK button label 1. set. Text("Selection CANCELLED!"); }// if break; }// case }// switch } catch (Exception e) { Toast. make. Text(get. Base. Context(), e. get. Message(), Toast. LENGTH_LONG). show(); }// try }// on. Activity. Result }// Andro. Intent 1 20

 12. Android – Intents – Part 2 Intents Example: Activity 1 invokes Activity

12. Android – Intents – Part 2 Intents Example: Activity 1 invokes Activity 2 using an Intent. A bundle conating a set of values is sent back-and-forth between both activities. @Override protected void on. Activity. Result(int request. Code, int result. Code, Intent data) { super. on. Activity. Result(request. Code, result. Code, data); try { switch (request. Code) { case IPC_ID: { //OK. This is the place to process the results sent back from the sub-activity //see next slide } else { // user pressed the BACK button label 1. set. Text("Selection CANCELLED!"); }// if break; }// case }// switch } catch (Exception e) { Toast. make. Text(get. Base. Context(), e. get. Message(), Toast. LENGTH_LONG). show(); }// try }// on. Activity. Result }// Andro. Intent 1 21

 12. Android – Intents – Part 2 Intents Example: Activity 1 invokes Activity

12. Android – Intents – Part 2 Intents Example: Activity 1 invokes Activity 2 using an Intent. A bundle conating a set of values is sent back-and-forth between both activities. // Activity 2 is over - see what happened if (result. Code == Activity. RESULT_OK) { // good! - we have some data sent back from Activity 2 Bundle my. Returned. Data = data. get. Extras(); String my. Returned. String 1 = my. Returned. Data. get. String("my. Returned. String 1"); Double my. Returned. Double 1 = my. Returned. Data. get. Double("my. Returned. Double 1"); String my. Returned. String 2 = my. Returned. Data. get. String("my. Current. Time"); } // display in the bottom label 1 Returned. set. Text(my. Returned. String 1 + "n" + Double. to. String(my. Returned. Double 1) + "n" + my. Returned. String 2); 22

 12. Android – Intents – Part 2 Intents Example: Activity 1 invokes Activity

12. Android – Intents – Part 2 Intents Example: Activity 1 invokes Activity 2 using an Intent. A bundle conating a set of values is sent back-and-forth between both activities. // Activity 2. This subactivity receives a bundle of data, performs some work on the data and, // returns results to Activity 1. package cis 493. intents; import java. util. Date; import android. app. Activity; import android. content. Intent; import android. os. Bundle; import android. view. View. On. Click. Listener; import android. widget. *; public class Activity 2 extends Activity { Text. View label 2; Button btn. Call. Activity 1; 23

 12. Android – Intents – Part 2 Intents Example: Activity 1 invokes Activity

12. Android – Intents – Part 2 Intents Example: Activity 1 invokes Activity 2 using an Intent. A bundle conating a set of values is sent back-and-forth between both activities. // Activity 2 – cont… @Override public void on. Create(Bundle saved. Instance. State) { super. on. Create(saved. Instance. State); set. Content. View(R. layout. main 2); //bind UI variables to Java code label 2 = (Text. View)find. View. By. Id(R. id. label 2); btn. Call. Activity 1 = (Button)find. View. By. Id(R. id. btn. Call. Activity 1); btn. Call. Activity 1. set. On. Click. Listener(new Clicker 1()); //create a local Intent handler – we have been called! Intent my. Local. Intent = get. Intent(); //grab the data package with all the pieces sent to us Bundle my. Bundle = my. Local. Intent. get. Extras(); //extract the individual data parts of the bundle String str 1 = my. Bundle. get. String("my. String 1"); double dob 1 = my. Bundle. get. Double("my. Double 1"); int[] arr 1 = my. Bundle. get. Int. Array("my. Int. Array 1"); 24

 12. Android – Intents – Part 2 Intents Example: Activity 1 invokes Activity

12. Android – Intents – Part 2 Intents Example: Activity 1 invokes Activity 2 using an Intent. A bundle conating a set of values is sent back-and-forth between both activities. //Activity 2 – cont… //do something with the data here (for example. . . ) String str. Arr = "{ "; int sum. Int. Values = 0; for (int i=0; i<arr 1. length; i++) { sum. Int. Values += arr 1[i]; str. Arr += Integer. to. String( arr 1[i] ) + " "; } str. Arr += " }"; //show arriving data in GUI label 2. set. Text("Activity 2 (receiving. . . ) nn" + "my. String 1: " + str 1 + "n" + "my. Double 1: " + Double. to. String(dob 1) + "n" + "my. Int. Array 1: " + str. Arr); //now go back to my. Activity 1 with some data made here double some. Number = sum. Int. Values + dob 1; my. Bundle. put. String("my. Returned. String 1", "Adios Android"); my. Bundle. put. Double("my. Returned. Double 1", some. Number); my. Bundle. put. String("my. Current. Time", new Date(). to. Locale. String() ); my. Local. Intent. put. Extras(my. Bundle); set. Result(Activity. RESULT_OK, my. Local. Intent); }//on. Create()); 25

 12. Android – Intents – Part 2 Intents Example: Activity 1 invokes Activity

12. Android – Intents – Part 2 Intents Example: Activity 1 invokes Activity 2 using an Intent. A bundle conating a set of values is sent back-and-forth between both activities. Layout main. xml <? xml version="1. 0" encoding="utf-8"? > <Linear. Layout android: id="@+id/lin. Layout" android: layout_width="fill_parent" android: layout_height="fill_parent" android: background="#ffccffff" android: orientation="vertical" xmlns: android="http: //schemas. android. com/apk/res/android" > <Text. View android: id="@+id/caption 1" android: layout_width="fill_parent" android: layout_height="wrap_content" android: background="#ffff 3300" android: padding="4 sp" android: text=" Activity 1 " android: text. Size="20 px" android: text. Style="bold" android: text. Color="#ff 000000" > </Text. View> <Text. View android: id="@+id/widget 107" android: layout_width="fill_parent" android: layout_height="2 sp" > </Text. View> <Text. View android: id="@+id/label 1" android: layout_width="fill_parent" android: layout_height="wrap_content" android: background="#ff 0033 cc" android: text="Data to be sent to Sub. Activity: " android: text. Style="bold" > </Text. View> <Button android: id="@+id/btn. Call. Activity 2" android: layout_width="149 px" android: layout_height="wrap_content" android: padding="6 sp" android: text="Call Activity 2" android: text. Style="bold" > </Button> <Text. View android: id="@+id/label 1 Returned" android: layout_width="fill_parent" android: layout_height="wrap_content" android: background="#ff 0033 cc" android: text=" Data returned by Activity 2" android: text. Style="bold" > </Text. View> </Linear. Layout> 26

 12. Android – Intents – Part 2 Intents Example: Activity 1 invokes Activity

12. Android – Intents – Part 2 Intents Example: Activity 1 invokes Activity 2 using an Intent. A bundle conating a set of values is sent back-and-forth between both activities. Layout main 2. xml <? xml version="1. 0" encoding="utf-8"? > <Linear. Layout android: id="@+id/linear. Layout" android: layout_width="fill_parent" android: layout_height="fill_parent" android: background="#ffffffcc" android: orientation="vertical" xmlns: android="http: //schemas. android. com/apk/res/android" > <Text. View android: layout_width="fill_parent" android: layout_height="wrap_content" android: background="#ffff 9900" android: padding="4 sp" android: text=" Activity 2" android: text. Size="20 px" android: text. Style="bold" > </Text. View> <Text. View android: id="@+id/widget 107" android: layout_width="fill_parent" android: layout_height="2 sp" > </Text. View> <Text. View android: id="@+id/label 2" android: layout_width="fill_parent" android: layout_height="wrap_content" android: background="#ff 0033 cc" android: text="Data Received from Activity 1. . . " android: text. Style="bold" > </Text. View> <Button android: id="@+id/btn. Call. Activity 1" android: layout_width="149 px" android: layout_height="wrap_content" android: padding="6 sp" android: text="Call. Back Activity 1" android: text. Style="bold" > </Button> </Linear. Layout> 27

 12. Android – Intents Questions ? 28

12. Android – Intents Questions ? 28

Bài tập về nhà/Lab 04 • Tạo 1 ứng dụng kết hợp các activity

Bài tập về nhà/Lab 04 • Tạo 1 ứng dụng kết hợp các activity đã tạo từ các bài tập tuần trước (Lab 03, lab 02) ứng dụng này có 2 nút bấm (hoặc menu) , một cho phép chạy activity chính của lab 02, một cho phép chạy activity chính của lab 03. • Hạn nộp: hỏi thầy thực hành.