Programming Android applications: an incomplete introduction. J. Serrat Software Design December 2013

Size: px
Start display at page:

Download "Programming Android applications: an incomplete introduction. J. Serrat Software Design December 2013"

Transcription

1 Programming Android applications: an incomplete introduction J. Serrat Software Design December 2013

2 Preliminaries : Goals Introduce basic programming Android concepts Examine code for some simple examples Limited to those relevant for the project at hand Provide references to best materials for self study, read them before programming, trial and error takes longer Understand provided project implementation Homework for a quick start

3 Preliminaries: why Android Many students own an Android phone Known and free development environment (Android SDK + Eclipse + ADK plugin) Well documented Good chance to learn UI design Take away course project in your pocket, funny to see and show your software running in a phone Starting point to learn more on mobile development

4 Preliminaries: why Android Drawbacks: learning curve, lots of details Many things left out: fragments, programming action bars, themes... How to learn: try to solve small problems in separate projects, like create an action bar wit actions and overflow action customize a ListView to show name and time make a contextual action bar

5 Contents 1. References 2. Development framework 3. Building blocks 4. Structure of an Android project 5. Activity life cycle 6. Views, Layouts

6 Contents 7. Menus 8. Action bar 9. Intents, Broadcast receivers, Adapters 10. Dialogs, Preferences 11. Services 12. TimeTracker architecture

