Top Banner
Android 5: Activities Kirk Scott
126

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

Dec 13, 2015

Download

Documents

Gladys Warren
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Android 5: Activities Kirk Scott. Introduction The title of this set of overheads is something of a misnomer It is not easy to encompass the contents.

Android 5: Activities

Kirk Scott

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

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

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

• 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

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

• 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

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

• 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

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

5.1 Contexts

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

• 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

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

• 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

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

• 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

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

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

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

• 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

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

• Finally, 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

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

• We have seen examples with a single activity• When MyEchoApp is run, for example,

MainActivity is brought into existence• It is an activity, an instance of a subclass of Context• Because it’s 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

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

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

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

• 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 ActivityMain.java, which retrieves the app context:

• Context myContext = getApplicationContext();

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

• 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

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

• 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()

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

• Recall that if you declare a string in strings.xml, successful compilation will result in handle for the string in R.java

• 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);

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

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

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

5.2 Activities

• As already stated, activities are the basic building blocks of apps

• From the top-down perspective, the context is central

• But from a bottom-up perspective, the activity is 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

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

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

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

• Darcey and Conder provide a small example• 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

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

• 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

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

• 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

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

• 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

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

• 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• 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

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

• Again, activities have lifecycles, similar to the way processes or threads 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

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

• 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

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

• 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

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

• 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()

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

• 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

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

• 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

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

• 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

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

• 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

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

• 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

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

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

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

• 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

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

• 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

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

• 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

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

• The fragment idea is encapsulated in the Fragment class in the Android API, android.app.Fragment

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

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

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

• 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()

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

• 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

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

• 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

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

• 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

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

• 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

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

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

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

• 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

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

• What does it mean to launch the specified?• Think back to the 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 the activity means creating

it

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

• 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()

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

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

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

• 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

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

• 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

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

• 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()

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

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

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

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

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

• 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);

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

• 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

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

• 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

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

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

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

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, android.app.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

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

• 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

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

• 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

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

• 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

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

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

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

• 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

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

• 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

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

• 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

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

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

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

• 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" >

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

• 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" />

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

• 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" >

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

• 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" >

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

• 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>

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

5.7 The Third Example

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

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

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

• 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

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

• 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

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

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

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

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

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

• <?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>

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

• 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

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

• 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

• <string name="edit_message">Edit message</string>• <string name="button_send">Button send</string>

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

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

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

• 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 MainActivity.java,

it will be riddled with errors• This is the consequence of developing in the

order chosen

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

• import android.view.View;• …• 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);

}

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

• The first line shown is this import:

• import android.view.View;

• The method has a parameter of this type, so the class is required

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

• 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

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

• 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()

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

• These lines of code should look familiar from 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

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

• 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);

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

• 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

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

• I may have overlooked something and this may not be an ideal solution, but I solved the problem by putting this declaration in ActivityMain.java:

• 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

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

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

• startActivity(intent);

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

• 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 android.app.Activity;• import android.widget.TextView;• import android.content.Intent;

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

DisplayMessageActivity

• It would be possible to create a new activity from scratch in the development environment

• Just save MainActivity.java under the new name DisplayMessageActivity.java in the src folder

• Delete sendMessage(), keeping onCreate() and onCreateOptionsMenu()

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

• 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

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

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

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

• Select the Blank Activity Template and click Next

• That takes you to the step in the wizard shown on the following overhead

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

• 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

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

• 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

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

• 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

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

• 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

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

• <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 reflect the values specified in the wizard

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

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

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

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 DisplayMessageActivity.java is shown on the following overhead

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

• @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);• }

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

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

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

• From our perspective this is just copy/paste housekeeping

• We’ve seen the pattern of calling super.xyz() and then adding lines of code which customize xyz() for the subclass in Java

• @Override• public void onCreate(Bundle savedInstanceState) {• super.onCreate(savedInstanceState);

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

• 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);

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

• 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);

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

• 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);

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

• 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

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

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

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

• 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

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

The End