android 6: activities kirk scott 1. 2 3 4 introduction the title of this set of overheads is...
Post on 02-Jan-2016
215 Views
Preview:
TRANSCRIPT
1
Android 6: Activities
Kirk Scott
2
3
4
5
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
• For lack of a better alternative, Activities, the word describing a central concept in the unit, was chosen
6
• 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 of Android development
• The overheads then take up another example app from the tutorials
7
• Parts of the new example will repeat the basics
• Parts of the new example will also include and illustrate the new, higher level concepts
• This is a repetitive, cyclical approach rather than an everything at once approach
8
• It also turns out that some of the important concepts talked about in this unit do not appear in the example
• What you get now is an introduction to those concepts
• Examples applying them will come in later units
9
• This is a list of the sections in this set of overheads:• 6.1 Overview• 6.2 Contexts• 6.3 Activities• 6.4 Fragments (we won’t use this yet)• 6.5 Intents• 6.6 Services (we won’t use this yet)• 6.7 The Android Manifest File• 6.8 The Example
10
6.1 Overview
11
• This overview section shows a UML diagram of certain classes in the Android API
• This is followed by snippets taken from the Android API documentation for the important classes included in the diagram
• The following sections of the unit expand on this and explain in greater detail
12
• The UML diagram on the following overhead includes certain key classes
• The classes ContextWrapper and ContextThemeWrapper are part of the diagram because they are part of the inheritance hierarchy, but their contents are of no interest
• The diagram also includes MainActivity, a class provided by a programmer, not by the Android API
13
14
• These are the classes of interest in the diagram:• Context• Activity• Fragment• Intent• Service• Application• Bundle• MainActivity
15
• The following overheads contain the Class Overview (or the beginning of the Class Overview) documentation for the classes of interest in the Android API
• A few comments are inserted for some of the classes
16
• It won’t be possible to understand everything in the API documentation
• Vocabulary and ideas will be introduced• Explanations will follow in the succeeding
sections
17
The Context Class
• Interface to global information about an application environment.
• This is an abstract class whose implementation is provided by the Android system.
• It allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities, broadcasting and receiving intents, etc.
18
The Activity Class
• An activity is a single, focused thing that the user can do.
• Almost all activities interact with the user, so the Activity class takes care of creating a window for you in which you can place your UI with setContentView(View).
• While activities are often presented to the user as full-screen windows, they can also be used in other ways: as floating windows (via a theme with windowIsFloating set) or embedded inside of another activity (using ActivityGroup).
19
• There are two methods almost all subclasses of Activity will implement:
• onCreate(Bundle) is where you initialize your activity.
• Most importantly, here you will usually call setContentView(int) with a layout resource defining your UI, and using findViewById(int) to retrieve the widgets in that UI that you need to interact with programmatically.
20
• onPause() is where you deal with the user leaving your activity.
• Most importantly, any changes made by the user should at this point be committed (usually to the ContentProvider holding the data).
• To be of use with Context.startActivity(), all activity classes must have a corresponding <activity> declaration in their package's AndroidManifest.xml.
21
The Fragment Class
• A Fragment is a piece of an application's user interface or behavior that can be placed in an Activity.
• Interaction with fragments is done through FragmentManager, which can be obtained via Activity.getFragmentManager() and Fragment.getFragmentManager().
22
• The Fragment class can be used many ways to achieve a wide variety of results.
• In its core, it represents a particular operation or interface that is running within a larger Activity.
• A Fragment is closely tied to the Activity it is in, and can not be used apart from one.
23
• Though Fragment defines its own lifecycle, that lifecycle is dependent on its activity:
• if the activity is stopped, no fragments inside of it can be started;
• when the activity is destroyed, all fragments will be destroyed.
24
• All subclasses of Fragment must include a public empty constructor.
• The framework will often re-instantiate a fragment class when needed, in particular during state restore, and needs to be able to find this constructor to instantiate it.
• If the empty constructor is not available, a runtime exception will occur in some cases during state restore.
25
The Intent Class
• An intent is an abstract description of an operation to be performed.
• It can be used with startActivity to launch an Activity, broadcastIntent to send it to any interested BroadcastReceiver components, and startService(Intent) or bindService(Intent, ServiceConnection, int) to communicate with a background Service.
26
• An Intent provides a facility for performing late runtime binding between the code in different applications.
• Its most significant use is in the launching of activities, where it can be thought of as the glue between activities.
• It is basically a passive data structure holding an abstract description of an action to be performed.
27
The Service Class
• A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use.
• Each service class must have a corresponding <service> declaration in its package's AndroidManifest.xml.
• Services can be started with Context.startService() and Context.bindService().
28
• Note that services, like other application objects, run in the main thread of their hosting process.
• This means that, if your service is going to do any CPU intensive (such as MP3 playback) or blocking (such as networking) operations, it should spawn its own thread in which to do that work.
• More information on this can be found in Processes and Threads.
• The IntentService class is available as a standard implementation of Service that has its own thread where it schedules its work to be done.
29
The Application Class
• Base class for those who need to maintain global application state.
• You can provide your own implementation by specifying its name in your AndroidManifest.xml's <application> tag, which will cause that class to be instantiated for you when the process for your application/package is created.
• [Comment: This is the class named Application, which holds the state of an application. But an application is an instance of the Activity class, not an instance of the Application class.]
30
The Bundle Class
• A mapping from String values to various Parcelable types.
• [Comment: This documentation is pretty mininal. The Bundle class is a container for holding and passing around information about activities. Not surprisingly, you won’t find the word “parcelable” in your average dictionary.]
31
The MainActivity Class
• [All commentary…]• This is the class written by programmers when
they are making an app• The MainActivity class extends Activity• At a fundamental level, an app is an activity
32
• Activity is a subclass of Context• So also at a fundamental level, an app is also a
context• The app overall can serve as a context
containing multiple activities• These activities, in turn, can contain multiple
fragments• (More boxes within boxes)
33
6.2 Contexts
34
• Any Android app has a context, but in simple apps the context may not appear explicitly in the code
• As noted, in fact, an app is a context• 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
35
• 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
36
• 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
37
Contexts and Activities
• An app is a context• But an app is also an activity• 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
38
• 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
39
• The Activity class is a subclass of the Context class
• That means that for any given app, its context will actually come into existence as an instance of the Activity class
• It also means that every activity is a context, and as such, can contain other activities
• Again, this is a case of boxes within boxes
40
• We have seen example apps with a single activity
• When MyEchoApp is run, for example, MainActivity is brought into existence
• Due to the inheritance hierarchy, MainActivity is both an Activity and a Context
• At the end of this unit, a new example will be given which contains multiple activities
41
Making Use of 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
42
• Within a piece of code it is possible to acquire a reference to the context of the current process
• This is sort of a “Who am I?” type call with respect to context
• This call on the implicit parameter that could appear in the code for ActivityMain.java, would retrieve the app context:
• Context myContext = getApplicationContext();
43
• These are some of the things 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
44
• Typically, you don’t have to execute the previous “Who am I?” call
• MainActivity is a subclass of Context, so you can call context methods directly on the implicit parameter in the code for MainActivity
• These are some of the context methods:• getResources()• getSharedPreferences()• getAssets()
45
Using getResources()
• Defining a view in a layout results in an id in R.java
• In earlier examples we saw that you can acquire a handle on such a resource
• This is an example of such a call:
• TextView cup = (TextView) findViewById(R.id.textView1);
46
• Defining a String resource in strings.xml also results in a string definition in R.java
• You can access a resource like this through the context by calling getResources() and calling a method on that
• Here is an example of such a call
• String greeting = getResources().getString(R.string.hello);
• Notice that this doesn’t return an id, it returns an actual string• This allows you to directly access the String “Hello World”,
which belongs to the app and is defined in strings.xml, in the code for your app
47
Summary of Contexts
• The context of an app is the broadest container for the components of an app
• You may call getApplicationContext() and get a direct reference to the context, or you may call methods like getResources() directly on the implicit parameter of an app
• Either way, in the body of the code, you can then call additional methods which will return components of the app
48
6.3 Activities
• Activities are the basic building blocks of apps• If the context denotes a container, then an
activity denotes function• Activities can be further subdivided into
fragments
49
Screens and Activities
• Apps more complicated than the examples given so far can have multiple screens
• A simple multiple screen app can be coded by having a different activity for each screen
• The Darcey and Conder book provides a small example that illustrates this idea, which will be presetned on the following overheads
50
• Consider a game which consists of the following screens:
• Startup or splash• Main menu• Game play• High scores• Help/about
51
• A hierarchy chart of such an app is shown on the following overhead
• The point of the chart is that there is a matchup between the screens and the activities of the app
52
53
The Activity Lifecycle
• Activities are more than just screens in an application
• Screens are just the visual representation of the function of the activities
• So the reality is that a sufficiently complex app will have separate recognizable functions it that can be implemented separately from each other
54
• 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 of these application may consist of multiple activities
55
• 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
56
• From operating systems you may be familiar with the concept of task scheduling
• You may also be familiar with the concept of a sequence of method calls maintained in a stack
• The Android system manages all currently existing activities in a stack
57
• 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• Activities at the bottom of the stack can be
killed if there is too much resource contention• A simple diagram of the situation is shown on
the following overhead
58
59
• Activities have lifecycles, similar to the way processes or threads have lifecycles
• As the app they belong to runs, or as system resources are claimed, activities come into and go out of existence, enter and leave various different states
60
Methods for Activity State Transitions
• Activity state transitions occur as the result of calls to methods in the app code
• The Activity class contains these methods• You might not call the method directly on
yourself• These methods tend to be used in callback
sequences
61
• Remember examples of this:• 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
62
• This is a list of the most significant of the lifecycle methods in the Activity class:
• onCreate(Bundle savedInstanceState)• onStart()• onRestart()• onResume()• onPause()• onStop()• onDestroy()
63
• Practically speaking, we don’t need to know this now, but it may be of some use in thinking broadly about this set of methods
• If you look in the Android API documentation, you will find that they are all declared protected
• Code within the inheritance hierarchy of an Activity class can call them
• Outside code cannot
64
State Transitions of Activities
• 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
• This is taken from Darcey and Conder
65
66
• A similar diagram exists in the API documentation for the Activity class
• It’s shown on the following overhead
67
68
• 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
• In other words, it may become necessary to implement/override some of these methods
69
Killing Activities
• In the foregoing diagrams, onDestroy() marks the utter end of a process
• The system can also kill an activity lower down in the stack if system resources, like memory, start to run out
• 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()
70
Saving and Restoring State
• It can be helpful to save state so that when processes go away or come back to life it’s not time consuming
• A class that extends Activity can implement (override) yet another method, onSaveInstanceState()
• When the system kills an activity, it can call this method and save the custom state into an instance of Bundle
71
• 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
72
• If an activity is being created for the first time, the Bundle parameter can be null
• If the activity is being created again after being killed, the Bundle containing the state saved when it was killed is passed in as a parameter
73
6.4 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 activities in 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
74
• 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
75
• 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 a 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
76
• An informal way of summarizing this idea:• An activity is a unit of work, a unit of functionality in
an app• A fragment is a unit of interface of the app• Depending on the device an app is running on, for
example:• A given activity may have one or more fragments
associated with it at any given time during a run• Different fragments may belong to different activities
at different times
77
An Example of the Use of Fragments
• The design idea is illustrated on the following overhead using a music app example from Darcey and Conder
• 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
78
79
• There is much more to be said about the use of fragments
• This will come later• For now it’s sufficient if the underlying idea is
clear
80
6.5 Intents
• The concept of an intent is extremely important• Intents are a critical element of multiple-activity
apps• Intents are the mechanism used for transitioning
between one activity and another• In their simplest form, intents are used to
transition between different activities of the same app
81
Synchronous Transitions
• As a Java programmer, you are familiar with the idea that one method can call another
• Such a call is synchronous• In other words, the flow of execution
immediately goes to the called method• Certain kinds of transitions between activities
may be manageable with direct calls in one activity to start or stop another activity
82
Asynchronous Transitions
• 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
• Intents are asynchronous• They are handled by the system when
appropriate
83
• It is more flexible to transition between activities using intents instead of direct calls
• This kind of flexibility is part of what helps the system manage the various activities, potentially belonging to >1 app, that it maintains on the stack
84
Other Characteristics of Intents
• As described so far, an intent is a request to start a particular activity belonging to the same app
• An intent may also in effect be a broadcast message rather than specific message
• In other words, it may be a request that could be satisfied by more than one activity
• The Android system can manage the selection of one of several activities to satisfy it
85
• 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
• An intent can also be structured as a request to a service provider
• Services will be discussed in greater detail later
86
How to Use an Intent to Launch an Activity
• The startActivity() method uses an intent to launch an activity
• An example is shown here• It will be explained piece by piece on the
following overheads
• startActivity(new Intent(getApplicationContext), MyDrawActivity.class));
87
What startActivity() is Called on and What the Return Value Is
• Within the context of a running app, you can call the startActivity() method on the implicit parameter
• Calling the method doesn’t have a direct effect on the implicit parameter
• The indirect effect is that the current activity will eventually be replaced by another activity
• We are also not interested in the return value, in particular, so we aren’t bothering to capture it
88
The Parameter Sent to startActivity()
• The parameter sent to the startActivity() method is a newly created intent:
• new Intent(getApplicationContext), MyDrawActivity.class)
• The construction of the intent takes two parameters• 1. The first parameter specifies that the context for the new activity will be
the same as the context for the current activity• This is clear because the call to getApplicationContext() is on the implicit
parameter• 2. The second parameter specifies the new activity that is requested to be
started• Note that you specify the activity by naming its compiled class file in the
project
89
What Does It Mean to Launch an Activity?
• Think back to the simple example code we’ve seen before
• The activity was coded in MainActivity.java• An activity file doesn’t contain a main()
method• It contains an onCreate() method• In effect, launching an activity means
requesting that onCreate() be called on it
90
• When an activity is the one for which onCreate() was most recently called, it is placed on the top of the activity stack and that activity is in the foreground
• That means that 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()
91
Intents and Bundles
• It was noted earlier that the onCreate() method may take 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 to initialize the activity’s state when it’s started
92
Adding a Bundle to an Intent
• The following snippet of code shows the use of an intent with a bundle
• Note that a bundle does not explicitly appear in the code• The code also illustrates a slightly different set of syntax
for setting up the intent and launching the activity• It will be explained piece by piece on the following
overheads
• Intent myIntent = new Intent(this, MyActivity.class);• myIntent.putExtra(“SomeStringData”, “a string”);• startActivity(myIntent);
93
• This line of code illustrates that you don’t actually have to call getApplicationContext()
• Due to the inheritance structure, the implicit parameter, the current activity, is a context
• Other than that, this is the same as the previous example
• You create an intent by sending in a context and an activity
• Intent myIntent = new Intent(this, MyActivity.class);
94
• This line of code illustrates the use of the putExtra() method on an intent
• Indirectly, it illustrates the use of a bundle• When you put extra data into the intent, it is
internally stored in a bundle
• myIntent.putExtra(“This is the name of the data.”, “This is the data.”);
95
• This is the declaration of putExtra() in the Android API
• The first parameter allows the programmer to name the data item being added
• The second parameter is the value• If you look in the API, there are versions of
putExtra() for all different kinds of values
• putExtra(String name, String value)
96
• This is the third line of code in the snippet• There’s no surprise here• Having created the intent and added data to
it, it’s now possible to call startActivity and pass in the intent
• startActivity(myIntent);
97
Using a Bundle of Extra Data When Creating an Activity from and Intent
• An activity is started by a call to onCreate()• This is the declaration of onCreate() in the Android
API:
• onCreate(Bundle savedInstanceState)
• The important thing to note now is that the bundle passed in as the explicit parameter is saved state
• This is not the bundle associated with an intent when the activity is started by means of the intent
98
• If an activity is started with an intent that has had data put into it, then the following kind of code needs to be in the onCreate() method:
• Bundle myExtras = getIntent().getExtras();• If(myExtras != null)• String myString = myExtras.getString(“SomeStringData”, “default value”);
• You get the intent of the activity• You get the extras of the intent• You then call methods by type (getString()) and retrieve
data items by name (“SomeStringData”)
99
The URI
• 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
100
Predefined Intents
• The previous example code snippets illustrated constructing an intent with a context and an action defined by a programmer written class
• 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);
101
• What is important about this example is not the syntax or the phone dialing specifically
• 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
102
• 2. This concretely shows how your activity can trigger a (system) activity that doesn’t belong to your application (the current context)
• You don’t have to write the code for common functions that (should) exist in mobile devices
• The system makes it possible to integrate system level functionality into your own handcrafted applications
103
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
104
Intents and Navigating among Activities in Applications
• Just to take one example to start with, the items in an app 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 also be coded to launch an activity
• This would support horizontal transitions between screens/activities
• Any application can mix and match these and other models of using intents to organize functionality
105
• We haven’t seen a complete example yet of how to create a multiple activity, multiple screen app with intents yet
• This will be the topic of the example which comes at the end of this unit
• There are a few more background items that need to be covered before giving the example
106
6.6 Services
• The Service class was included in the list of classes at the beginning of this unit
• It will be a while before examples are given where services are used, but they are an important concept
• It was noted earlier that roughly speaking, an activity may correspond to a screen that a user interacts with in an app
107
• By contrast, 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 also be used by more than one activity—as opposed to being a unitary part of a single app
108
• In other words, one way of thinking of a service is as a background process
• 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
109
• 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
110
6.7 The Android Manifest File
• This will be the last nuts and bolts section before considering the example app
• This is section is different from the foregoing sections
• It’s not about code internals or the classes mentioned so far
• It’s back to an XML file associated with an app which you can look at and edit in the development environment
111
• There was no need to consider it earlier—we effectively just accepted the default
• However, having 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
112
• 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
113
• 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
114
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
115
• The manifest file identifies the app
• <?xml version="1.0" encoding="utf-8"?>• <manifest
xmlns:android="http://schemas.android.com/apk/res/android"• package="com.example.myechoapp"• android:versionCode="1"• android:versionName="1.0" >
116
• 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
• <uses-sdk• android:minSdkVersion="8"• android:targetSdkVersion="17" />
117
• The manifest file specifies whether the app can be backed up and the icon used to represent it, its label, and its theme
• <application• android:allowBackup="true"• android:icon="@drawable/ic_launcher"• android:label="@string/app_name"• android:theme="@style/AppTheme" >
118
• 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
• <activity• android:name="com.example.myechoapp.MainActivity"• android:label="@string/app_name" >
119
• 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
• MainActivity.java is it—and if an intent is directed at this activity, it should be launched
• <intent-filter>• <action android:name="android.intent.action.MAIN" />
• <category android:name="android.intent.category.LAUNCHER" />• </intent-filter>• </activity>• </application>
• </manifest>
120
• This information on activities and intents in the manifest file is why the manifest file is considered in this set of overheads
• It is fundamental to understanding the nature of apps as collections of activities and intents
• The example, which will follow, will make explicit use of intents and multiple activities
121
• At a basic level the analogy with the manifest file for a Java self-executable jar file is this:
• In the jar file manifest, you have to specify which class contains the main() method
• In the manifest file for a multiple activity app, you have to specify which of the activities is the principal activity
122
6.8 The Example
123
Introduction
• The example that will be presented now is taken from the online tutorials, as of August of 2013
• If you compare what’s in these overheads with the contents of the tutorials, there are very minor differences
• A couple of things which are not necessary and seemed problematic to explain or use are left out
• It’s also possible that some things like imports, etc., are in a slightly different order
124
• The example is an echoing application where the input is one activity, on one screen, and the output is another activity, on another screen
• The transition from input to output is accomplished using an intent
125
• The remaining overheads in this unit will cover the steps in developing the app from the ground up
• The input and output screens of the app are shown on the following two overheads
• This shows what the end result of the development is
126
127
128
How Interfaces are Structured
• Android interfaces can 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
129
130
• Do not be confused—this diagram is different from the diagrams at the beginning of the unit about activities
• The point now is just to get you back into the XML for layouts
• Each activity for an app will have a layout, and the individual layout is a view group that will contain widgets, etc., which are individual views
131
activity_main.xml
• The complete activity_main.xml file for this example app is shown on the following overhead
• The point at this stage is that the LinearLayout is a ViewGroup and the EditText and Button widgets are Views
132
• <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal"> <EditText android:id="@+id/edit_message" android:layout_weight="1" android:layout_width="0dp" android:layout_height="wrap_content" android:hint="@string/edit_message" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/button_send" /></LinearLayout>
133
• 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
134
• 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 strings.xml
• <string name="edit_message">Edit message</string>• <string name="button_send">Button send</string>
135
MainActivity.java and sendMessage()
• Some code for the MainActivity.java class will be shown shortly
• Some needed imports will be shown• A needed constant definition will be shown• Then the complete code for sendMessage()
will be shown
136
• Recall that sendMessage() is the method triggered by clicking the button in the app
• The critical feature of sendMessage() it that an intent is created to start a second activity
• After completing the presentation of sendMessage(), we will turn our attention to this second activity
137
• The imports, constant definition, and sendMessage() code are shown on the following overhead
• Note that if you put this into MainActivity.java, the development environment will flag errors
• You have to start doing development somewhere• Because an app consists of interrelated files, no
matter where you start, at the outset the other files will not be consistent with what you’ve initially done
138
• import android.view.View;• import android.content.Intent;• import android.widget.EditText;• …• public class MainActivity extends Activity {
• public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
• public void sendMessage(View view)• {• Intent intent = new Intent(this, DisplayMessageActivity.class);• EditText editText = (EditText) findViewById(R.id.edit_message);• String message = editText.getText().toString();• intent.putExtra(EXTRA_MESSAGE, message);• startActivity(intent);
}
139
• On the following overheads, the different sections of the code snippet given on the previous overhead will be considered one after the other
140
• The first lines shown are these imports:
• import android.view.View;• import android.content.Intent;• import android.widget.EditText;
• These classes appear in the method, so they need to be imported in order to be used
141
• 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
142
• This line of code just defines a string constant
• public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
• The tutorial chooses to define that name of the extra string to be put into the bundle as a constant up front, rather than giving it a name when making the putExtra() call
143
• Here the intent is being created
• Intent intent = new Intent(this, DisplayMessageActivity.class);
• The first parameter is the context, the implicit parameter, this, namely the current activity, which is MainActivity
• The second parameter is the second activity of the app
144
• We will turn our attention to creating the code for DisplayMessageActivity after finishing with sendMessage() in MainActivity
145
• These lines of code embody the logic for doing input
• (It’s the same logic as in the simple, one activity app, MyEchoApp)
• EditText editText = (EditText) findViewById(R.id.edit_message);• String message = editText.getText().toString();
• First we get a handle on the EditText view• Then we get whatever text it contains
146
• Now the fun starts• We put the input message into the intent
• intent.putExtra(EXTRA_MESSAGE, message);
• More precisely, internally the message is going into a bundle
• When the second activity is created, this message will be retrieved for display in that activity’s separate layout
147
• Finally, from sendMessage() in MainActivity, we call startActivity, passing in the intent which contains the second activity of the app, DisplayMessageActivity
• startActivity(intent);
148
DisplayMessageActivity
• If you become experienced in app development, you might eventually remember the necessary components in the code for an activity other than MainActivity
• For convenience though, it’s best to just rely on the wizard for creating activities
149
Using the Wizard to Create an Activity
• In the Eclipse environment, the leftmost tool in the toolbar will be “New”
• To get to the wizard, in the New tool, select Android, Android Activity
• You can also get to the wizard with File|New|Other|Android Activity in the menu
• A screenshot of the starting point is shown on the following overhead
150
151
• Starting the wizard takes you to the step shown on the following overhead
152
153
• Accept Blank Activity and that takes you to the next step, shown on the following overhead
• When you enter an activity name other fields will auto-complete
• Take the options and fill out any other fields as shown
• (Ignore the error message. I went back to get the screenshots for the overheads after the app was already complete.)
154
155
• When you click next, the Java file for the new activity will be created
• This file will contain methods needed for an activity just as MainActivity.java contains the methods it needs when it’s created using a wizard
156
A Note on the AndroidManifest.xml File
• This is another note on what the wizard and development environment do for you:
• They automatically create the required entry for the new 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
157
• <activity•
android:name="com.example.tutorialexampleforoverheads5.DisplayMessageActivity"• android:label="@string/title_activity_display_message"• android:parentActivityName="tutorialexampleforoverheads5.MainActivity" >• <meta-data• android:name="android.support.PARENT_ACTIVITY"• android:value="tutorialexampleforoverheads5.MainActivity" />• </activity>
• Not surprisingly, the contents of the XML file as shown here reflect the values specified in the wizard
158
activity_display_message.xml
• The activity creation wizard brings the layout file for that activity into existence
• Like all default layout files, this is essentially a copy of “Hello World”
• Immediately after considering the code for the DisplayMessage.java class, we’ll consider how layout for the activity is updated
159
Code Functionality for DisplayMessageActivity
• Fundamentally, the new activity has to receive the intent, get the text from it, and display it
• The work is done in the onCreate() method for this activity
• The complete onCreate() method of DisplayMessageActivity.java is shown on the following overhead
160
• @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);• }
161
• For the sake of completeness, the method is shown again, part-by-part, on the following overheads
162
• From our perspective the call to super() is just copy/paste housekeeping
• @Override• public void onCreate(Bundle savedInstanceState) {• super.onCreate(savedInstanceState);
• We’ve seen the pattern of calling super.xyz() and then adding lines of code which customize xyz() for the subclass in Java in methods like paintComponent()
163
• The idea that you have to get the message before you can display it is familiar from MyEchoApp and all echoing type applications
• Intent intent = getIntent();• String message =
intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
• The difference here is that the message comes from the intent• Notice how the public static String constant defined in
MainActivity can be used here as a handle on the message of interest
164
• Here is the spot where you 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);
165
• As a result of this line of code, the text view becomes the contents of the layout
• // Set the text view as the activity layout• setContentView(textView);
• In the sequence of steps in the activity creation wizard, the activity_display_message.xml layout file was created and associated with the activity
• This call on the implicit parameter, the new activity, passes the text view constructed in the activity Java code to the layout file
166
• The overhead with the title activity_display_message.xml noted that the system apparently provided a copy of the “Hello World” layout as a default
• This code worked fine with the default layout• The contents of the default layout were
replaced with the text view passed in as the new contents, and when the app ran it displayed the echoed message
167
What it Looks Like
• This section now ends where it began, by showing what the app does
• The following overhead shows what the app looks like in the emulator when some sample text has been entered into it
168
169
• 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
170
171
Summary and Mission
• Summary: Activities, intents, etc.• Various terms were mentioned• Some, like fragments, have not been applied
in practice yet• Others, like activities and intents have been
applied
172
• A large amount of background information was presented
• Ultimately, it will all be important• The background was followed by an example• Both the things that were applied in the
example and the other things which weren’t will come back again in future examples which are more complicated
173
• Mission: You should get the tutorial example to work in your environment
174
The End
top related