Presentation is loading. Please wait.

Presentation is loading. Please wait.

Android 5: Activities Kirk Scott 1. Introduction The title of this set of overheads is something of a misnomer It is not easy to encompass the contents.

Similar presentations

Presentation on theme: "Android 5: Activities Kirk Scott 1. Introduction The title of this set of overheads is something of a misnomer It is not easy to encompass the contents."— Presentation transcript:

1 Android 5: Activities Kirk Scott 1

2 Introduction The title of this set of overheads is something of a misnomer It is not easy to encompass the contents of the unit in a single word, so for lack of a better alternative, the word describing a central concept was chosen 2

3 This set of overheads covers more background on the overall structure of Android apps The earlier examples were very simple and focused on the basic nuts and bolts The new background includes higher level concepts 3

4 The overheads then take up another example app from the tutorials This is a repetitive, cyclical approach rather than an everything at once approach Parts of the new example will repeat the basics The new example will also include and illustrate the new, higher level concepts 4

5 This is a list of the sections of this set of overheads: 5.1 Contexts 5.2 Activities 5.3 Fragments 5.4 Intents 5.5 Services 5.6 The Android Manifest File 5.7 The Third Example 5

6 5.1 Contexts 6

7 The Android API contains a class named Context, android.content.Context Any Android app does have a context, but in simple apps the context may not appear explicitly in the code In a very broad and non-technical sense, an app’s context is the container, or access point for all of the “things” that belong to that app 7

8 The “things” accessible through the context include resources belonging to the app, like files or allocated devices The “things” also include services which the app makes use of Services will be discussed further in a subsequent section 8

9 For the time being, if you recall the boxes within boxes development analogy for programming, you can think of the context as being the biggest of the boxes containing components related to an app 9

10 Contexts and Activities There is also one more thing to understand about the context up front—which also depends on something which hasn’t been fully discussed yet In the hierarchy of Android classes, there is an Activity class The Activity class is the topic of the next section In a certain sense, the idea of an activity is the basic building block of all apps—that’s why it’s the title for these overheads 10

11 A key idea behind apps is that they can consist of multiple activities So another way of describing the context is that it is the common container or access point for all of the different activities belonging to a single app 11

12 The Activity class is related to the Context class in the Android API inheritance hierarchy The Activity class is a subclass of the Context class That means that for any given app, its context will actually exist as an instance of the Activity class This works because the subclass “is a kind of” the superclass 12

13 To emphasize: The overall activity of an app is the context for everything else in the app We have seen examples with a single activity When MyEchoApp is run, for example, MainActivity is brought into existence MainActivity extends Activity At run time, an instance of MainActivity is constructed—an instance of a kind of Activity comes into existence 13

14 As an activity, it is an instance of a subclass of Context Because MyEchoApp is a single activity app, it is its own context If the app contained other activities, the main activity would also be the context for those other activities 14

15 Using the Context in Order to Understand What it is We don’t need to use the app context yet, but in order to better understand the concept of the context and the overall structure of apps, it’s useful to see how the context can be used In general, it can be used to acquire information about the app, or handles on things belonging to the app, within the app code itself 15

16 In order to use the context, first you have to retrieve a reference to it Here is a call on the implicit parameter that would appear in the code for, which retrieves the app context: Context myContext = getApplicationContext(); Note that this will be a superclass reference to the activity which is the context 16

17 These are some of the things, more specifically, that you can access and manage through the context: Application resources, such as strings, graphics files, etc. Other directories and files belonging to the application, including SQLite databases Application permissions, preferences, and services 17

18 Because MainActivity is an instance of a subclass of Context, you can call context methods directly on the implicit parameter These are some of the methods: getResources() getSharedPreferences() getAssets() 18

19 Recall that if you declare a string in strings.xml, successful compilation will result in handle for the string in Here is an example of acquiring access to an app resource within app code by using a context method: String greeting = getResources().getString(R.string.hello); 19

20 Summary of Contexts In summary, even though we don’t have a particular practical use for the context yet, it is important to understand the concept: The context is the central organizing principle underlying app development 20