7 References Published since 2010 (O'Reilly, Apress, Wrox, Manning) and many more...

8 References Professional Android 4 application development. Reto Meier. Wiley, Complete, comprehensive, basic and advanced topics. I used the Android 2 version to learn. Source code at eu.wiley.com Hello, Android. 3rd Edition. Ed Burnette. The pragmatic programmers, Simpler, only basic topics. Sudoku application. Source code at Android UI fundamentals: develop and design. Jason Ostrander. Peachpit, Focused on UI only. Example application: a time tracker (1 level). Source code at

9 References December

10 References

11 References In Eclipse, you can install many (legacy) application examples : File New Other Android Sample project...

12 References Load examples as Eclipse projects: File New Android project create from existing sample Api demos Run and see source code for the API demos. Virtual device emulator

13 References For example, in emulator: Api Demos Views Controls Light theme and in Eclipse: res/layout/controls_1.xml apis.views/controls1.java

14 Development framework

15 Development framework

16 Building blocks Main logical components of Android applications : Activity : UI component typically corresponding to one screen. They contain views = UI controls like buttons, editable text boxes... May react to user input and events (intents) An application typically consists of several screens, each screen is implemented by one activity. Moving to the next screen means starting a new activity. An activity may return a result to the previous activity.

17 Building blocks Service : application part that runs in background without the user s direct interaction, similar to a Unix daemon. For example, a music player. Content provider : generic interface to manage (access, change) and share (like contacts ) application data. Can be stored as SQLite databases. Application Activity Activity Application Application Activity Content Resolver Service Content Resolver Content Provider Content Resolver Data file SQLite XML file Remote Store

18 Building blocks Intent : messages sent by an activity or service in order to launch an activity = show a new screen broadcast (announce) that a certain event has occurred so that it can be handled Fundamental to decouple cooperating application components. Post 3.0 APIs include some more components: fragments, tasks...

19 Building blocks Structure of an Android project: create and run a Hello world application, File New Android application project... Do not close the emulator! It takes a lot to start. Each time you build the project, the new version is uploaded and execution starts automatically.

20 HelloWordActivity.java Automatically generated code

21 HelloWordActivity.java Autogenerated class R Inflates the UI from the main.xml file specifying it

22 values/strings.xml Place to define UI constant strings, values, arrays of integers and strings, colors, size of things (dimensions)... Can use the Resources assistant to edit.

23 values/strings.xml Message displayed in the screen

24 AndroidManifest.xml other views xml view

25 AndroidManifest.xml includes xml nodes for each of the application components : Activities, Services, Content Providers and Broadcast Receivers using intent filters to specify how they interact with each other: which activities can launch another activity or service which broadcast intents an activity listens to, in order to handle them with a receiver... offers attributes to specify application metadata (like its icon or theme)

26 AndroidManifest.xml Won't start on devices supporting an older API This activity may be the application entry point.

27 layout/main.xml The interface design is represented in XML, decoupling design from code (opposite to programmatic UI ). A call inflates the UI. Layout is a special view that contains other views in specific spatial arrangements. LinearLayout arranges its children in a single column or row. TextView is a non-editable text label. XML view of the UI design

28 layout/main.xml string id defined in string.xml

29 layout/main.xml <LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:text="tubequoter V0.10" /> <TableLayout android:layout_marginleft="20dp" > <TableRow <TextView android:text="longitud" /> <EditText android:inputtype="number" > <requestfocus /> </EditText> <TextView android:text="mm" /> </TableRow> : : </TableLayout> <Button android:id="@+id/butocalcul" android:text="calcula" /> </LinearLayout>

30 layout/main.xml Graphical view of the UI design, better to design. Select item and edit properties.

31 Activity Life Cycle Many Android devices have limited memory, CPU power, and other resources. The OS assures the most important processes get the resources they need. In addition, the OS takes responsiveness very seriously: if the application does not answer user input (key press...) in < 5 secons, the ANR dialog appears.

32 Activity Life Cycle Each application runs in its own process, which has a main thread, within which activities, services... run The OS ranks processes and kills those with lowest priority, if some application needs unavailable resources. If a process is killed in the middle, somehow data can not be lost.

33 Activity Life Cycle Android in practice. Collins, Galpin, Käpler. Manning, 2012.

34 Activity Life Cycle States of an activity and methods invoked when changing state Activity is active = visible in foreground interacting with user Not visible. Will remain in memory. Need to save data, such as a database record being edited. Hello Android. Ed Burnette. The Pragmatic Programmer, 2010 Activity is visible in background

35 States of an activity and methods invoked when changing state. Changing orientation landscape portrait calls ondestroy() + oncreate(). Ctrl-F11 on virtual device.

36 Homework Recap Get some recommended book AND read developer.android.com/training main topics Load API demos in Eclipse : File New Other Android Android project from existing code + select <SDK folder>/android-18/samples/legacy Create a Hello world project with string and icon resources try different nested layouts

37 Views, Layouts Control: extension of class View that implements some simple functionality, like a button. ViewGroup : extensions of the View class that can contain multiple child Views (compound controls). Layout managers, such as LinearLayout. Activities represent the screen being displayed to the user. You assign a View or layout to an Activity: HelloWordActivity.java main.xml

38 Views, Layouts Controls: catalog and appearance depends on API level. Look at Eclipse Graphical layout editor : shows controls depending on the API level of your project. Run Api Demos Views developer.android.com/guide/components

39 Views, Layouts Common controls : TextView, EditText (many types), Button, ListView, ExpandableList, Spinner, Checkbox, ProgressBar, SeekBar, RadioGroup, RatingBar, Time and Date Picker

40 Views, Layouts Layouts control the position of child controls on a screen. Common layouts: LinearLayout adds each child View in a straight line, either vertically or horizontally RelativeLayout define the positions of child Views relative to each other or screen boundaries TableLayout lay out Views using a grid of rows and columns Can be nested, creating arbitrarily complex interfaces.

41 Views, Layouts LinearLayout

42 Views, Layouts RelativeLayout

43 <LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:text="tubequoter V0.10" /> <TableLayout android:layout_marginleft="20dp" > <TableRow <TextView android:text="longitud" /> <EditText android:inputtype="number" > <requestfocus /> </EditText> <TextView android:text="mm" /> </TableRow> : : </TableLayout> <Button android:id="@+id/butocalcul" android:text="calcula" /> </LinearLayout>

44 Views, Layouts ToDoList example : how to react to user input? How to bind data to the UI (lists)? Write to the edit box and then press D-Pad or Enter to add as a new item to the ToDo list. D-Pad

45 Views, Layouts

46 Views, Layouts From now on, changes on ArrayList todoitems are shown in the screen when adapter notifies it.

47 Views, Layouts Java anonymous class Override onkey of class onkeylistener Which listeners has an EditText?

48 Views, Layouts It is possible to customize the aspect and content of items in a ListView. See Ch. 4 Reto Meier's book and source code at

49 Contents 7. Menus 8. Action bar 9. Intents, Broadcast receivers, Adapters 10. Dialogs, Preferences 11. Services 12. TimeTracker architecture

50 Menus Present application functionality using little screen space. Each Activity can specify its own menu. Difference between pre and post 3.0 platform (API level 10): pre: physical menu button on the device, three levels of menus: options, expanded, submenu post: superseded by the action bar

51 Menus phones with physical navigation keys virtual navigation controls

52 Menus Three types of menus 1. Options menu at the bottom of screen icons and text if more than 6 items, a More item is displayed that opens an Expanded menu On Android 3.0 and higher, items from the options menu are presented by the action bar

53 Menus expanded menu action bar

54 Menus 2. Context menu floating menu that appears when the user performs a long-click on an element similar to right-click menu provides actions that affect the selected content, normally an item of a ListView

55 Menus 2. Context menu from Android 3.0 on, better use a contextual action bar to present actions the user can perform on the currently selected item contextual action bar: actions depend on selected item(s) context menu pre

56 Menus 3. Popup or submenu modal menu anchored to a View, appears below or above it good to provide an overflow of actions that relate to specific content or to provide options for a second part of a command/menu item no icons submenu title action overflow : less often used actions

57 Menus 3. Popup or submenu but can't be nested: a submenu item can not expand another submenu On Android 3.0+ : actions should not directly affect the corresponding content that's what contextual actions are for Context menu and submenu for an item

58 Menus Programming (1) Recommended: define menu items and properties as a menu resource in XML, not in the code easier to visualize the menu structure allows to create alternative configurations for different platform versions, screen sizes... compact code: menu is inflated by a single call can use Eclipse's resource editor

59 Menus

60 Menus string resource name that will appear in the UI, better use array of strings in xml to reference the menu options in the code : what's been selected?

61 Menus Programming (2) Override Activity method to inflate the xml menu res/menu/game_menu.xml

62 Menus Programming (3) Program event handling : when the user selects an item from the options menu (also action items in the action bar), the system calls the activity's method selected item item ids

63 Menus Spinners offer similar functionality: multiple choice selection from exclusive options on a dropdown menu. Not a menu control! Menu items can contain radiobuttons but also checkboxes and form groups

64 Action bar Replaces the options menu in Android 3.0+ with buttons ('action items') One of the most important design elements of an Android app. : dedicated piece of screen visible throughout the app. running makes our app. consistent with the core Android apps.

65 Action bar Examples

66 Action bar Purposes : make important actions prominent and accessible [3] support consistent navigation and view switching [2] (with spinner or tabs) reduce clutter by providing an action overflow for rarely used actions [4] show app identity [1] app. icon spinner action buttons action overflow

67 Action bar Action bars can be split If the user can navigate, contains the up caret, at a minimum To quickly switch between the views, use tabs or a spinner in the top/main action bar Display actions and, if necessary, the action overflow main action bar top bar bottom bar

68 Action bar spinner action overflow

69 Dialogs Small windows displayed over the screen. modal: block all user input and must be dismissed before the user can continue. partially obscures the Activity that launched it. Purposes : answer questions Yes/No, Ok/Cancel... make selections read warning or error messages show bar progress

70 Dialogs Dialog share a common structure: Optional title region: Introduces content Content area: text, UI elements, text fields, checkboxes, etc... Action Buttons: Typically OK/Cancel, indicating the preferred option.

71 Dialogs Special types of Dialogs: Alerts: Inform user from a situation that requires confirmation. Pop-ups: Lightweight dialogs with a single selection from the user. Toasts: Small pop-up that feedbacks about something. Disappear automatically.

72 Dialogs Programming (1) Dialogs should normally be created(instantiated) within the Activity's oncreatedialog(int). This is called only the first time the dialog is showed. To show the dialog, call showdialog(int) To change dialog properties each time the dialog is opened, define onpreparedialog(int) 1st call showdialog(id) 2nd call showdialog(id) oncreatedialog(id) onpreparedialog(id) onpreparedialog(id)

73 Dialogs Programming (2) The best way to define oncreatedialog(int) is with a switch statement that checks the id of the dialog being created. The method must return the dialog created.

74 Dialogs Programming (3) When it's time to show one of the dialogs, call showdialog with the desired ID. To close a dialog, you can dismiss it by calling dismiss() from the Dialog object. If necessary, you can also call dismissdialog(int) from the Activity.

75 Preferences Android provides classes to manage application preferences and implement the preferences UI. ensures consistency, with specific UI elements (e.g ListPreference) all preferences within each application is maintained in the same manner.

76 Preferences The SharedPreferences class: provides a general framework to save and retrieve key-value pairs. there is a single instance of this class. its data will persist across user sessions (even if the app is killed)

77 Preferences Steps to implement the Preferences: 1. Add string resources needed for preferences.

78 Preferences 2. Create the preferences UI layout (using standard Preference UI elements). We can reference the string resources

79 Preferences 3. Create the Preferences Activity, and inflate the layout overriding the oncreate method. 4. Add static string values to identify each of the preferences by a unique key.

80 Preferences 5. Implement the OK/Cancel listeners and a method to save preferences. This method commits changes on the sharedpreferences object

81 Preferences 5. Implement the OK/Cancel listeners and a method to save preferences. Add pairs string,value to the SharedPreferences object Commit changes. If the preferences file MYPREFS does not exist, it will be created

82 Preferences 6. Apply the preferences when the activity starts. Preferences file name. If it does not exist will be created when committing changes Default value if it is not defined Unique preference key (string)

83 Intents Intents is a fundamental concept in Android development : the glue that binds applications' components. Message-passing mechanism to explicitly or implicitly start an Activity or a Service broadcast that an event has occurred, application or system-wide to handle user action or process a piece of data

84 Intents

85 Intents origin context activity to start Intents can return a result: startactivityforresult()

86 Intents Need to declare all activities in AndroidManifest.xml

87 Broadcast Receivers Intents can also be used to broadcast messages to anonymous components with one same application. The sender can associate data to those intents. A broadcast receiver (maybe within other app. component): listens for selected types of broadcast intents responds to them = processes associated data 'Anonymous' implies components are loosely coupled, do not need to know each other.

88 Broadcast Receivers NEW_LIFE String name double longitude double latitude On button click a broadcast intent of type NEW_LIFE is sent, along with three data fields. A broadcast receiver object has subscribed to this type of messages in the AndroidManifest.xml. The receiver does not belong to an Activity or Service in this case. Response is printing a message.

89 Broadcast Receivers

90 Broadcast Receivers Broadcast intent type data field names

91 Broadcast Receivers The broadcast receiver will always be active (listening), even when MyActivity has been killed or not started

92 Broadcast Receivers Register the receiver when MyActivity is visible and unregister when not. Typically when the receiver updates am UI element.

93 TimeTracker architecture LlistaActivitatsActivity.java LlistaIntervalsActivity.java ListView controls

94 TimeTracker architecture Harder to destroy by Android OS than activities Contains the actual activities and intervals tree Analogous to TimerTask or Timer, which are not usable in Android. See code comments and references there.

95 TimeTracker architecture Show a part of the tree, the childs of some node. root P P T P T P P T I I I different fields

96 TimeTracker architecture DONAM_FILLS PUJA_NIVELL BAIXA_NIVELL DONAM_FILLS ENGEGA_CRONOMETRE PARA_CRONOMETRE PUJA_NIVELL

97 TimeTracker architecture TE_FILLS + array of project and task data : dates and duration TE_FILLS + array of interval data : name, dates and duration

98 TimeTracker architecture Intent data to activities is a serialized array list of these objects. This avoids serializing the whole or a subtree of activities and intervals, slow if the tree is large! (need to do it every 2 secs.) Creates a random synthetic but data-consistent large tree (durations and dates)