Bài giảng Android - Bài 4: Intent & Service

pdf 98 trang phuongnguyen 1350
Bạn đang xem 20 trang mẫu của tài liệu "Bài giảng Android - Bài 4: Intent & Service", để tải tài liệu gốc về máy bạn click vào nút DOWNLOAD ở trên

Tài liệu đính kèm:

  • pdfbai_giang_android_bai_4_intent_service.pdf

Nội dung text: Bài giảng Android - Bài 4: Intent & Service

  1. Intent & Service
  2. 12. Android – Intents Intents Android Activities Một chương trình android có thể có nhiều activity. • Một activity dùng phương thức setContentView( ) để thiết lập giao diện tương tác người dùng. • Các activity độc lập, nhưng chúng có thể cộng tác với nhau nhằm hoàn thành 1 chức năng nào đó, và giao tiếp với nhau. • Điền hình mỗi ứng dụng có 1 activity là chính (main) activity này được gọi khi chương trình khởi tạo. • Khi một activity này chuyển sang một activity khác thì yêu cầu phải thực hiện một intent. • Các activity tương tác với nhau thông qua chế độ bất đồng bộ. 3 3
  3. 12. Android – Intents Intents Android Activities Android Application Main Activity results intents Sub-Activity-1 Sub-Activity-n extras 4 4
  4. 12. Android – Intents Intents Taken from: Intents are invoked using the following options startActivity (intent) Gọi 1 activity sendBroadcast (intent) Gửi đến các BroadcastReceiver liên quan startService(intent) Giao tiếp với các dịch vụ nền. or bindService(intent, ) 5 5
  5. 12. Android – Intents Intents Taken from: 2 tham số chính của Intent: 1. Action một số được xây dựng sẵn, như là ACTION_VIEW, ACTION_EDIT, ACTION_MAIN, hoặc user-created-activity 2. Data Dữ liệu cho các hoạt động như là số điện thoại để gọi (được biểu diễn như là Uri). Intent: { action + data } Activity- Activity- 1 2 Optional results 6 6
  6. 12. Android – Intents Intents Taken from: Ví dụ 1 intent được sử dụng như sau: Intent myActivity = new Intent (action, data); startActivity (myActivity); Primary data (as an URI) tel:// http:// Built-in sendto:// or user-created activity 7 7
  7. 12. Android – Intents Intents Taken from: Ví dụ các cặp action/data : ACTION_DIAL tel:123 Display the phone dialer with the given number filled in. ACTION_VIEW Show Google page in a browser view. Note how the VIEW action does what is considered the most reasonable thing for a particular URI. ACTION_EDIT content://contacts/people/2 Edit information about the person whose identifier is "2". ACTION_VIEW content://contacts/people/2 Used to start an activity to display 2-nd person. ACTION_VIEW content://contacts/ people/ Display a list of people, which the user can browse through. Selecting a particular person to view would result in a new intent 8 8
  8. 12. Android – Intents Intents Built-in Standard Actions Danh sách các action được android xây dựng sẵn (usually through startActivity(Intent). ACTION_MAIN ACTION_ANSWER ACTION_VIEW ACTION_INSERT ACTION_ATTACH_DATA ACTION_DELETE ACTION_EDIT ACTION_RUN ACTION_PICK ACTION_SYNC ACTION_CHOOSER ACTION_PICK_ACTIVITY ACTION_GET_CONTENT ACTION_SEARCH ACTION_DIAL ACTION_WEB_SEARCH ACTION_CALL ACTION_FACTORY_TEST ACTION_SEND ACTION_SENDTO For a list of actions see: 9 9
  9. 12. Android – Intents Intents ACTION_AIRPLANE_MODE_CHANGED ACTION_SCREEN_OFF ACTION_EXTERNAL_APPLICATIONS_AVAI ACTION_MEDIA_SCANNER_STARTED ACTION_ALL_APPS LABLE ACTION_SCREEN_ON ACTION_MEDIA_SHARED ACTION_ANSWER ACTION_EXTERNAL_APPLICATIONS_UNA ACTION_SEARCH VAILABLE ACTION_MEDIA_UNMOUNTABLE ACTION_ATTACH_DATA ACTION_SEARCH_LONG_PRESS ACTION_FACTORY_TEST ACTION_MEDIA_UNMOUNTED ACTION_BATTERY_CHANGED ACTION_SEND ACTION_GET_CONTENT ACTION_MY_PACKAGE_REPLACED ACTION_BATTERY_LOW ACTION_SENDTO ACTION_GTALK_SERVICE_CONNECTED ACTION_NEW_OUTGOING_CALL ACTION_BATTERY_OKAY ACTION_SEND_MULTIPLE ACTION_GTALK_SERVICE_DISCONNECTE ACTION_PACKAGE_ADDED ACTION_BOOT_COMPLETED D ACTION_SET_WALLPAPER ACTION_PACKAGE_CHANGED ACTION_BUG_REPORT ACTION_HEADSET_PLUG ACTION_SHUTDOWN ACTION_PACKAGE_DATA_CLEARED ACTION_CALL ACTION_INPUT_METHOD_CHANGED ACTION_SYNC ACTION_PACKAGE_FIRST_LAUNCH ACTION_CALL_BUTTON ACTION_INSERT ACTION_SYSTEM_TUTORIAL ACTION_PACKAGE_INSTALL ACTION_CAMERA_BUTTON ACTION_INSERT_OR_EDIT ACTION_TIMEZONE_CHANGED ACTION_PACKAGE_REMOVED ACTION_CHOOSER ACTION_LOCALE_CHANGED ACTION_TIME_CHANGED ACTION_PACKAGE_REPLACED ACTION_CLOSE_SYSTEM_DIALOGS ACTION_MAIN ACTION_TIME_TICK ACTION_PACKAGE_RESTARTED ACTION_CONFIGURATION_CHANGED ACTION_MANAGE_PACKAGE_STORAGE ACTION_UID_REMOVED ACTION_PASTE ACTION_CREATE_SHORTCUT ACTION_MEDIA_BAD_REMOVAL ACTION_UMS_CONNECTED ACTION_PICK ACTION_DATE_CHANGED ACTION_MEDIA_BUTTON ACTION_UMS_DISCONNECTED ACTION_PICK_ACTIVITY ACTION_DEFAULT ACTION_MEDIA_CHECKING ACTION_USER_PRESENT ACTION_POWER_CONNECTED ACTION_DELETE ACTION_MEDIA_EJECT ACTION_VIEW ACTION_POWER_DISCONNECTED ACTION_DEVICE_STORAGE_LOW ACTION_MEDIA_MOUNTED ACTION_VOICE_COMMAND ACTION_POWER_USAGE_SUMMARY ACTION_DEVICE_STORAGE_OK ACTION_MEDIA_NOFS ACTION_WALLPAPER_CHANGED ACTION_PROVIDER_CHANGED ACTION_DIALFor a list of actionsACTION_MEDIA_REMOVED see: ACTION_WEB_SEARCH ACTION_REBOOT ACTION_DOCK_EVENT ACTION_MEDIA_SCANNER_FINISHED ACTION_RUN 10 ACTION_EDIT ACTION_MEDIA_SCANNER_SCAN_FILE 10
  10. 12. Android – Intents Intents Taken from: Ví dụ : gọi intent thực hiện gọi điện thoại Intent myActivity2 = new Intent (Intent.ACTION_DIAL, Uri.parse( "tel:555-1234")); startActivity(myActivity2); 11 11
  11. 12. Android – Intents Intents Taken from: Intents - Secondary Attributes Ngoài thuộc tính action/ data thì intent còn 1 thuộc tính là: 1. Category 2. Components 3. Type 4. Extras Example: sử dụng chức năng tìm kiếm của google Intent intent = new Intent (Intent.ACTION_WEB_SEARCH ); intent.putExtra(SearchManager.QUERY, "straight hitting golf clubs"); startActivity(intent); Secondary data 12 Apparently the Google answer is „none‟ 12
  12. 12. Android – Intents Intents Taken from: Intents - Secondary Attributes Example: Sending a text message (using extra attributes) Intent intent = new Intent( Intent.ACTION_SENDTO, Uri.parse("sms:5551234")); intent.putExtra("sms_body", "are we playing golf next Saturday?"); startActivity(intent); 13 “address”, “sms_body” are keywords 13
  13. 12. Android – Intents Intents Taken from: Intents - Secondary Attributes Example: Showing Pictures (using extra attributes) Intent myIntent = new Intent(); myIntent.setType("image/pictures/*"); myIntent.setAction(Intent.ACTION_GET_CONTENT); startActivity(myIntent); 14 14
  14. 12. Android – Intents Intents 1. Ví dụ : 1 activity cho phép người dùng nhập số gọi, sau đó gọi activity thực hiện cuộc gọi (Activity này có sẵn trong hệ thống). 15 15
  15. 12. Android – Intents Intents 1. Ví dụ : 1 activity cho phép người dùng nhập số gọi, sau đó gọi activity thực hiện cuộc gọi (Activity này có sẵn trong hệ thống). 16 16
  16. 12. Android – Intents Intents 1. A Complete Example: Activity1 displays an interface to accept a phone number and requests (built-in) Activity2 to make the call. //IntentDemo1_Intent: making a phone call package cis493.intents; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.*; public class IntentDemo1 extends Activity { TextView label1; EditText text1; Button btnCallActivity2; 17 17
  17. 12. Android – Intents Intents 1. A Complete Example: Activity1 displays an interface to accept a phone number and requests (built-in) Activity2 to make the call. @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); try { setContentView(R.layout.main); label1 = (TextView)findViewById(R.id.label1); text1 = (EditText)findViewById(R.id.text1); btnCallActivity2 = (Button)findViewById(R.id.btnCallActivity2); btnCallActivity2.setOnClickListener(new ClickHandler()); } catch (Exception e) { Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show(); } }//onCreate 18 18
  18. 12. Android – Intents Intents 1. A Complete Example: Activity1 displays an interface to accept a phone number and requests (built-in) Activity2 to make the call. ) private class ClickHandler implements OnClickListener { @Override public void onClick(View v) { try { // myActivity2 places a phone call // for ACTION_CALL or ACTION_DIAL // use 'tel:' formatted data: "tel:555-1234" // for ACTION_VIEW use data: " " // (you also need INTERNET permission - see Manifest) String myData = text1.getText().toString(); Intent myActivity2 = new Intent(Intent.ACTION_DIAL, Uri.parse(myData)); startActivity(myActivity2); } catch (Exception e) { Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show(); } }//onClick }//ClickHandler 19 }//IntentDemo1 19
  19. 12. Android – Intents Intents 1. A Complete Example: Activity1 displays an interface that accepts from the user a phone number and requests (built-in) Activity2 to make the call. Action/categor y 20 20
  20. 12. Android – Intents Intents Built-in Standard Broadcast Actions List of standard actions that Intents can use for receiving broadcasts (usually through registerReceiver(BroadcastReceiver, IntentFilter) or a tag in a manifest). ACTION_TIME_TICK ACTION_TIME_CHANGED ACTION_TIMEZONE_CHANGED ACTION_BOOT_COMPLETED ACTION_PACKAGE_ADDED ACTION_PACKAGE_CHANGED ACTION_PACKAGE_REMOVED ACTION_UID_REMOVED ACTION_BATTERY_CHANGED 21 21
  21. 12. Android – Intents Intents More Examples: Using Standard Actions Call Immediately Modify the complete example1 replacing the method „ClickHandler‟ with the following code String myData = "tel:555-1234"; Intent myActivity2 = new Intent(Intent.ACTION_CALL, Uri.parse(myData)); startActivity(myActivity2); Needs Permission: 22 22
  22. 12. Android – Intents Intents More Examples: Using Standard Actions Show all your Contacts Modify the complete example1 replacing the method „ClickHandler‟ with the following code String myData = "content://contacts/people/"; Intent myActivity2 = new Intent(Intent.ACTION_VIEW, Uri.parse(myData)); startActivity(myActivity2); 23 23
  23. 12. Android – Intents Intents More Examples: Using Standard Actions Show a Particular Contact (ID = 210) Modify the complete example1 replacing the method „ClickHandler‟ with the following code String myData = ContactsContract.Contacts.CONTENT_URI + "/" + "210"; Intent myActivity2 = new Intent(Intent.ACTION_VIEW, Uri.parse(myData)); startActivity(myActivity2); 24 24
  24. 12. Android – Intents Intents More Examples: Using Standard Actions Edit a Particular Contact (ID = 210) Modify the complete example1 replacing the method „ClickHandler‟ with the following code String myData = ContactsContract.Contacts.CONTENT_URI + "/" + "210"; Intent myActivity2 = new Intent(Intent.ACTION_EDIT, Uri.parse(myData)); startActivity(myActivity2); 25 25
  25. 12. Android – Intents Intents More Examples: Using Standard Actions View a Webpage Modify the complete example1 replacing the method „ClickHandler‟ with the following code String myData = " "; Intent myActivity2 = new Intent(Intent.ACTION_VIEW, Uri.parse(myData)); startActivity(myActivity2); Caution. Add to the Manifest a request to use the Internet: 26 26
  26. 12. Android – Intents Intents More Examples: Using Standard Actions Geo Mapping an Address Provide a geoCode expression holding a street address (or place, such as „golden gate ca‟ ) Replace spaces with „+‟. String geoCode = "geo:0,0?q=1860+east+18th+street+cleveland+oh"; Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(geoCode)); startActivity(intent); Modify the Manifest adding the following requests: 27 27
  27. 12. Android – Intents Intents More Examples: Using Standard Actions Geo Mapping Coordinates (latitude, longitude) Provide a geoCode holding latitude and longitude (also an addittional zoom „?z=xx‟ with xx in range 1 23) String geoCode = "geo:41.5020952,-81.6789717"; Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(geoCode)); startActivity(intent); Modify the Manifest adding the following requests: 28 28
  28. 12. Android – Intents Intents More Examples // Getting driving directions: how to go from loaction A to location B? String sourceDestination = " "; Intent intent = new Intent( android.content.Intent.ACTION_VIEW, Uri.parse(sourceDestination)); startActivity(intent); 29
  29. 12. Android – Intents Intents More Examples // use a mnemonic to articulate an address String thePlace = "Cleveland State University"; Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("geo:0,0?q= (" + thePlace + ") " )); startActivity(intent); 30
  30. 12. Android – Intents Intents More Examples: Using Standard Actions Geo Mapping - Google StreetView geoCode Uri structure: google.streetview:cbll=lat,lng&cbp=1, yaw,,pitch,zoom&mz=mapZoom Reference: String geoCode = "google.streetview:cbll=41.5020952,- 81.6789717&cbp=1,270,,45,1&mz=1"; Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(geoCode)); startActivity(intent); Modify the Manifest adding the following requests: 31 31
  31. 12. Android – Intents Intents More Examples: Using Standard Actions Launching the Music Player Reference: //launch music player Intent myActivity2 = new Intent("android.intent.action.MUSIC_PLAYER"); startActivity(myActivity2); 32 32
  32. 12. Android – Intents Intents More Examples: Using Standard Actions Playing a song stored in the SD card Reference: // play song "amarcord.mp3" saved in the SD Intent myActivity2 = new Intent(android.content.Intent.ACTION_VIEW); Uri data = Uri.parse("file:///sdcard/amarcord.mp3"); String type = "audio/mp3"; myActivity2.setDataAndType(data, type); startActivity(myActivity2); 33 33
  33. 12. Android – Intents Intents More Examples: Using Standard Actions Sending MMS Add picture #1 from SD to MMS Reference: //send mms attach picture #1 to it Uri uri = Uri.parse("content://media/external/images/media/1"); Intent myActivity2 = new Intent(Intent.ACTION_SEND); myActivity2.putExtra("address", "555-1234"); myActivity2.putExtra("sms_body", "some text message goes here"); myActivity2.putExtra(Intent.EXTRA_STREAM, uri); myActivity2.setType("image/png"); startActivity(myActivity2); 34 34
  34. 12. Android – Intents Intents More Examples: Using Standard Actions Sending Email Reference: // send email Uri uri = Uri.parse("mailto:v.matos@csuohio.edu"); Intent myActivity2 = new Intent(Intent.ACTION_SENDTO, uri); // you may skip the next two pieces [subject/text] myActivity2.putExtra(Intent.EXTRA_SUBJECT, "subject goes here"); myActivity2.putExtra(Intent.EXTRA_TEXT, "The email's body goes here"); startActivity(myActivity2); 35 35
  35. 12. Android – Intents Intents More Examples: Using Standard Actions Setting System Reference: Intent intent = new Intent( android.provider.Settings.ACTION_SETTINGS); startActivity(intent); 36 36
  36. 12. Android – Intents Intents More Examples: Using Standard Actions Setting System Locale: Language & Keyboard Reference: Intent intent = new Intent( android.provider.Settings.ACTION_LOCALE_SETTINGS); startActivity(intent); 37 37
  37. 12. Android – Intents – Part 2 Intents 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. Intent Activity-1 {action + data} Activity-2 startActivityForResult onResult() onActivityResult() requestCode requestResult [ optional data ] 39 39
  38. 12. Android – Intents – Part 2 Intents Android Bundles Most programming languages support the notion of IPC method-calling with arguments flowing birectionally from the caller to the invoked method. In android the calling activity issues an invocation to another activity using an Intent object. Notably in Android, the caller does not stop waiting for the called activity to return results. Instead a listening-method [onActivityResult( ) ] should be used. 40 40 IPC Inter-Process Communication
  39. 12. Android – Intents – Part 2 Intents Android Bundles Normally the IPC expressions actual parameter list, and formal parameter list are used to designated the signature of particpating arguments, and the currently supplied data. Instead of using the traditional formal / actual parameter lists, Android relies on the concept of Intents to establish Inter- process-communication. Intents optionally carry a named actual list or bundle for data exchange. 41 41
  40. 12. Android – Intents – Part 2 Intents Android Bundles The Android Bundle container is a simple mechanism used to pass data between activities. A Bundle is a type-safe collection of pairs. There is a set of putXXX and getXXX methods to store and retrieve (single and array) values of primitive data types from/to the bundles. For example Bundle myBundle = new Bundle(); myBundle.putDouble ("var1", 3.1415); Double v1 = myBundle.getDouble("var1"); 42 42
  41. 12. Android – Intents – Part 2 Intents Android Intents & Bundles Activity1: Sender Activity2: Receiver Intent myIntentA1A2 = new Intent (Activity1.this, Activity2.class); Bundle myBundle1 = new Bundle(); myBundle1.putInt ("val1", 123); myIntentA1A2.putExtras(myBundle1); INTENT startActivityForResult(myIntentA1A2, 1122); Sender class / Receiver class requestCode (1122) resultCode Extras: { val1 = 123 } 43 43
  42. 12. Android – Intents – Part 2 Intents Android Intents & Bundles Activity1: Sender Activity2: Receiver Intent myCallerIntent2 = getIntent(); Bundle myBundle = myCallerIntent.getExtras(); int val1 = myBundle.getInt("val1"); INTENT Sender class / Receiver class requestCode (1122) resultCode Extras: { val1 = 123 } 44 44
  43. 12. Android – Intents – Part 2 Intents Android Intents & Bundles Activity1: Sender Activity2: Receiver myBundle.putString("val1", 456 ); myCallerIntent.putExtras(myBundle); setResult(Activity.RESULT_OK, INTENT myCallerIntent); Sender class / Receiver class requestCode (1122) resultCode (OK) Extras: { val1 = 456 } 45 45
  44. 12. Android – Intents – Part 2 Intents Android Bundles Available at: of Public Methods void clear() Removes all elements from the mapping of this Bundle. Object clone() Clones the current Bundle. boolean containsKey(String key) Returns true if the given key is contained in the mapping of this Bundle. void putIntArray(String key, int[] value) Inserts an int array value into the mapping of this Bundle, replacing any existing value for the given key. void putString(String key, String value) Inserts a String value into the mapping of this Bundle, replacing any existing value for the given key. void putStringArray(String key, String[] value) Inserts a String array value into the mapping of this Bundle, replacing any existing value for the given key. void putStringArrayList(String key, ArrayList value) Inserts an ArrayList value into the mapping of this Bundle, replacing any existing value for the given key. void remove(String key) Removes any entry with the given key from the mapping of this Bundle. int size() Returns the number of mappings contained in this Bundle. 46 46
  45. 12. Android – Intents – Part 2 Intents Tutorial 1. Activity Excahange Activity1 collects two values from its UI and calls Activity2 to compute the sum of them. The result is sent back from Activity 2 to Activity1. 47 47
  46. 12. Android – Intents – Part 2 Intents Tutorial 1. Activity Excahange 48 48
  47. 12. Android – Intents – Part 2 Intents Tutorial 1. Activity Excahange Step2. Create GUI for Activity2(main2.xml) 49 49
  48. 12. Android – Intents – Part 2 Intents Tutorial 1. Activity Excahange Step3. Activity1. After clicking the button data, from UI is put in a bundle and sent to Activity2. A listener remains alert waiting for results to come from the called package cis493.matos.intent2b; activity.// Activity1: get two input values from user, put them in a bumble. call Activity2 to add the two numbers, show result import ; public class Activity1 extends Activity { EditText txtVal1; EditText txtVal2; TextView lblResult; Button btnAdd; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main1); txtVal1 = (EditText)findViewById(R.id.EditText01); txtVal2 = (EditText)findViewById(R.id.EditText02); lblResult = (TextView) findViewById(R.id.TextView01); btnAdd = (Button) findViewById(R.id.btnAdd); btnAdd.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // get values from the UI Double v1 = Double.parseDouble(txtVal1.getText().toString()); Double v2 = Double.parseDouble(txtVal2.getText().toString()); // create intent to call Activity2 Intent myIntentA1A2 = new Intent (Activity1.this, Activity2.class); // create a container to ship data Bundle myData = new Bundle(); // add data items to the container myData.putDouble("val1", v1); myData.putDouble("val2", v2); // attach the container to the intent myIntentA1A2.putExtras(myData); // call Activity2, tell your local listener to wait for response startActivityForResult(myIntentA1A2, 101); } }); 50 }//onCreate 50
  49. 12. Android – Intents – Part 2 Intents Tutorial 1. Activity Excahange cont. Step3. Activity1. After clicking the button data, from UI is put in a bundle and sent to Activity2. A listener remains alert waiting for results to come from the called activity. ////////////////////////////////////////////////////////////////////////////// // local listener receiving callbacks from other activities @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); try { if ((requestCode == 101 ) && (resultCode == Activity.RESULT_OK)){ Bundle myResults = data.getExtras(); Double vresult = myResults.getDouble("vresult"); lblResult.setText("Sum is " + vresult); } } catch (Exception e) { lblResult.setText("Problems - " + requestCode + " " + resultCode); } }//onActivityResult }//Activity1 51 51
  50. 12. Android – Intents – Part 2 Intents Tutorial 1. Activity Excahange cont. Step4. Activity2. Called from Activity1. Extracts input data from the bundle attached to the intent. Performs local computation. Adds result to bundle. Returns package cis493.matos.intent2b; // return sending an OK signal to calling activity OK signal. setResult(Activity.RESULT_OK, myLocalIntent); import . . .; // experiment: remove comment public class Activity2 extends Activity implements OnClickListener{ // finish(); EditText dataReceived; Button btnDone; }//onCreate @Override @Override protected void onCreate(Bundle savedInstanceState) { public void onClick(View v) { super.onCreate(savedInstanceState); // close current screen - terminate Activity2 finish(); setContentView(R.layout.main2); }//onClick dataReceived = (EditText) findViewById(R.id.etDataReceived); btnDone = (Button) findViewById(R.id.btnDone); }//Activity2 btnDone.setOnClickListener(this); // pick call made to Activity2 via Intent Intent myLocalIntent = getIntent(); // look into the bundle sent to Activity2 for data items Bundle myBundle = myLocalIntent.getExtras(); Double v1 = myBundle.getDouble("val1"); Double v2 = myBundle.getDouble("val2"); // operate on the input data Double vResult = v1 + v2; // for illustration purposes. show data received & result dataReceived.setText("Data received is \n" + "val1= " + v1 + "\nval2= " + v2 + "\n\nresult= " + vResult); // add to the bundle the computed result myBundle.putDouble("vresult", vResult); // attach updated bumble to invoking intent myLocalIntent.putExtras(myBundle); 52 52
  51. 12. Android – Intents – Part 2 Intents Tutorial 1. Activity Excahange cont. Step5. Update the application„s manifest. Add new tag for “Activity2“ add 53 53
  52. 12. Android – Intents – Part 2 This example is similar to previous. Intents You may want to skip it. Tutorial 2: : Activity1 invokes Activity2 using an Intent. A bundle conating a set of different data types is sent back-and-forth between both activities (see 12IntentDemo3.zip). 54 54
  53. 12. Android – Intents – Part 2 Intents Tutorial 2 : Activity1 invokes Activity2 using an Intent. A bundle conating a set of different data types is sent back-and-forth between both activities (see 12IntentDemo3.zip). //Activity1: Invoking a user-defined sub-activity sending and receiving results from the sub-activity package cis493.intents3; import . . .; public class Activity1 extends Activity { TextView label1; TextView label1Returned; Button btnCallActivity2; // arbitrary interprocess communication ID (just a nickname!) private final int IPC_ID = (int) (10001 * Math.random()); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); try { setContentView(R.layout.main); label1 = (TextView) findViewById(R.id.label1); label1Returned = (TextView) findViewById(R.id.label1Returned); btnCallActivity2 = (Button) findViewById(R.id.btnCallActivity2); btnCallActivity2.setOnClickListener(new Clicker1()); // for demonstration purposes- show in top label label1.setText("Activity1 (sending ) \n\n" + "RequestCode ID: " + IPC_ID + "\n" + "myString1: Hello Android" + "\n" + "myDouble1: 3.141592 " + "\n" + "myIntArray: {1 2 3} "); } catch (Exception e) { Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show(); 55 } 55 }// onCreate
  54. 12. Android – Intents – Part 2 Intents Tutorial 2 : Activity1 invokes Activity2 using an Intent. A bundle conating a set of different data types is sent back-and-forth between both activities (see 12IntentDemo3.zip). private class Clicker1 implements OnClickListener { public void onClick(View v) { try { // create an Intent to talk to Activity2 Intent myIntentA1A2 = new Intent(Activity1.this, Activity2.class); // prepare a Bundle and add the data pieces to be sent Bundle myData = new Bundle(); myData.putInt("myRequestCode", IPC_ID); myData.putString("myString1", "Hello Android"); myData.putDouble("myDouble1", 3.141592); int [] myLittleArray = { 1, 2, 3 }; myData.putIntArray("myIntArray1", myLittleArray); // bind the Bundle and the Intent that talks to Activity2 myIntentA1A2.putExtras(myData); // call Activity2 and wait for results startActivityForResult(myIntentA1A2, IPC_ID); } catch (Exception e) { Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_LONG).show(); } }// onClick }// Clicker1 56 56
  55. 12. Android – Intents – Part 2 Intents Tutorial 2 : Activity1 invokes Activity2 using an Intent. A bundle conating a set of different data types is sent back-and-forth between both activities (see 12IntentDemo3.zip). @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); try { // check that these results are for us if (IPC_ID == requestCode) { // Activity2 is over - see what happened if (resultCode == Activity.RESULT_OK) { // good - we have some data sent back from Activity2 Bundle myReturnedData = data.getExtras(); String myReturnedString1 = myReturnedData.getString("myReturnedString1"); Double myReturnedDouble1 = myReturnedData.getDouble("myReturnedDouble1"); String myReturnedString2 = myReturnedData.getString("myCurrentTime"); // display in the bottom label label1Returned.setText( "requestCode: " + requestCode + "\n" + "resultCode: " + resultCode + "\n" + "returnedString1: " + myReturnedString1 + "\n" + "returnedDouble: " + Double.toString(myReturnedDouble1) + "\n" + "returnedString2: " + myReturnedString2); } else { // user pressed the BACK button label1.setText("Selection CANCELLED!"); }// if } } catch (Exception e) { Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show(); }// try }// onActivityResult 57 }// AndroIntent1 57
  56. 12. Android – Intents – Part 2 Intents Tutorial 2: Activity2 is called to cooperate with Activity1. Data is transferred in a bundle // Activity2. This subactivity receives a bundle of data, performs some work on the data and, returns results to Activity1. package cis493.intents3; import . . .; public class Activity2 extends Activity { TextView label2; TextView spyBox; Button btnCallActivity1; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main2); //bind UI variables to Java code label2 = (TextView)findViewById(R.id.label2); spyBox = (TextView)findViewById(R.id.spyBox); btnCallActivity1 = (Button)findViewById(R.id.btnCallActivity1); btnCallActivity1.setOnClickListener(new Clicker1()); // create a local Intent handler – we have been called! Intent myLocalIntent = getIntent(); //grab the data package with all the pieces sent to us Bundle myBundle = myLocalIntent.getExtras(); //extract the individual data parts of the bundle int int1 = myBundle.getInt("myRequestCode"); String str1 = myBundle.getString("myString1"); double dob1 = myBundle.getDouble("myDouble1"); int[] arr1 = myBundle.getIntArray("myIntArray1"); 58 58
  57. 12. Android – Intents – Part 2 Intents Tutorial 2: Activity2 is called to cooperate with Activity1. Data is transferred in a // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ bundle // What if I don't know the key names? // what came in the bundle?. This fragment shows how to use // bundle methods to extract its data. Need to know // ANDROID TYPES: // class [I (array integers) // class [J (array long) // class [D (array doubles) // class [F (array floats) // class java.lang.xxx (where xxx= Integer, Double, ) // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ String spy = "\nSPY>>\n"; Set myKeyNames = myBundle.keySet(); for (String keyName : myKeyNames){ Serializable keyValue = myBundle.getSerializable(keyName); String keyType = keyValue.getClass().toString(); if (keyType.equals("class java.lang.Integer")){ keyValue = Integer.parseInt(keyValue.toString()); } else if (keyType.equals("class java.lang.Double")){ keyValue = Double.parseDouble(keyValue.toString()); } else if (keyType.equals("class java.lang.Float")){ keyValue = Float.parseFloat(keyValue.toString()); } else if (keyType.equals("class [I")){ int[] arrint = myBundle.getIntArray(keyName); int n = arrint.length; keyValue = arrint[n-1]; // show only the last! } else { keyValue = (String)keyValue.toString(); } spy += keyName + ": " + keyValue + " " + keyType + "\n" ; } 59 spyBox.append(spy); 59
  58. 12. Android – Intents – Part 2 Intents Tutorial 2: Activity2 is called to cooperate with Activity1. Data is transferred in a // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ bundle //do something with the data here (for example ) String strArr = "{ "; int sumIntValues = 0; for (int i=0; i<arr1.length; i++) { sumIntValues += arr1[i]; strArr += Integer.toString( arr1[i] ) + " "; } strArr += " } their sum is= " + sumIntValues; //show arriving data in GUI label2 label2.append("\n\nActivity2 (receiving ) \n\n" + "Caller's requestCode ID: " + int1 + "\n" + "myString1: " + str1 + "\n" + "myDouble1: " + Double.toString(dob1) + "\n" + "myIntArray1: " + strArr); //now go back to myActivity1 with some new data made here double someNumber = sumIntValues + dob1; myBundle.putString("myReturnedString1", "Adios Android"); myBundle.putDouble("myReturnedDouble1", someNumber); myBundle.putString("myCurrentTime", new Date().toLocaleString() ); myLocalIntent.putExtras(myBundle); // all done! setResult(Activity.RESULT_OK, myLocalIntent); }//onCreate private class Clicker1 implements OnClickListener { public void onClick(View v) { //clear Activity2 screen so Activity1 could be seen finish(); }//onClick }//Clicker1 60 }//Activity2 60
  59. 12. Android – Intents – Part 2 Intents Tutorial 2: Activity2 is called to cooperate with Activity1. Data is transferred in a bundle Layout: main.xml android:layout_width="fill_parent" xmlns:android=" " android:background="#ff555555"> android:textSize="20px" android:textStyle="bold" android:layout_width="fill_parent" android:layout_height="wrap_content" > <TextView android:id="@+id/label1" 61 61
  60. 12. Android – Intents – Part 2 Intents Tutorial 2: Activity2 is called to cooperate with Activity1. Data is transferred in a bundle Layout: main2.xml android:layout_height="wrap_content" android:orientation="vertical" xmlns:android=" " android:id="@+id/btnCallActivity1" android:textSize="20px" android:textStyle="bold" > android:id="@+id/spyBox" android:textStyle="normal" android:layout_margin="7dip"> android:id="@+id/label2" android:layout_width="fill_parent" 62 62
  61. 12. Android – Intents – Part 2 Intents Appendix A. Bundling Complex Objects Extending Tutorial2 to allow Activity1 to create a local object and pass it to Activity2 into the IPC bundle as serialized data. Step 1. Create an Object. Make sure it implements Serializable interface. package cis493.intents3; import java.io.Serializable; public class Person implements Serializable { private static final long serialVersionUID = 1L; private String firstName; private String lastName; public Person(String firstName, String lastName) { super(); this.firstName = firstName; this.lastName = lastName; } public String getFullName() { return firstName + " " + lastName; } }//Person 63 63
  62. 12. Android – Intents – Part 2 Intents Appendix A. Bundling Complex Objects Extending Tutorial2 to allow Activity1 to create a local object and pass it to Activity2 into the IPC bundle as serialized data. Step 2. Modify Activity1. Create an instance of the Person class and add it to the bundle using the method putSerializable (key, object); // prepare a Bundle and add the data pieces to be sent Bundle myData = new Bundle(); . . . // creating an object and passing it into the bundle Person p1 = new Person("Maria", "Macarena"); myData.putSerializable("person", p1); // bind the Bundle and the Intent that talks to Activity2 myIntentA1A2.putExtras(myData); // call Activity2 and wait for results startActivityForResult(myIntentA1A2, IPC_ID); 64 64
  63. 12. Android – Intents – Part 2 Intents Appendix A. Bundling Complex Objects Extending Tutorial2 to allow Activity1 to create a local object and pass it to Activity2 into the IPC bundle as serialized data. Step 3. Modify Activity2. Capture the instance of the Person class using the method getSerializable (key); // create a local Intent handler – we have been called! Intent myLocalIntent = getIntent(); //grab the data package with all the pieces sent to us Bundle myBundle = myLocalIntent.getExtras(); //extract the individual data parts of the bundle . . . Person p = (Person) myBundle.getSerializable("person"); String pval = p.getFullName(); . . . Note: The object person has a complex class type received as: 65 65 class packageName.Person
  64. 12. Android – Intents Intents Starting Activities and Getting Results The startActivity(Intent) method is used to start a new activity, which will be placed at the top of the activity stack. The caller however continues to execute in its own thread. Sometimes you want to get a result back from the called sub-activity when it ends. For example, you may start an activity that let the user pick a person from a list of contacts; when it ends, it returns the person that was selected. 67 67
  65. 12. Android – Intents Intents Starting Activities and Getting Results In order to get results back from the called activity we use the method startActivityForResult ( Intent, requestCodeID ) Where requestCodeID is an arbitrary value you choose to identify the call (similar to a „nickname‟ ). The result sent by the sub-activity could be picked up through the listener-like asynchronous method onActivityResult ( requestCodeID, resultCode, Intent ) 68 68
  66. 12. Android – Intents Intents Starting Activities and Getting Results • Before an invoked activity exits, it can call setResult (resultCode) to return a termination signal back to its parent. • It is convenient to supply a result code, which can be the standard results Activity.RESULT_CANCELED, Activity.RESULT_OK, or any custom values. • All of this information can be capture back on the parent's onActivityResult (int requestCodeID, int resultCode, Intent data) • If a child activity fails for any reason (such as crashing), the parent activity will receive a result with the code RESULT_CANCELED. 69 69
  67. 12. Android – Intents Intents Starting Activities and Getting Results Intent: {action + data + Activity-1 requestCodeID } startActivityForResul Activity-2 t ___ __ ___ onActivityResult() _ requestCodeID onResult() resultCode optional data 70 70
  68. 12. Android – Intents Intents Example2. Let‟s play golf - Call for a tee-time. 1. Show all contacts and pick a particular one (Intent.ACTION_PICK). 2. For a successful interaction the main-activity accepts the returned URI identifying the person we want to call (content://contacts/people/n). 3. „Nicely‟ show the selected contact‟s entry allowing calling, texting, emailing actions (Intent.ACTION_VIEW). Intent.ACTION_PI User’s main CK Built-in Activity-2 Contact‟s (show contact list) Activity-1 Uri Intent.ACTION_VIE Call Send text message W Built-in Activity-3 Send email (show selected contact) 71 71
  69. 12. Android – Intents Intents Example2. Let‟s play golf - Call for a tee-time. Cont. 72 Main Activity Intent.ACTION_PICK Intent.ACTION_VIEW 72
  70. 12. Android – Intents Intents Example2 (cont.) Let‟s play golf - Call for a tee-time 73 Place the call Terminate the call Selected contact‟s URI 73
  71. 12. Android – Intents Intents Example2. Calling a sub-activity, receiving results. //IntentDemo2_Intent: making a phone call //receiving results from a sub-activity package cis493.intents; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.*; public class IntentDemo2 extends Activity { TextView label1; EditText text1; Button btnCallActivity2; 74 74
  72. 12. Android – Intents Intents Example2. Calling a sub-activity, receiving results. @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); try { setContentView(R.layout.main); label1 = (TextView)findViewById(R.id.label1); text1 = (EditText)findViewById(R.id.text1); btnCallActivity2 = (Button)findViewById(R.id.btnPickContact); btnCallActivity2.setOnClickListener(new ClickHandler()); } catch (Exception e) { Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show(); } }//onCreate 75 75
  73. 12. Android – Intents Intents Example2. Calling a sub-activity, receiving results. private class ClickHandler implements OnClickListener { @Override public void onClick(View v) { try { // myData refer to: content://contacts/people/ String myData = text1.getText().toString(); //you may also try ACTION_VIEW instead Intent myActivity2 = new Intent(Intent.ACTION_PICK, Uri.parse(myData)); // start myActivity2. // Tell it that our requestCodeID (or nickname) is 222 startActivityForResult(myActivity2, 222); // Toast.makeText(getApplicationContext(), // "I can't wait for you", 1).show(); } catch (Exception e) { label1.setText(e.getMessage()); } }//onClick 76 }//ClickHandler 76
  74. 12. Android – Intents Intents Example2. Calling a sub-activity, receiving results. @Override protected void onActivityResult(int requestCode, Listener int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); try { // use requestCode to find out who is talking back to us switch (requestCode){ case (222): { // 222 is our friendly contact-picker activity if (resultCode == Activity.RESULT_OK) { String selectedContact = data.getDataString(); // it will return an URI that looks like: // content://contacts/people/n // where n is the selected contacts' ID label1.setText(selectedContact.toString()); //show a 'nice' screen with the selected contact Intent myAct3 = new Intent (Intent.ACTION_VIEW, Uri.parse(selectedContact)); startActivity(myAct3); 77 } 77
  75. 12. Android – Intents Intents Example2. Calling a sub-activity, receiving results. else { //user pressed the BACK button label1.setText("Selection CANCELLED " + requestCode + " " + resultCode); } break; } }//switch } catch (Exception e) { Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show(); } }// onActivityResult }//IntentDemo2 78 78
  76. 12. Android – Intents Intents Example2. Calling a sub-activity, receiving results. 79 79
  77. 12. Android – Intents Intents Example3. Showing Pictures and Video - Calling a sub-activity, receiving results. private void showSoundTracks() { All videos and all still images Intent myIntent = new Intent(); myIntent.setType("video/*, images/*"); myIntent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(myIntent, 0); }//showSoundTracks @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); if ((requestCode == 0) && (resultCode == Activity.RESULT_OK)) { String selectedImage = intent.getDataString(); Toast.makeText(this, selectedImage, 1).show(); // show a 'nice' screen with the selected image Intent myAct3 = new Intent(Intent.ACTION_VIEW, Uri.parse(selectedImage)); startActivity(myAct3); } }//onActivityResult 80 80
  78. 12. Android – Intents Intents Example3. Showing Pictures and Video - Calling a sub-activity, receiving results. video 81 81
  79. 12. Android – Intents Intents Example4. Showing/Playing Sound Tracks - Calling a sub-activity, receiving results.private void showSoundTracks() { Intent myIntent = new Intent(); myIntent.setType("audio/mp3"); myIntent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(myIntent, 0); }//showSoundTracks The returned string value is similar to the following “content://media/external/audio/media/14” ACTION_VIEW on that Uri would produce a result similar to the image on the right 82 82
  80. Intent Filters INTENTS • Intent là một mô tả trừu tượng của 1 hành động được thực hiện. • Là một thành phần quan trọng trong quá trình khởi tạo 1 activity. • Thông tin chủ yếu trong intent : action & data. ACTION DATA Misc The general action to be The data to operate on, such as a performed, such as: person record in the contacts database, expressed as a URI. ACTION_EDIT, I am good for editing a document ACTION_VIEW, I am good for viewing a document ACTION_MAIN, I am the first exec. Activ. of ACTION_LAUNCHER Application etc. Put me on the phone‟s Menu_Pad Source: 85
  81. 19. Android – Intent Filters Intent Filters Parts of a Typical Intent ACTION DATA MISC Standard URI Category CATEGORY_DEFAULT ACTION_MAIN ACTION_TIME_TICK CONTENTS such as: CATEGORY_BROWSABLE ACTION_VIEW ACTION_TIME_CHANGED CATEGORY_TAB ACTION_ATTACH_DATA ACTION_TIMEZONE_CHANGED CATEGORY_ALTERNATIVE ACTION_EDIT ACTION_BOOT_COMPLETED CATEGORY_SELECTED_ALTERNATIVE ACTION_PICK ACTION_PACKAGE_ADDED content://contacts/ CATEGORY_LAUNCHER ACTION_CHOOSER ACTION_PACKAGE_CHANGED CATEGORY_INFO content://contacts/1 CATEGORY_HOME ACTION_GET_CONTENT ACTION_PACKAGE_REMOVED CATEGORY_PREFERENCE ACTION_DIAL ACTION_PACKAGE_RESTARTE CATEGORY_TEST ACTION_CALL D SCHEME such as: ACTION_SEND ACTION_PACKAGE_DATA_CLE ACTION_SENDTO ARED MIME ACTION_ANSWER ACTION_UID_REMOVED tel:123 Explicit type (a MIME type) of ACTION_INSERT ACTION_BATTERY_CHANGED ACTION_DELETE ACTION_POWER_CONNECTED the intent data. ACTION_RUN ACTION_POWER_DISCONNECT mailto://aa@bbb.ccc ACTION_SYNC ED ACTION_PICK_ACTIVITY ACTION_SHUTDOWN Component ACTION_SEARCH Explicit name of a component ACTION_WEB_SEARCH . . . ACTION_FACTORY_TEST pop:// class to use for the intent. smtp:// Extras ssl:// putExtra(String, Bundle) Flags 86 86
  82. 19. Android – Intent Filters Intent Filters Aside: MIME “ This set of documents, collectively called the Multipurpose Internet Mail Extensions, or MIME, redefines the format of messages to allow for (1) textual message bodies in character sets other than US-ASCII, (1) an extensible set of different formats for non-textual message bodies, (2) multi-part message bodies, and (3) textual header information in character sets other than US-ASCII.” NOTE: Current usage of MIME describes ___ content type in general. Source: Multipurpose Internet Mail Extensions. (MIME) Part Two: Media Types. 87 Available at: 87
  83. 19. Android – Intent Filters Intent Filters Intent Resolution Khi intent gửi ra 1 yêu cầu, Android sẽ tím kiếm các trả lời phù hợp cho intent đó. Để quyết định intent nào thực hiện dưa trên mô tả của intent, và đây là cách chia intent thành 2 thành phần : Intent tường minh(Explicit Intents) dùng để nói đến một thành phần cụ thể ( setComponent(ComponentName) or setClass(Context, Class) ), 1 class cụ thể để thực hiện. Đây là 1 cách để gọi 1 activity khác thực thi. Intent không tường minh (Implicit Intents) không phải là một thành phần cụ thể (1 class). Nhưng các intent này đủ thông tin, giúp hệ thống xác định thành phần nào được thực thi. 88 88
  84. 19. Android – Intent Filters Intent Filters Intent Resolution 89
  85. 19. Android – Intent Filters Intent Filters Intent Resolution Activity3 gửi 1 yêu cầu xử lý tin nhắn vừa được gửi tới. Giả sử người dùng đã cài đặt ứng dụng “Fancy SMS” để thay thế 1 ứng dụng có sẵn trong hệ thống “HUMBLE SMS”. Upon the arrival of the implicit Intent, Android will (somehow) tell the user: You have got a new text-message. I have a FANCY and a HUMBLE SMS application – which one you want me to execute? Make it a default? Choosing candidates: For an activity to be eligible for execution it must: 1. Support the specified action 2. Support the indicated MIME type (if supplied) 3. Support all of the categories named in the intent.___ RULE OF THUMB: Your Intents should be as specific as possible 90 90
  86. Intent Filters Example: Intent Filters The Manifest tells the application (FancySms) is able to intercept incoming SMS data using its SMSReceiver (potential alternative to the default SMS app.) 91
  87. 19. Android – Intent Filters Intent Filters Comments on the example: • The application consists of two components: 1. a common Activity called FancySms (acting as the main routine) and 2. a background Service (BroadcastReceiver) called SMSService. • The clause below indicates the application is allowed to receive SMS • The component SMSService has the filter that triggers its execution whenever a new SMS is received • Other applications with the same filter can be also called by Android when new SMS arrives (until a DEFAULT is chosen) 92 92
  88. 19. Android – Intent Filters Intent Filters Example: Intercepting Incoming SMS 93
  89. 19. Android – Intent Filters Intent Filters Example: Intercepting Incoming SMS Note: Test the following application from the Eclipse‟s DDMS perspective. Select “Emulator Control” > “Telephony Actions”. Set phone no. to 5554, type a message, click on Send. Alternatively you may start another emulator and send SMS to 5554 94 94
  90. 19. Android – Intent Filters Intent Filters Example: Intercepting Incoming SMS // FancySms: main screen - displays intercepted SMS package cis493.intentfilters; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class FancySms extends Activity { static TextView txtMsg; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); txtMsg = (TextView)findViewById(R.id.theMessage); } }// class FancySms 95 95
  91. 19. Android – Intent Filters Intent Filters Example: Intercepting Incoming SMS // SMSReceiver: listens to broadcasted SMS_RECEIVED signals package cis493.intentfilters; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.telephony.gsm.SmsMessage; import android.widget.Toast; public class SMSReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // Android saves in a bundle the current text-message // under name "pdus" and type: Object[]. Later we cast to // SmsMessage[]. Jargon pdu stands for "protocol data unit" Bundle bundle = intent.getExtras(); 96 96
  92. 19. Android – Intent Filters Intent Filters Example: Intercepting Incoming SMS Object messages[] = (Object[]) bundle.get("pdus"); SmsMessage smsMessage[] = new SmsMessage[messages.length]; // Note: long sms are broken and transmitted into various pieces String msg = ""; int smsPieces = messages.length; for (int n = 0; n >> Received SMS: " + smsMessage[0].getMessageBody(), Toast.LENGTH_LONG); toast.show(); cis493.intentfilters.FancySms.txtMsg.setText(msg); } 97 }// class SMSReceiver 97