21 5.2 Activities As already stated, activities are the basic building blocks of apps Apps are classes which extend Activity From the top-down perspective, the MainActivity, which is the app’s context, is central But from a bottom-up perspective, other, component activities, are central As we’ll see, there is another layer under activities, fragments, but it is the activity that is regarded as the basic concept, not the fragment 21

22 Screens and Activities Even if you haven’t designed and built multi- screen applications yet, as a user, you’re familiar with applications that transition from one screen to another An easy initial way to understand how an app may consist of multiple activities is that each screen may be coded as a separate activity 22

23 The explanatory example which follows is taken from: Darcey, Lauren and Shane Conder Android Wireless Application Development Volume I: Android Essentials Third edition Addison Wesley, 2012 23

24 Consider a game which consists of the following screens: Startup or splash Main menu Game play High scores Help/about A hierarchy chart of the corresponding activities is shown on the following overhead 24

25 25

26 Activities are more than just screens in an application Activities are tied up with the idea of multiprocessing Multiple applications may be in the run state on a device at a given time Each application may consist of multiple activities 26

27 Out of all of the activities of all of the running applications, only one activity can be in the foreground at a time This is the activity that’s visible on the screen Other activities may be in various states in the background, some running, some not The Android operating system has to manage all of the activities 27

28 From operating systems you may be familiar with circularly linked lists for task scheduling You may also be familiar with the concept that during the execution of a single process, a sequence of method (or subroutine) calls is managed in a stack 28

29 Android activities are managed using a stack discipline The new activities are pushed onto the top of the stack Only the topmost activity can run The rest have to wait for activities above them to complete and be removed 29

30 Activities at the bottom of the stack can be destroyed if there is too much resource contention A simple diagram of the situation is shown on the following overhead 30

31 31

32 Activities have lifecycles, similar to the way processes or threads in an operating system have lifecycles In other words, as the app they belong to runs, or as system resources are claimed, they enter and leave various different states 32

33 Transitions occur as the result of calls to methods The Activity class contains these methods You might not call the method directly on yourself These methods tend to be used in callback sequences 33

34 Remember examples of callbacks: You call repaint(), which is inherited, and it calls paintComponent(), which you implemented Or, something happens in the user interface, causing a method in a listener in your code to be called, like mouseClicked() You may inherit the default implementations of the methods of interest, and you may override them 34

35 This is a list of the most significant of the lifecycle methods in the Activity class: onCreate(Bundle savedInstanceState)—note that this is the moral equivalent of the main() method, which we have seen in the onStart() onRestart() onResume() onPause() onStop() onDestroy() 35

36 The potential changes in an activity’s lifecycle can be shown in a diagram reminiscent of a state transition diagram Such a diagram is shown on the following overhead 36

37 37

38 Activity lifecycles become important in multiple activity apps, and become even more important in environments where multiple apps are running concurrently Eventually it may become necessary to write code to handle particular transitions gracefully 38

39 It is too soon to be concerned with the details, but one additional aspect of this can be mentioned now Note that the onCreate() method takes a parameter The type of the parameter is Bundle The Bundle class is designed to hold the state of an activity 39

40 If an activity is being created for the first time, the Bundle parameter can be null A class that extends Activity can implement (override) the onSaveInstanceState() method When the system kills an activity, it can call this method and save the custom state into an instance of Bundle 40

41 Killing an activity is not as drastic as destroying it Lazarus-like, a killed activity can be brought back to life with a call to onCreate() In this case, the Bundle containing the state saved when it was killed is passed in as a parameter 41

42 5.3 Fragments In early versions of Android, it was usually the case that one activity corresponded to one screen in the app This is a straightforward way of dealing consistently with a world consisting of devices with small screens However, with the advent of tablets, TV’s, and other devices in the Android world, a different model became useful 42

43 The general idea is this: A fragment is a part of the functionality associated with a screen or part of the user interface A fragment has to be associated with an activity But a fragment can be associated with different activities at different times 43

