• Save
Intents in Android 4.x
Upcoming SlideShare
Loading in...5

Intents in Android 4.x



An introduction to Intents in Android 4.x

An introduction to Intents in Android 4.x

The source code is available at https://github.com/iliocatallo/takenotes



Total Views
Views on SlideShare
Embed Views



0 Embeds 0

No embeds



Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
Post Comment
Edit your comment

Intents in Android 4.x Intents in Android 4.x Presentation Transcript

  • Intents Ilio Catallo, Eleonora Ciceri – Politecnico di Milano ilio.catallo@polimi.it, eleonora.ciceri@polimi.it
  • Agenda ¤  Event handling ¤  Event handling vs. layout file ¤  TakeNotes V3 implementation ¤  Intents ¤  What is an Intent? ¤  Launching an Activity ¤  TakeNotes V3 implementation 2
  • Event handling vs. layout file 3
  • Event handling vs. layout file Callback methods ¤  Already present in the View class Event listeners ¤  Nested interfaces + Customized implementation 4 . . . . . .
  • Event handling vs. layout file ¤  Sometimes there are views that do not need to change during run-time 5 The “+” button ü  Used to add new items to the list ü  It is loaded at runtime ü  Its behavior remains unchanged during the execution ü  Its aspect remains unchanged during the execution
  • Event handling vs. layout file Changes on the view ¤  Causes ¤  It is created during the execution (e.g., new to- do item) ¤  Approach ¤  The listener is added programmatically ¤  Example ¤  Checkboxes vs. onClick! View is unaltered ¤  Causes ¤  It represents a static behavior of the application ¤  Approach ¤  Define its aspect and behavior in layout file ¤  Example ¤  “+” button 6
  • Event handling vs. layout file 7 associated with described in This is a reference to the button that was clicked
  • Event handling vs. layout file ¤  To correctly locate the callback method from its name as specified in the layout file, the callback method must: ¤  Be public ¤  Have a void return value ¤  Specify a View as the only parameter (i.e., the View that was clicked) ¤  Example: public void addNewToDo(View v)! 8
  • TakeNotes v3: add a new item ¤  In the previous TakeNotes version we have seen how to delete an item from the to do list ¤  We are now going to add a new item to the do to list ¤  Use case: ¤  The user presses the + button ¤  A form appears, requiring the item description ¤  The user inserts the text and confirms the action ¤  The new checkbox appears in the to do list 9
  • TakeNotes v3: The + button ¤  We define a + button that, if clicked, starts the procedure used for adding an item to the to do list ¤  where the requireNewToDo is a method defined in the ToDoListActivity class that will be invoked when the user clicks the button 10 <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/button_requireAdd" android:onClick="requireNewToDo"/>
  • TakeNotes v3: The + button 11
  • Intents 12
  • Intents ¤  An Intent is an abstract description of an operation to be performed ¤  It can be thought as a message that is passed between components ¤  The message contains instructions for executing a specific action ¤  An intent involves two subjects: ¤  The sender wants a job to be performed and thus publishes a message (i.e., an intent) ¤  The receiver is any component which is able to perform the requested job 13
  • Exampleof(Implicit) Intent 14 Intent Action: play video Data: URL Browser application YouTube application
  • What Intents are good at ¤  Intents are used in a variety of situations: ¤  Taking pictures from the camera ¤  Starting a new web search ¤  Sending e-mails ¤  Sending SMS’s ¤  All these features take advantage of the most significant use of Intents, i.e., launching new Activities 15
  • Explicit and implicit Intents ¤  There exist only two ways of launching a new Activity: ¤  By name: you know the exact name of the Activity you want to launch ¤  By action: you want something to be done for you (e.g., taking a picture) ¤  Consequently, Android provides two kinds of Intents: ¤  Explicit intents, which specify the exact Activity to which the Intent should be given ¤  Implicit Intents, which do not declare the name of the Activity to start, but instead declare an action to perform 16
  • Explicit Intents (1) ¤  Explicit Intents are typically used for launching new Activities within the same application ¤  Nothing in the Intent object other than the name of the Activity to be launched matters ¤  All other fields (action, data, category) are null! 17 Intent intent = new Intent(this, NewActivity.class);
 ! Context The calling Activity is used as a Context object in order to determine the package where to look for the NewActivity class
  • Implicit Intents (1) ¤  Each implicit Intent contains information useful to the receiver for performing the job: ¤  Action: the job that the sender can require to perform ¤  Data: the data on which the job will run ¤  Category: the execution requirements (e.g., of being executed in a browser) 18 Intent in = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:0223993669")); ! Action Making a phone call Data The phone number
  • Implicit Intents (2) ¤  The system determines which Activity is best to run based on the fields (e.g., action) of the implicit Intent ¤  If more than one Activity can handle the Intent, a dialog for the user to select which app to use is displayed 19
  • Implicit intents vs. explicit intents 20 Activity 1 Activity 2 Intent Resolution Explicit Intent: “Execute Activity3” Implicit Intent: “Send a new e-mail” Activity 3 Fancy e-mail client Humble e-mail client User decides which client to use
  • Launching an Activity (1) ¤  To start an activity, call the startActivity(Intent) method ¤  Once the startActivity(Intent) method is invoked ¤  In case of implicit intent, the resolution mechanism identifies the Activity that best matches the intent fields ¤  In case of explicit intent, the system receives the call and starts an instance of the Activity specified by the Intent! 21 Intent intent = ..." startActivity(intent);!
  • Launching an Activity (2) ¤  It is possible to pass some parameters to the started Activity by adding them as extra content of the Intent! 22 Intent intent = ..." intent.putExtra(EXTRA_MESSAGE, myMessage);
  • Launching an Activity (3) ¤  Within the just-started Activity, you can inspect the received Intent by using the getIntent() method ¤  Useful to retrieve the data contained in the Intent ¤  This is usually done in the onCreate() method of the new Activity 23 Intent intent = getIntent();
 String message = intent.getStringExtra(EXTRA_MESSAGE);!
  • Receiving implicit Intents ¤  How to inform the system that an Activity can handle a specific type of implict Intent? ¤  This can be done by advertising that a given Activity can manage a specific implicit Intent, i.e., by associating the Activity with an Intent filter ¤  An Intent filter: ¤  declares the capability of an Activity of receiving implicit Intents of a specific type ¤  delimits the Intents an Activity can handle 24
  • Example: dialing a number (1) ¤  In order to declare an Intent filter, you need to add an <intent-filter> element in your manifest file for the corresponding <activity> element ¤  Example: we declare that the Activity can act as a dialer 25 <intent-filter> <action android:name="android.intent.action.DIAL" /> <category android:name="android.intent.category.DEFAULT" /> <data android:scheme="tel"/> </intent-filter>
  • Example: dialing a number (2) ¤  Everytime an implicit intent of type android.intent.action.DIAL is casted: ¤  Our Activity is listed as a candidate: 26 Intent in = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:0223993669")); startActivity(in);
  • Example: launching an app ¤  Look in your AndroidManifest.xml file: ¤  You will find an intent filter associated with the main Activity ¤  The intent filters declares that the main activity can receive an implicit Intent coming from the Launcher ¤  Such a implicit intent corresponds to the user’s action of launching the application 27 <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter>
  • Requesting a result from an Activity (1) ¤  Starting another Activity does not have to be one-way ¤  You can start a second Activity and receive a result back ¤  Examples ¤  Start the camera and receive the photo as a result ¤  Start the People app and receive a contact details as a result 28
  • Requesting a result from an Activity (2) 29 Activity 1 Camera Activity Implicit Intent: “Take a picture” Calling (first) Activity Called (second) Activity
  • Requesting a result from an Activity (3) ¤  The Intent you pass is the same you could use to start an Activity without requiring a result back ¤  Just call startActivityForResult() instead of startActivity()! ¤  You need to pass an additional integer argument, that represents a request code that identifies the request 30 Intent intent = ... " startActivityForResult(intent, MY_REQUEST_CODE);!
  • Returned data (1) ¤  As soon as the user is done with the called Activity, the result will be sent back to the first Activity ¤  Along with the actual result, additional information is returned from the called Activity to the calling Activity: ¤  The request code originally sent by the calling Activity ¤  A result code to notify that the operation in the called Activity has been successful ¤  Insight: Activity result codes have the same role as the HTTP status codes 31
  • Returned data (2) 32 Activity 1 Camera Activity (android.media.action.IMAGE_CAPTURE, TAKE_PICTURE*) Calling (first) Activity Called (second) Activity < , TAKE_PICTURE, RESULT_OK> * where TAKE_PICTURE is a int constant representing the request code
  • Processing the returned data ¤  When the second Activity returns, the system invokes the onActivityResult() method on the calling Activity ¤  The data are sent back to the calling Activity as an Intent 33 @Override
 protected void onActivityResult(int requestCode,int resultCode,Intent data) {
 if (requestCode == MY_REQUEST_CODE)
 if (resultCode == RESULT_OK)
  • Role of the request code (1) ¤  The calling Activity uses different request codes to distinguish between different types of requests ¤  When receiving a result, the calling Activity uses the request code to identify the provenance of the result ¤  The request codes only makes sense for the calling Activity, while they do not have any particular meaning for the called Activity 34
  • Role of the request code (2) 35 Activity 1 Activity 4 Activity 3 Activity 2 Request code: 1! Request code: 2! Request code: 3!
  • Role of the request code (3) 36 Request code: 1! Activity 2 Activity 1 Activity 4 Activity 3 The data come from Activity 2, as the request code bundled with the result is 1!
  • Returning data from an Activity ¤  In case the called Activity is part of our application, we have to deal also with the problem of returning data to the calling Activity ¤  We need to: ¤  Perform the operation for which we launched the second Activity ¤  Pack the result into an Intent object ¤  Determine the result code ¤  Terminate the called Activity 37
  • Performing the operation in the called Activity ¤  An Activity represents a task the user can achieve ¤  To this end, it may be possible for the calling Activity to provide some parameters to the second Activity ¤  These parameters are sent within the Intent as extra’s ¤  We already know how to inspect the triggering Intent within the second Activity: 38 Intent intent = getIntent();
 String message = intent.getStringExtra(EXTRA_MESSAGE);!
  • Packing the result into an Intent object ¤  The called Activity produces a result of some kind ¤  These data can be packed into an Intent by using the Intent’s putExtra() method 39 Intent intent = new Intent(); intent.putExtra("KeyForResult1", result1); intent.putExtra("KeyForResult2", result2); We use the default constructor, since we do not know anything about the calling Activity (but the OS knows for us)
  • Determining the result code ¤  The operation performed in the called Activity may succeed or fail, and the resulting data may change accordingly ¤  You can set the result and the corresponding result code as follows: 40 Intent data = new Intent(); data.putExtra(...) .... setResult(RESULT_OK, data); We use the default constructor, since we do not know anything about the calling Activity (but the OS knows for us)
  • Terminating the called Activity (1) ¤  The Intent containing the result will not be fired until the called Activity is running ¤  It is the Operating System (OS) that passes Intents between different components ¤  No communication occurs as long as the control does not return to the OS ¤  Hence, when the user is done with the Activity, it has to be terminated 41
  • Terminating the called Activity (2) ¤  Usually, it is up to the Operating System to decide when to terminate an Activity ¤  However, is some cases the user performs an operation of the UI that indicates that he is done with the current Activity ¤  To manually terminate an Activity we can use the finish() method 42 Intent data = new Intent(); data.putExtra(...) .... setResult(RESULT_OK, data); finish()
  • TakeNotes v3: require a new to do ¤  When the + button is clicked, a new to do is required ¤  The input form containing the to do data is launched in a second Activity (AddToDoActivity) ¤  We require the execution of the second Activity, expecting it to return a result (i.e., the to do description) 43 Intent intent = new Intent(this, AddToDoActivity.class);
 startActivityForResult(intent, REQUIRE_NEW_TODO);! Request code, stored in ToDoListActivity.java: public static final int REQUIRE_NEW_TODO = 0;!
  • TakeNotes v3: input the new to do ¤  The interface is built in the layout file (res/layout/) 44 <LinearLayout [...]> <EditText android:id="@+id/toDoContent" [...]/> <Button [...] android:onClick="addToDoToList"/> </LinearLayout>
  • TakeNotes v3: return the result (1) ¤  When the user clicks on the button, the to-do item has to return to the first activity (ToDoListActivity) ¤  To do so, we collect the result from the AddToDoActivity activity and send it back with an Intent ¤  The Intent will report the to-do description as extra content ¤  Once the Intent is sent, the AddToDoActivity activity is closed using the finish() instruction 45
  • TakeNotes v3: return the result (2) 46 public void addToDoToList(View view) { Intent intent = new Intent(this, ToDoListActivity.class); EditText editText = (EditText) findViewById(R.id.toDoContent); String newContent = editText.getText().toString(); intent.putExtra(TODO_CONTENT, newContent); setResult(RESULT_OK, intent); finish(); } Called when the button is pressed Terminate the Activity and release the intent
  • @Override
 public void onActivityResult(int requestCode, int resultCode, Intent intent) {
 super.onActivityResult(requestCode, resultCode, intent);
 if (requestCode == REQUIRE_NEW_TODO &&" resultCode == RESULT_OK)
 if (intent != null)
 addNewToDoToList(" " "intent.getStringExtra(AddToDoActivity.TODO_CONTENT));
 }! TakeNotes v3: receive the result 47 ¤  The result is now returned to ToDoListActivity and needs to be processed ¤  All the results coming from an Intent are collected by the onActivityResult method Verify the request code so as to identify the correct result
  • TakeNotes v3: add to do to list ¤  We retrieved the item description, not the checkbox ¤  The next steps are: ¤  Build the checkbox ¤  Add the checkbox to the list linear layout 48 CheckBox newToDoCheckBox = new CheckBox(this);
 LinearLayout linearLayout = (LinearLayout) " " " "findViewById(R.id.checkBoxContainer);
 linearLayout.addView(newToDoCheckBox);! See TakeNotes v2
  • References 49
  • References ¤  Android Training, Starting an Activity http://developer.android.com/training/basics/firstapp/starting- activity.html ¤  Android Training, Getting a Result from an Activity http://developer.android.com/training/basics/intents/result.html ¤  Android API Guides, Intent and Intent Filters http://developer.android.com/guide/components/intents- filters.html ¤  Android Training, Sending the User to Another App http://developer.android.com/training/basics/intents/sending.html ¤  Android Training, Allowing other Apps to Start Your Activity http://developer.android.com/training/basics/intents/filters.html 50