Presentation is loading. Please wait.

Presentation is loading. Please wait.

Activities and Intents Chapter 3 1. Objectives Explore an activity’s lifecycle Learn about saving and restoring an activity Understand intents and how.

Similar presentations


Presentation on theme: "Activities and Intents Chapter 3 1. Objectives Explore an activity’s lifecycle Learn about saving and restoring an activity Understand intents and how."— Presentation transcript:

1 Activities and Intents Chapter 3 1

2 Objectives Explore an activity’s lifecycle Learn about saving and restoring an activity Understand intents and how they are used with multiple activities Become familiar with passing data between activities Implement applications that require basic animation activity transitions Study scene transitions 2

3 Overview Activity Units or building blocks of Android applications in that an app is made up of zero or more activities Container for UI, holding UI as well as the code that runs it; controller in MVC Q: how to associate a UI with an activity? Run on its own VM Q: Why? Advantages/disadvantages? Intent Glue for connecting activities that run on different VMs 3 VM Activity 1 Activity 2 VM intent

4 Activity Declaration Defined as a subclass of android.app.Activity Declared in the AndroidManifest.xml file Q: Why? to be accessible to the system Use the tag Must be a child of the element One designated as the main activity … 4

5 Activity Management In most cases, apps are composed of multiple activities. With one serving as the main (entry) activity Often loosely connected to each other Information passed from one activity to another But remain distinct and separate in every other way 5

6 Activity Stack The activities in an application are managed by the Android system using an activity stack (similar to call stack). Each time a new activity starts, the previous activity is paused and its status is preserved. New activities are pushed onto the top of the stack and become the running activity. VM A1 invoke VM A2 VM A3 invoke A1 A2 A3 6 running paused activity stack

7 Activity Lifecycle Determine an app’s overall lifecycle Managed by the Android system by providing seven callback methods (defined in Activity class), beginning with the creation of the activity and ending with its destruction onCreate() onStart() onResume() onPause() onStop() onRestart() onDestroy() 7 *Read API doc of the Activity class

8 Lifecycle Methods onCreate(): when created first or recreated if a paused or stopped activity requires destruction due to a system need for more memory, the activity will need to be recreated again. onStart(): when becoming visible; always to be called after onRestart() onStop(): when becoming no longer visible to the user onDestroy(): performs final cleanup prior to an activity’s destruction 8

9 9

10 Lab 3-1 Activity Lifecycle App Pages 193-202 Or extend the Timer App by overriding lifecycle methods to find sequences of calls when: 1.The app is first launched 2.The Home button is clicked 3.It is restarted from the launcher 4.The Previous button is clicked 5.It is restarted from the launcher 6.The device is rotated (CTRL-[ALT]-F11 on AVD) 10

11 Saving and Restoring an Activity When an activity is paused or stopped, the state of the activity is retained When the system destroys an activity in order to recover memory, the memory for that activity object is also destroyed 11

12 Saving and Restoring (Cont.) A Bundle is a container for the activity state information that can be saved putInt(String, int) getInt(String), … Recover the saved state from the Bundle that the system passes to the activity onCreate(Bundle) and onRestoreInstanceState(Bundle) Check whether the activity’s state (stored in the Bundle object) is null before you attempt to read it If it is null, then the system is creating a new instance, instead of restoring a previous one that was destroyed 12

13 Screen Orientation Change Activity behavior when orientation changes onCreate -> onStart -> onResume... onDestroy <- onStop <- onPause -> onCreate -> onStart -> onResume... What about activity state? Only named views (via the android:id attribute) in an activity will have their states persisted. 13

14 Screen Orientation Change Activity behavior when orientation changes onCreate -> onStart -> onResume... onDestroy <- onStop <- onPause -> onCreate -> onStart -> onResume... What about activity state? Only named views (via the android:id attribute) in an activity will have their states persisted. 14