44 This model makes the following possible, for example: On a device with a small display, there is an activity which manages multiple screens, each screen with one fragment on it On a device with s large display, there may be fewer separate screens, or even just one screen The screen has an activity, and that activity has many different fragments on it 44

45 The design idea is illustrated on the following overhead using a music app as an example The upper part of the figure shows how you might traverse four screens on a device with a small display The lower figure shows how it might be convenient to just include all of the fragments on one screen with a large display 45

46 46

47 The fragment idea is encapsulated in the Fragment class in the Android API, 47

48 5.4 Intents There is another class in the Android API, the Intent class, android.content.Intent Intents are a critical element of the structure of a multiple-activity app Intents are the mechanism used for transitioning between one activity and another 48

49 Certain kinds of transitions may be manageable with direct calls in one activity to start or stop another activity In simple cases, the programmer can code calls to startActivity() and finish(), for example A slightly more complicated version of this approach would involve calls to startActivityForResult() and onActivityResult() 49

50 However, the most flexible way to transition between activities is with intents If you’ve had operating systems, you may see some similarities between intents and the concept of message passing In general, you can describe the use of intents as asynchronous rather than synchronous 50

51 In other words, the use of the intent mechanism is a request to the Android system to start an activity It is not a direct call of a method on that activity This supports the fact that various activities are currently in existence, in various states, on the stack 51

52 Not only do intents support this form of activity management Their flexibility comes from some additional features: An intent may in effect be a broadcast message In other words, it may be a request that could be satisfied by more than one activity, and the Android system can select one of several to satisfy it 52

53 An intent can also be structured as a request that can be satisfied by an activity belonging to another app In other words, in an asynchronous way, it can be something similar to a remote procedure call The topic of services hasn’t been covered yet, but an intent can also be structured as a request to a service provider 53

54 Launching an Activity Using an Intent Within an application’s context, you can call a startActivity() method In other words, within one activity, you can make a call to this method on the implicit parameter The startActivity() method takes an intent as a parameter The intent is constructed with two parameters: 1. A context 2. An activity class 54

55 Here is an example of a call to startActivity(): startActivity(new Intent(getApplicationContext), MyDrawActivity.class)); The call getApplicationContext() on the implicit parameter gets the current context The syntax MyDrawActivity.class is a way to refer to the class code for the class in question 55

56 What does it mean to launch the specified? Think back to the example code we’ve seen before The activity was coded in An activity file doesn’t contain a main() method It contains an onCreate() method In effect, launching the activity means creating it 56

57 When the activity is (the one most newly) created, it is at the top of the activity stack and it’s in the foreground At that point, whatever is defined in its activity_main.xml file will be displayed on the screen The activity will be alive, and clicking on its components, like the button, will trigger the running of the activity’s methods, like sendMessage() 57

58 Intents and Bundles As noted earlier, the call to onCreate() for an activity takes a Bundle as a parameter The Bundle can contain state information, for example, the state of an activity before it was last killed If an activity is to be started as a result of an intent, it is also possible to add a Bundle of data to the intent which can be used in the activity when it’s started 58

59 The putExtra() method of the Intent class accepts data items to be put into the Bundle The code snippet on the following overhead shows two things: 1. The use of putExtra() 2. The fact that the current context and the activity to be started can be specified as construction parameters to the Intent This means the call to startActivity() only needs the intent as its parameter 59

60 Intent myIntent = new Intent(this, MyActivity.class); Intent.putExtra(“SomeStringData”, “a string”); startActivity(myIntent); There are various strings such as “SomeStringData” defining the types of extras that can be put into Bundles There is no need to go into all of them here 60

61 If an activity has been started with an Intent such as the one shown above, then the following kind of code can appear in the onCreate() method: Bundle myExtras = getIntent().getExtras(); If(myExtras != null) String myString = myExtras.getString(“SomeStringData”, “default value”); Note that the Bundle information has to be retrieved inside the method. It isn’t passed as a parameter to onCreate() 61

