Android App Development - 02 Activity and intent

Embed Size (px)

Citation preview

  1. 1. Activity and Intent
  2. 2. Activity and Intent A Intent is a messaging object that has the purpose to let communicate the fundamental components of an application and the system. Can be composed of 3 parameters (of which none required): Action: A string that specifies the action you want to perform Data: a Uri object that specifies the MIME Type of the object and depends on the action (eg. ACTION_EDIT With action you can specify what type of file you want to edit) Category: a string that contains additional information to narrow down the choices to the system Additional parameters: Extras: Bundle object to insert additional data via key-value map Flag: int that tells the system how to behave handling activity lifecycle Intent - Definition
  3. 3. Activity and Intent When you instantiate an Intent there are 2 possible approaches based on the result you want to achieve: Explicit Intent: used to get a main component inside the application using its class Intent intent = new Intent(context, MyActivity.class); Implicit Intent: used to perform an action, but without specifying the class of the object that must be performed. In this way you are delegating to the system the task of selecting the correct key component to perform the action. If multiple external applications contain components that handle the Intent, the system prompts the user to select the application to run. The system looks in the manifest of installed applications to make the match of the data Intent. Intent intent = new Intent("com.example.android.READ_FILE"); Intent - Tipology
  4. 4. Activity and Intent To notify the system that a main component of our application handles an Intent, it is declared in the manifest inside the component node: When prompted for the system to handle an Intent that matches the one stated above, the system starts the corresponding Activity. The action is mandatory, category and data aren't. Everyone can have multiplicity greater than 1. Intent - IntentFilter
  5. 5. Activity and Intent To decide which is the best component to manage an Intent, the system performs 3 tests (if one fails, the component is discarded): Action Test: complete match between the Intent action and that of the component Category Test: any category Intent must match that of the manifest, but not vice versa (if it is not specified intent category, the test is positive) Data Test: each data can specify a URI like this: ://:/ If not specified scheme, the host is ignored. If the host is not specified, the path is ignored. If there are nor scheme nor host, the path is ignored. Intent - Resolution
  6. 6. Activity and Intent It's the only component that has a graphical user interface and thus provides for user interaction An application with UI is composed of one or more Activity All instances of Activity are maintained and operated in a back stack It can not be instantiated using the keyword "new" Each Activity has its own life cycle that must be managed by the developer Each Activity you want to start the application have to be declared in the Manifest (with an optional Intent Filter) To notify the system which Activities are our application launcher, you must enter the following Intent Filter in the Manifest for each activity: Activity - Description
  7. 7. Activity and Intent An Activity is created only by Intent (implicit or explicit), passed as a parameter to the method Context.startActivity(Intent intent). Without an Intent Filter an Activity can only be started via an explicit Intent. Implicit Intent: Intent intent = new Intent(Intent.ACTION_SEND); intent.putExtra(Intent.EXTRA_EMAIL, recipientArray); startActivity(intent); Explicit Intent: Intent intent = new Intent(this, SignInActivity.class); startActivity(intent); To get a result from a started Activity you can use the method Activity.startActivityForResult (Intent intent, int requestCode). To retrieve the results you need to override the method Activity.OnActivityResult (requestCode int, int resultCode, Intent data) int the activity that initiates the request. Activity - Starting
  8. 8. Activity and Intent private void pickContact() { // Create an intent to "pick" a contact, as defined by the content // provider URI Intent intent = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI); startActivityForResult(intent, PICK_CONTACT_REQUEST); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // If the request went well (OK) and the request was PICK_CONTACT_REQUEST if (resultCode == Activity.RESULT_OK && requestCode == PICK_CONTACT_REQUEST) { // Perform a query to the contact's content provider for the //contact's name } } To close the instance of an Activity you must use the method Activity.finish(). Activity - Starting
  9. 9. Activity and Intent Activity LifeCycle
  10. 10. Activity and Intent The entire life cycle of an Activity can be divided into 3 macro states: Creation state (onCreate() - onDestroy()): The whole life cycle (everything happens between onCreate() and OnDestroy()). In onCreate() the Activity is instantiated with its graphical interface, in onDestroy() all the resources are released and the entire interface is destroyed . Visibility state (onStart() - onStop()): during this state the Activity is visible and the user can interact with it. The system can invoke these methods multiple times during the life cycle of the Activity Foreground state (onResume() onPause()): during this state the Activity is visible and on top of the other. These methods are invoked frequently, such as when you put in stand-by mode the terminal the onPause() method is invoked and the the onResume () method is invoked when then it wakes up. Activity LifeCycle
  11. 11. Activity and Intent The management of the Activity in the stack is based on the implemented navigation. The classical management is the following: Back Stack
  12. 12. Activity and Intent An Activity can be destroyed by the system for 2 main reasons: Configuration changes Every time a configuration changes the Activity is destroyed and recreated. The configurations that generate this process are the following: Locale: The user has modified the language of the terminal, then the application must necessarily take all references to localized resources for the new language. Orientation: The user has rotated the device (portrait2lanscape or landscape2portrait). To properly display the graphical interface, the application must be loaded at runtime resources for the new configuration. ScreenSize: As orientation, but built from Android 3.0 to change aspect ratio of the Tablet. It's possible to inhibit this behavior by inserting the following attribute to the Android Manifest node: android:configChanges=||... Activity Recreation Config Changes
  13. 13. Activity and Intent In this case, the application life cycle is not met and therefore does not invoke the following methods: onDestroy() onCreate() It therefore does not create a new instance of the Activity and layout are those added in OnCreate() method In stead the following method is invoked(which is not part of the life cycle of the Activity and then it's invoked only in this case): onConfigurationChanges(Configuration newConfig) In this case, if you want to force the loading of new resources is necessary to recall them as if you were recreating the entire Activity (as in onCreate() method you have to invoke the setContentView(int layoutRes) method) Pattern: it is preferable to use the entire life cycle of the Activity except in case this should be closed for a rotation of the terminal. Activity Recreation Config Changes
  14. 14. Activity and Intent Memory Leak This occurs when the memory of the terminal is not enough to handle Activity and Services in running processes. The system, therefore, destroys Contexts running according to the Stack and priorities: The services have higher priority than the Activity Latest Activity have higher priority than the first based on how they have been included in the Stack. When the Activity is destroyed, you lose all reference to the Context and to all of its instance variables. However, if the user presses the Back button to restore a previously created Activity it is re-created following the classic life cycle. To manage internal data and restore the state of the Activity, the APIs provide two methods: onSaveInstanceState(Bundle outState): called just before onDestroy() it is used to save data in the Bundle. onRestoreInstanceState(Bundle inState): called immediately after onCreate () it returns the data saved in Bundle with onSaveInstaceState(). The same bundle is passed to the method onCreate (Bundle state). Activity Recreation Memory Leak
  15. 15. Activity and Intent Activity Recreation Memory Leak
  16. 16. Activity and Intent You can set the system to handle the launch of an Activity. Each Activity is created in a task. There are 4 ways to start an Activity with regard to Task created: Standard (n:n): it is the default, an Activity can be instantiated multiple times, each instance can belong to a different task from the others, each task can have multiple instances of the same Activity; SingleTop (1:n): if there is already an instance of this Activity on top of the current task, this is called in the foreground and the implementation of the onNewIntent() method is performed. An Activity can be instantiated multiple times, each instance can belong to a different task from the others, each task can have multiple instances of the same Activity; SingleTask (1:n): if there is already an instance of this Activity on top of the current task, this is called in the foreground and the implementation of the onNewIntent() method is performed, otherwise it creates a new task and a new instance of the Activity. There can be only one instance of the Activity. SingleInstance (1:1): the instance of the Activity is the only member of the Task. Activity Launch Modes
  17. 17. Activity and Intent The same result can be achieved by adding a flag to the explicit Intent that asks the system to start the Activity: FLAG_ACTIVITY_NEW_TASK: same behaviour of singleTask FLAG_ACTIVITY_SINGLE_TOP: same behaviour of singleTop FLAG_ACTIVITY_CLEAR_TOP: if an instance of the activity exists in the current Task it is restored by destroying all the others and then it's on top of the stack FLAG_ACTIVITY_CLEAR_TOP and FLAG_ACTIVITY_NEW_TASK are often used together to destroy all of the Activities until the required one regardless of the task being executed (eg. used to return to the HomeScreen). It is common to put all the Activities inside the same Task to simplify navigation to observe the pattern of the Back Button. Activity Launch Modes