15 Persisting State Information Two possible events upon activity kills onPause(): always fired onSaveInstanceState(Bundle): not fired when activity is unloaded from the stack (e.g., when the Back button is pressed; no reason to store) *Bundle from onSaveInstanceState is also available to onCreate(Bundle) 15 protected void onSaveInstanceState(Bundle outState) { outState.putString("ID", "1234"); super.onSaveInstanceState(outState); // Q: why? } // called when activity is re-recreated, following onCreate(). protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); // Q: why? String ID = savedInstanceState.getString("ID"); }

16 Lab: Improved Timer App Extend the Timer app to handle screen orientation changes, i.e., not to reset to 0 Use onSave/RestoreInstanceState() May need to extend the TimerModel class Lifecyle: onPause -> onSave* -> onStop -> onDestroy --------+ onResume <- onRestore* <- onStart <- onCreate <-+ 16

17 Intents Glue for connecting activities (possibly from different apps) that may run on different VMs Apps built with multiple activities need to utilize the Intent class. This class provides the framework for the navigation from one screen to another. An Intent object is a message from one component to another component, either within the app or outside the app. Designed to communicate messages between three application core components: Activities Broadcast receivers Services 17

18 Explicit vs. Implicit Intents Explicit Specify a specific activity class Only for activities defined within the same app Implicit Specifies an action along with data For activities defined within or outside the app 18 startActivity(new Intent(this, SecondActivity.class); startActivity(new Intent(android.content.Intent.ACTION_DIAL, Uri.parse("tel:+915-123-4567")));

19 Linking Activities with Explicit Intents 1.Create a new activity, say SecondActivity, including its UI 2.Declare it in AndroidManifest.xml 3.Start the new activity 19 <application... … // from main activity public void onClick(View view) { startActivity(new Intent(this, SecondActivity.class)); } *Q: startActivity similar to method call?

20 Implicit Intents Unlike an explicit intent, an implicit Intent does not name a specific component. It declares a general action to perform, which allows a component from another app to handle it. When an implicit intent is created, the system locates the appropriate target component by comparing the contents of the intent to an intent filter. Intent filters are declared in the manifest file of other apps located on a given device. When the intent has found a match with an intent filter, the system starts that component and delivers the intent object to it. 20

21 Declaring Intent Filters 21 <application... … Action: to be called by other activities Convention: Use reverse domain name Category: group activities User-defined categories possible DEFAULT: to be called using startActivity()

22 Linking with Implicit Intents 22 public void onClick(View view) { startActivity(new Intent("edu.utep.cs.cs4330.PLAY")); } Can add a category to an intent to find an activity belonging to that category, e.g., Intent i = new Intent("..."); i.addCategory("edu.utep.cs.cs4330.FUN_GAME"); Resolving intent filter collision What happen if there exist more than one activities with the same intent filter name? => Android OS will let you select one by displaying a selection dialog

23 Calling Built-in Apps Using Intents Use intents to call activities from other apps, including built-ins, e.g., call a person using the Contacts app. Benefits? Consistent user experience Avoid building another duplicate app How? In intent, specify action along with data Intent resolution: process performed by Android OS to look for all activities that are able to satisfy an intent In sum, an action-and-data pair describes the operation to be performed 23

24 Standard Activity Actions 24 ActionExample Browse a website Intent i = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("http://www.cs.utep.edu"); startActivity(i); Dial a number startActivity(new Intent(android.content.Intent.ACTION_DIAL, Uri.parse("tel:+915-123-4567"))); Show a map Intent i = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("geo:31.7677,-106.502"); startActivity(i); Choose a contact Intent i = new Intent(android.content.Intent.ACTION_PICK); i.setType(ContactsContract.Contacts.CONTENT_TYPE); startActivityForRessult(i, requestCode); *Many predefined actions and categories; read API doc of the Intent class. *Uniform Resource Identifier (URI): a string to identify a name or a resource, e.g., URL

25 Lab: Launcher App Create an app with two buttons for launching: Timer app from previous lab Built-in Dialer (Phone) app Hint: An activity may have more than one intent filter. 25

26 Passing Data Between Activities Issues Activities run on different VMs (no global variables) Asynchronous invocation (no return point) Solution  : Piggyback on intent  : Use intent and callback 26 VM Activity 1 Activity 2 VM ?

27 Sending Data to Invoked Activity Piggyback on the intent 27 // calling activity Intent i = new Intent("edu.utep.cs.cs4330.PLAY"); Bundle extras = new Bundle(); extras.putString(“course", “CS 4330"); i.putExtras(extras); startActivity(i); // called activity String course = null; Bundle extras = getIntent().getExtras(); if (extras != null) { course= extras.getString(“course"); } *Numerous helper methods defined on Intent, e.g., putExtra and getStringExtra. Bundle extras intent Activity getIntent() Intent getExtras()

28 Returning Results Use callback (Observer pattern) Q: Why request code? 28 // calling activity Intent i = new Intent(“edu.utep.cs.cs4330.PLAY"); startActivityForResult(i, 1); // 1: request code protected void onActivityResult(int requestCode, int resultCode, Intent result) { if (requestCode == 1 && resultCode == RESULT_OK) {... result.getData().toString()... // Uri getData() } // called activity Intent result = new Intent(); result.setData(Uri.parse("Here's the result!")); // Intent setData(Uri) setResult(RESULT_OK, result); finish(); // close the activity and give control to the invoking activity

29 Activity and Intent Classes 29 Bundle extras intent Uri Activity getIntent() onActivityResult(int, int, Intent) setResult(Intent) finish() Intent setExtras(Bundle) getExtras() setData(Uri) getData() data result

30 Lab 3-3 Auto Loan Calculator Pages 225-243 App consisting of two activities 30

31 Lab: MyGrade App 31 App to inquire CS 4330 grade Two activities: MainActivity and HelperActivity Source files from course website

32 Activity Transitions Judicious use of animation can enhance the usability of an app by providing engaging and dynamic UI. Basic transition Custom transition animation between activities Use overridePendingTransition() Entering/exiting animation defined in XML Lab 3-4: Flip Cards Scene transition Since KitKat (Android 4.4) Lab 3-5: Pieces of a Painting 32


Download ppt "Activities and Intents Chapter 3 1. Objectives Explore an activity’s lifecycle Learn about saving and restoring an activity Understand intents and how."

Similar presentations


Ads by Google