62 Intents and Navigating among Activities in Applications We haven’t seen how to create complex user interfaces in Android yet, but the idea is familiar The items in a menu may be coded to launch different activities using intents This would support a hierarchical, top down graphical user interface organization Any graphical widget, like a button, may be coded to launch an activity This would support horizontal transitions between screens/activities Any application can mix and match 62

63 Predefined Intents The acronym URI stands for universal resource identifier There is a corresponding class in Android, Uri These are used for various purposes and are brought up here because they’re needed in the next example 63

64 It is possible to create an intent with a predefined action and a URI The following code snippet illustrates this: Uri myNumber = Uri.parse(“tel:01234567890”); Intent myIntent = new Intent(Intent.ACTION_DIAL, myNumber); startActivity(myIntent); 64

65 What is important about the last example is not phone dialing specifically, or the syntax of the intent It illustrates the following: 1. There are many predefined intents in Android, that are designed to work with features that commonly exist on Android devices 65

66 2. This concretely shows how your activity can trigger a (system) activity that doesn’t belong to your application You don’t have to reinvent the wheel And the system makes it possible to integrate system level functionality into your own handcrafted applications 66

67 Intent Filters It’s way too soon to be worried about explicitly making use of intent filters, but it’s worth knowing the concept at this point The idea is that an app may broadcast an intent The Android system uses intent filters to try to determine which of several activities may be eligible or able to take action on the intent 67

68 5.5 Services At the present point, services are still a pretty remote topic, but it won’t hurt to mention them briefly There is a class, Service, Instances of the Service class contain programmer written code Roughly speaking, in a graphical app, an activity corresponds to something that happens on the screen 68

69 Roughly speaking, a service may have these characteristics: 1. It doesn’t have a user interface—it provides a service to activities 2. The service provided may be used by more than one activity In other words, one way of thinking of a service is as a background process 69

70 If the need of some processing by an app isn’t particularly time sensitive And if doing the processing in the foreground would tend to affect app performance Then offloading the processing into a service might be a good idea When processing is done as a service, it is scheduled outside of the activity lifecycle mechanism 70

71 These are some concrete examples of things that might be usefully coded as services: Regular, routine checks for updates to information at some network location Data uploading or downloading which isn’t time sensitive—can be done when a device is otherwise idle—no foreground activities are currently being used Local processing, preparing, storing data, etc., can also be done when the device is otherwise idle 71

72 5.6 The Android Manifest File This will be the last nuts and bolts section before considering the next example app This is different from the foregoing sections It’s not about code internals It’s back to an XML file associated with an app which you can look at and edit in the development environment 72

73 There was no need to consider it earlier—we effectively just accepted the default However, having now considered such things as activities and intents, it’s now possible to take a look at a manifest file and have some understanding of what it’s about 73

74 You may recall that when you made jar files you had to define manifest files Likewise, when you make Android apps that result in apk’s (application package files) you have to have a manifest file The manifest file is the place where many characteristics of the app are specified 74

75 To find the manifest file for an app, scroll down to the bottom of the project explorer in Eclipse You’re looking for AndroidManifest.xml The manifest file will be nearly the last file listed If you double click on it, you will enter a wizard- like interface Clicking on the tab at the bottom of the editor screen for AndroidManifest.xml will bring up the XML code 75

76 AndroidManifest.xml for MyEchoApp The complete contents of AndroidManfest.xml for MyEchoApp is shown, part by part, on the following overheads Since MyEchoApp is rock-bottom simple, obviously, this is an example of a rock-bottom simple manifest file 76

77 The manifest file identifies the app 77

78 The manifest file specifies the minimum version of Android that the app will run on, as well as the version of Android that the app was targeted for 78

79 The manifest file specifies whether the app can be backed up and the icon used to represent it, its label, and its theme 79

80 The manifest file lists every activity in an app This app only has one activity, but a more complicated app would have more The name and label are specified for each activity 80

81 The manifest file gives an intent-filter with an action and a category for each activity in an app For this simple app there is just one activity with no transitions between activities is it—and if an intent is directed at this activity, it should be launched 81

82 5.7 The Third Example 82

83 Introductory Blah blah blah The example that will be presented now is taken directly from the online tutorials, as of August of 2013 This example is not much more complicated than MyEchoApp and large parts of it will simply be repetition of the basics 83

84 On the other hand, this example does do something slightly different More importantly, the app is structured in such a way that it illustrates the use of activities and intents 84

85 In addition to the fact that it’s pretty easy to lift the work from the tutorials, there’s another reason for doing so Not only is it useful to see the app itself It’s also useful to see the preferred order for creating the elements of the app, as illustrated by the tutorial 85

86 How Interfaces are Structured Android interfaces be visualized as boxes within boxes The organizing classes in Android are View and ViewGroup The figure shown on the following overhead illustrates the idea 86

87 87

88 activity_main.xml The layout of an app is created using XML in activity_main.xml The syntax of the XML corresponds to the idea of Views and ViewGroups The complete activity_main.xml file for this example app is shown on the following overhead The point at this stage is that the LinearyLayout is a ViewGroup and the EditText and Button widgets are Views 88

89 89

90 What appears in the file should look pretty familiar If you put these contents into the activity_main.xml file in the development environment, you will get two error messages: Couldn’t resolve resource @string/edit_message Couldn’t resolve resource @string/button_send 90

91 You have to start entering code somewhere, so these error messages are to be expected They can be fixed right away by adding these lines of code to activity_main.xml Edit message Button send 91

92 Having the sendMessage() Method Start a New Activity Recall that sendMessage() is the method triggered by clicking the button in the app This sendMessage() implementation has some things in common with MyEchoApp, but it also diverges In the body of sendMessage() an intent is created to start a second activity Then it’s necessary to create the code for that second activity 92

93 The complete code for the sendMessage() method is shown on the following overhead After that, it will be run through line-by-line Note that if you put this into, it will be riddled with errors This is the consequence of developing in the order chosen 93

94 import android.view.View; … public void sendMessage(View view) { Intent intent = new Intent(this, DisplayMessageActivity.class); EditText editText = (EditText) findViewById(; String message = editText.getText().toString(); intent.putExtra(EXTRA_MESSAGE, message); startActivity(intent); } 94

95 The first line shown is this import: import android.view.View; The method has a parameter of this type, so the class is required 95

96 This is the signature of the method: public void sendMessage(View view) The idea is that the button where the click originates is a view, and it is this view which is passed to the method when it is called This is reminiscent of passing the event as a parameter to an event handler in Java 96

97 Here the intent is being created Its first parameter is the context, the implicit parameter, this, namely the current activity, which is MainActivity Intent intent = new Intent(this, DisplayMessageActivity.class); The second parameter is the second activity of the app We will turn our attention to creating the code for this after finishing sendMessage() 97

98 These lines of code should look familiar from MyEchoApp EditText editText = (EditText) findViewById(; String message = editText.getText().toString(); First we get a handle on the EditText view Then we get whatever text it contains 98

99 Now the fun starts Instead of simply echoing the text into another view, we put the text into the Bundle belonging to the intent using the putExtra() method intent.putExtra(EXTRA_MESSAGE, message); 99

100 The EXTRA_MESSAGE constant is taken directly from the tutorial—but when I copied the code over it didn’t work The way its used, EXTRA_MESSAGE has to belong to the current activity, ActivityMain I checked the API documentation, and this is not a constant defined in the Activity class— so ActivityMain doesn’t have it by default— which explains the build error 100

101 I may have overlooked something and this may not be an ideal solution, but I solved the problem by putting this declaration in public static final String EXTRA_MESSAGE = "HiHo"; Obviously, the content of the string doesn’t matter The existence of the named constant is what matters It will be used in the second activity to refer to the message that was put in the bundle 101

102 Finally, from sendMessage() in MainActivity, we call startActivity, passing in the intent which contains the second activity of the app, DisplayMessageActivity startActivity(intent); 102

103 In order to get a clean compile, remember that you’ll have to import the classes you’re using These might be among the needed imports: import; import android.widget.TextView; import android.content.Intent; 103

104 DisplayMessageActivity It would be possible to create a new activity from scratch in the development environment Just save under the new name in the src folder Delete sendMessage(), keeping onCreate() and onCreateOptionsMenu() 104

105 Then add setupActionBar() and onOptionsItemSelected() At this point you realize that you should use the wizard in the development environment You need model code for these new methods—and if you use the wizard, it will create this code for you 105

106 Using the Wizard to Create an Activity In the Eclipse environment, the leftmost tool in the toolbar will be “New” Do not confuse this with File|New in the menu In the New tool, select Android, Android Activity A screenshot of the wizard is shown on the following overhead 106

107 107

108 Select the Blank Activity Template and click Next That takes you to the step in the wizard shown on the following overhead 108

109 109

110 Accept Blank Activity and click Next That takes you to the last step in the wizard Enter an activity name of DisplayMessageActivity and certain other fields will auto-complete Among the auto-completions is a layout name of activity_display_message—so you know what the xml layout file is going to be for this activity 110

111 Do not check launcher activity For this example, being developed under the name I’ve given it for these overheads, this is the Hierarchical Parent: Tutorialexampleforoverheads5.MainActivity Leave Navigation Type set to None The following overhead shows a screenshot of these choices in the wizard 111

112 112

113 When you click next, the file will be created and it will contain the needed methods In particular it will contain the setupActionBar() and onOptionsItemSelected() methods, which we haven’t seen before 113

114 This is another note on what the development environment does for you: It automatically creates the required entry for this activity in the AndroidManifest.xml file If you weren’t using the development environment, you would have to master creating XML code such as that shown on the following overhead 114

115 Not surprisingly, the contents of the.xml file reflect the values specified in the wizard 115

116 activity_display_message.xml The activity creation wizard brings the layout file for that activity into existence When I did this, I discovered that the.xml file was a copy the layout file of one of my previous examples I don’t know if this is normal but it didn’t cause any harm This will be mentioned again when explaining the code 116

117 Code Functionality for DisplayMessageActivity Fundamentally, the new activity has to receive the intent, get the text from it, and display it It turns out that the new methods in the activity are not needed in order to complete this simple app The work is done in the onCreate() method for this activity The complete onCreate() method of is shown on the following overhead 117

118 @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Get the message from the intent Intent intent = getIntent(); String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE); // Create the text view TextView textView = new TextView(this); textView.setTextSize(40); textView.setText(message); // Set the text view as the activity layout setContentView(textView); } 118

119 For the sake of completeness, the method is shown again, part-by-part, on the following overheads 119

120 From our perspective this is just copy/paste housekeeping We’ve seen the pattern of calling and then adding lines of code which customize xyz() for the subclass in Java @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); 120

121 The idea that you have to get the message before you can display it is familiar from MyEchoApp and all echoing type applications The difference here is that the message comes from the intent—and this is where you make use of the statically declared constant in MainActivity as a handle on the message of interest Intent intent = getIntent(); String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE); 121

122 Here is the spot where create the view that will appear on the new screen You then put the message in it // Create the text view TextView textView = new TextView(this); textView.setTextSize(40); textView.setText(message); 122

123 When activity_display_message.xml was created, that’s when the new activity was defined as having its own screen What you finally have to do is make the newly created text view be the text view for this layout // Set the text view as the activity layout setContentView(textView); 123

124 I mentioned under activity_display_message.xml that the system apparently provided a copy of one of my previous layout files—which happened to have a text view in it This code worked fine with that layout The text view in the layout was replaced with the text view from this code, and when the app ran it displayed the right message 124

125 What it Looks Like The following overhead shows what the app looks like in the emulator when some sample text has been entered into it 125

126 126

127 Ta-Da The following overhead shows the emulator after the button has been clicked A new screen is displayed and it contains the text that was entered 127

128 128

129 The End 129

Download ppt "Android 5: Activities Kirk Scott 1. Introduction The title of this set of overheads is something of a misnomer It is not easy to encompass the contents."

Similar presentations

Ads by Google