Software Environments of Smartphone Applications

Size: px
Start display at page:

Download "Software Environments of Smartphone Applications"

Transcription

1 Software Environments of Smartphone Applications Exercise/Practice Professur Schaltkreisund Systementwurf 1

2 Introduction The course Software Environments of Smartphone Applications (SESA) provides an overview of the current smartphone market. It depicts the concepts of the operating systems and introduces to the development environments and philosophies. As an example, the Android OS and the development of Android applications is presented in depth. The course consists of an exercise and a practice session. The examination is a 20 minutes presentation of a self developed smartphone application. 2 2

3 Prerequisites for Attending What do I do? Depicts the concepts of the operating systems Introduce the development environments and philosophies What else do I do? Introduce Android environment in depth Show some basic programming philosophies for Android Lend you a hand while you develop your application What do I not do? Teach you the english language Teach you the basics of the Java programming language Implement your application for you 3 3

4 Prerequisites for Attending What do you do? Have programming skills beyond those of Hello World Or have a deep personal interest in learning the Java programming language Have a deep personal interest in learning the Android dependent part of the Java programming language Regularly attend the exercise/pactise! 4 4

5 Software Environments of Smartphone Applications Professur Schaltkreisund Systementwurf 5

6 Smartphones First devices appeared 1994 at the market Boom started with Apples first iphone (2007) Before, RIM and Nokia dominated the market Key hardware features of today s smartphones High resolution touch display (mostly capacitive displays) Fast processor (up to 2 GHz), various architectures Plenty of RAM (512MB and more) Gigabytes of Flash One or two high quality cameras Several sensors (acceleration, rotation, GPS,...) HTC Sensation, htc.com, October 01,

7 Smartphones Key software features Well defined, open and mostly free API Well developed, mostly free development environments App development is open to anyone Applications (Apps) Sony Xperia S, Chip.de, October 01, 2012 Applications extend the functionality of the OS Applications are often OS specific (look, feel, API) App Stores offers access to applications and contents (books/magazines, music, movies) 7 7

8 Operating Systems Lots of different operating systems Biggest ones are Android and ios Former leader Symbian (up to 75%) lost its importance Windows Phone still lags behind RIM is also not able to follow Other Linux based solutions do not gain importance, yet 8 IDC Worldwide Mobile Phone Tracker, May 24,

9 Ecosystems The Ecosystem is the sum of The vendor support for The smartphone hardware The smartphone OS The available App-Store(s) and contents The development environment The hardware and software the phone is (directly) compatible with e. g. hardware and software of the same vendor software to integrate the phone in one s workflow 9 9

10 Smartphone Applications Apps - short for Applications All kind of (end-)user software is an App Currently the term is commonly used as a synonym for end user software on smartphones Types of smartphone applications OS specific apps Build using the specific programming languages and tools Target to a certain Phone-API and run directly on that OS Often also address on special look & feel, as well as OS specific features Web-Apps Build using web technologies like HTML, CSS, jquery Need a web server to be hosted Can be transformed to run directly on the phone 10 10

11 Basic Workflow Idea Specification Maintenance Resource Analysis Shop Rollout Platform Decision Test SDK Decision Implementation 11 11

12 Basic Workflow Idea Specification (first round) Rough line-out, pictures,... Resource analysis Estimations for display size, computing power,... Platform decision One platform, all major platforms SDK decision Specific apps or web-apps Programming language 12 12

13 Basic Workflow Implementation Specification (second round) control concept, GUI elements,... Programming language, modularisation,... Test First using the simulator(s) Second using real phone(s) May become very expensive due to the mass of devices 13 13

14 Basic Workflow Shop rollout Decision of the price Advertisement Shop account Gate keepers,... Maintenance May be very intensive in the first cycles due to costumers feedback 14 14

15 Runtime Environments Hosted on a web server Run in the phones web browser / browser environment Is therefore restricted to the browser capabilities Not necessarily full hardware access (filesystem, phone data, sensors, cameras,...) Speed limitations Should emulate the phones elements and specific look Should follow the UI guidelines of the target OS 15 15

16 Runtime Environments Run natively in the phones app environment Sandbox (ios) Java VM / Dalvik VM Silverlight / XNA (Windows Phone) Restricted by sandboxing / virtualization Access to hardware, data,... through a OS dependent API Look & Feel predefined / affected by OS dependent API 16 16

17 Specific SDKs Applications form one of the most important selling arguments Therefore all vendors offer a SDK for their mobile OS Apple: Xcode Android: Android SDK (to be used with Eclipse) Windows 8: Visual Studio 2012 RIM: BlackBerry Specific SDK The SDKs also offer Simulators 17 17

18 Apples Xcode Source: developer.apple.com 18 18

19 Google Android SDK Based on Eclipse 19 19

20 Windows 8 Source: app/ 20 20

21 3rd Party SDKs Several 3rd party IDEs exist with different goals More graphical approaches for nonprogrammers Specific app development with other languages Some even provide platform independent specific app development Conversion of web-app to stand alone app 21 21

22 3rd Party SDKs Codea Corona Lazarus LiveCode RealStudio RhoMobile Suite Unity Vendor Two Lives Left Corona Labs Lazarus Community RunRev Realsoftwar e Motorola Unity Technologie s Platform ipad OS X, Windows OS X, Windows, Linux OS X, Windows, Linux OS X, Windows OS X, Windows OS X, Windows Programming Language Lua Lua Object Pascal LiveCode Realbasic Ruby Javascript, C#, Boo Price 8 from 199 US-$ Open Sources from 99 US- $ from 79 Freeware from 400 US-$ Source: heise Mac & I, Heft 07,

23 Google Android - Operating System Basics Professur Schaltkreisund Systementwurf 23

24 Android Operating System for Smartphones Kernel, Middelware, Applications The first commercially available phone to run Android was the HTC Dream, released on October 22, Since then Android became the most used Smartphone Operating System Therefore very heterogenous infrastructure: Hundreds of devices Variety of Architectures, Displays, Brandings, Versions,

25 Android Versions Android Timeline, FAQoid.com, October 01, 2012 Platform Versions,Dashboards Developers Android, October 01,

26 Android Versions Android Timeline, FAQoid.com, October 01, 2012 Platform Versions,Dashboards Developers Android, October 01,

27 Architecture Source: Unknown 26 26

28 Architecture 27 27

29 Architecture The base of Android is formed by the Linux Kernel and its drivers. The kernel is the only element having direct access to the hardware. It also manages the system memory and provides interfaces for the applications to communicate with each other in a secure and fast way

30 Architecture The base of Android is formed by the Linux Kernel and its drivers. The kernel is the only element having direct access to the hardware. It also manages the system memory and provides interfaces for the applications to communicate with each other in a secure and fast way. At the second layer, also called the "Native Layer" there are system libraries which access kernel interfaces and provide services for the application framework. It is mainly written in C and runs directly on the CPU. The prominent part of this layer is the Android Runtime. It consists of the Dalvik VM and its core libraries

31 Architecture At the third layer, the Application Framework, all components run inside the Dalvik VM. Here reside services which access the libraries of the native layer and provide standardized interfaces for the Applications. The base of Android is formed by the Linux Kernel and its drivers. The kernel is the only element having direct access to the hardware. It also manages the system memory and provides interfaces for the applications to communicate with each other in a secure and fast way. At the second layer, also called the "Native Layer" there are system libraries which access kernel interfaces and provide services for the application framework. It is mainly written in C and runs directly on the CPU. The prominent part of this layer is the Android Runtime. It consists of the Dalvik VM and its core libraries

32 Architecture The highest layer is where all applications live. Each applications live in its own sandbox. This means: Each application runs as a different user of the linux system. Each process has its own virtual machine and every application runs in its own process. Each application, by default, has access only to the components that it requires to do its work and no more. This creates a very secure environment in which an application cannot access parts of the system for which it is not given permission. At the third layer, the Application Framework, all components run inside the Dalvik VM. Here reside services which access the libraries of the native layer and provide standardized interfaces for the Applications. The base of Android is formed by the Linux Kernel and its drivers. The kernel is the only element having direct access to the hardware. It also manages the system memory and provides interfaces for the applications to communicate with each other in a secure and fast way. At the second layer, also called the "Native Layer" there are system libraries which access kernel interfaces and provide services for the application framework. It is mainly written in C and runs directly on the CPU. The prominent part of this layer is the Android Runtime. It consists of the Dalvik VM and its core libraries

33 Architecture Source: Unknown 28 28

34 Architecture Source: Unknown 28 28

35 Dalvik VM Optimized for slim devices Process Virtual Machine Runs as a normal application inside a host OS and supports execution of a single process Created when the process is started and destroyed when it exits Interprets byte code, which is typically created from Java source code As of Android 2.2 Dalvik is enhanced by a justin-time-compiler to speed up execution 29 29

36 Architecture Source: Unknown 30 30

37 Architecture Source: Unknown 30 30

38 Core Libraries Set of basic libraries close to the VM Three main parts Dalvik VM- specific libraries System info, debugging,... Java compatibility libraries Base and utility classes Third-party utility libraries Like Apache HttpClient 4.0 Provides more desktop like JRE Subset of desktop JRE

39 Application File Format Java source files of an Application are converted to Java class files by the Java compiler Then Java class files will be converted into a.dex (Dalvik Executable) file Due to some optimization, dex files are much smaller in size than the corresponding class files. The.dex file and the resources of an Android project, e.g. the images and XML files, are packed into an.apk (Android Package) file. The resulting.apk file contains all necessary data to run the Android application and can be deployed to an Android device The Android Development Tools (ADT) perform these steps transparently to the user

40 Sandboxing Each Android application lives in its own security sandbox The Android operating system is a multi-user Linux system Each application is a different user with a unique, unknown Linux user ID Permissions for all the files in an application are set to this user ID Each process has its own virtual machine (VM) By default, every application runs in its own Linux process

41 Android SDKs (by Google) Android SDK Includes a debugger, libraries, a handset emulator based on QEMU, documentation, sample code, and tutorials Native Development Kit Development of libraries written in C and other languages Compiled to ARM or x86 native code App Inventor for Android Web-based visual development environment from Google For novice programmers, based on MIT's Open Blocks Java library Offers Access to phone functions and sensors 34 34

42 Installation of Android SDK Download eclipse for Java developers Install the ADT plugin for Eclipse Download the latest SDK tools and platforms using the SDK Manager

43 Installation of Android SDK 36 36

44 Installation of Android SDK 36 36

45 Installation of Android SDK 37 37

46 Installation of Android SDK 37 37

47 Installation of Android SDK 38 38

48 Installation of Android SDK Opens the Android SDK Manager 38 38

49 Google Android - A First Example Professur Schaltkreisund Systementwurf 39

50 Login Use the provided login and password If you change the password -> WRITE IT DOWN! Scientific Linux 6 Eclipse needs to be started from the command line Screenshot vom Pool- Desktop 40 40

51 Eclipse module load android/ eclipse Load module for eclipse Start eclipse Decide where your work will be stored At the first start it will ask for the Android-SDK use existing /sse/eda/adt/adt-bundle-linux-x86_ /sdk 41 41

52 Workspace workspace-screenshot 42 42

53 Existing SDK 43 43

54 HelloWorld Professur Schaltkreisund Systementwurf 44

55 45 45

56 46 46

57 47 47

58 48 48

59 49 49

60 50 50

61 Running the App Launch the Android Virtual Device Manager Create one or more devices reflecting your desired targets Eclipse -> Run As... -> 51 51

62 Create AVD 52 52

63 Tweaking the AVD 53 53

64 Tweaking the AVD 53 53

65 Tweaking the AVD 53 53

66 Emulator 54 54

67 Google Android - Application Basics Professur Schaltkreisund Systementwurf 55

68 Analyzing the App Using the Eclipse SDK... Ending with a working Hello World App after some klicks!"" AndroidManifest.xml!"" assets!"" bin!"" gen!"" libs!"" res #!"" drawable-hdpi #!"" drawable-ldpi #!"" drawable-mdpi #!"" drawable-xhdpi #!"" layout #!"" menu # %"" values %"" src 56 56

69 Analyzing the App Using the Eclipse SDK... Ending with a working Hello World App after some klicks!"" AndroidManifest.xml!"" assets!"" bin!"" gen!"" libs!"" res #!"" drawable-hdpi #!"" drawable-ldpi #!"" drawable-mdpi #!"" drawable-xhdpi #!"" layout #!"" menu # %"" values %"" src 56 Android Manifest 56

70 Analyzing the App Using the Eclipse SDK... Ending with a working Hello World App after some klicks!"" AndroidManifest.xml!"" assets!"" bin!"" gen!"" libs!"" res #!"" drawable-hdpi #!"" drawable-ldpi #!"" drawable-mdpi #!"" drawable-xhdpi #!"" layout #!"" menu # %"" values %"" src 56 Android Manifest Generated Code 56

71 Analyzing the App Using the Eclipse SDK... Ending with a working Hello World App after some klicks!"" AndroidManifest.xml!"" assets!"" bin!"" gen!"" libs!"" res #!"" drawable-hdpi #!"" drawable-ldpi #!"" drawable-mdpi #!"" drawable-xhdpi #!"" layout #!"" menu # %"" values %"" src 56 Android Manifest Generated Code Needed Libraries 56

72 Analyzing the App Using the Eclipse SDK... Ending with a working Hello World App after some klicks!"" AndroidManifest.xml!"" assets!"" bin!"" gen!"" libs!"" res #!"" drawable-hdpi #!"" drawable-ldpi #!"" drawable-mdpi #!"" drawable-xhdpi #!"" layout #!"" menu # %"" values %"" src 56 Android Manifest Generated Code Needed Libraries Resources 56

73 Analyzing the App Using the Eclipse SDK... Ending with a working Hello World App after some klicks!"" AndroidManifest.xml!"" assets!"" bin!"" gen!"" libs!"" res #!"" drawable-hdpi #!"" drawable-ldpi #!"" drawable-mdpi #!"" drawable-xhdpi #!"" layout #!"" menu # %"" values %"" src 56 Android Manifest Generated Code Needed Libraries Resources Java Source Files 56

74 Analyzing the App AndroidManifest.xml file, the "manifest" file Declare all components of an App Identify any user permissions the application requires, such as Internet access or read-access to the user's contacts. Declare the minimum API Level required by the application, based on which APIs the application uses. Declare hardware and software features used or required by the application, such as a camera, bluetooth services, or a multitouch screen. API libraries the application needs to be linked against (other than the Android framework APIs), such as Google Maps library. And more

75 58 58

76 Manifest File <manifest xmlns:android=" package="de.tuchemnitz.etit.sse.sesafirstapp" android:versioncode="1" android:versionname="1.0" > <uses-sdk android:minsdkversion="10" android:targetsdkversion="15" /> <application > <activity android:name=".mainactivity" > <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter> </activity> <activity android:name=".displaymessageactivity" > <meta-data android:name="android.support.parent_activity" android:value="de.tuchemnitz.etit.sse.sesafirstapp.mainactivity" /> </activity> </application> </manifest> 59 59

77 Analyzing the App Resources like layouts, strings, icons, images Are kept separated from the source code The containing folders define their purpose The.xml-Files will automatically be converted to Java code See gen/.../r.java 60 60

78 String Resources <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">sesafirstapp</string> <string name="menu_settings">settings</string> <string name="title_activity_main">mainactivity</string> </resources> 61 61

79 Layout An activity is made up of Views and Viewgroups Views are typically UI objects ViewGroups are invisible view containers that define how the child views are laid out 62 62

80 Changing the Layout Professur Schaltkreisund Systementwurf 63

81 Changing the Layout First What do you like to display? Second Add the needed Strings Third Add the needed ViewGroups and Views 64 64

82 Changing the Layout First What do you like to display? Second Add the needed Strings Third Add the needed ViewGroups and Views 64 64

83 String Resources <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">sesafirstapp</string> <string name="menu_settings">settings</string> <string name="title_activity_main">mainactivity</string> <string name="edit_message">enter a message</string> <string name="button_send">send</string> </resources> 65 65

84 A Linear Layout <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=" android" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" > </LinearLayout> 66 66

85 Adding an Element <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=" android" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" > <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> 67 67

86 Adding a Second View <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" > <EditText android:id="@+id/edit_message" android:layout_width="wrap_content" 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> 68 68

87 Adding a Second View <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" > <EditText android:id="@+id/edit_message" android:layout_width="wrap_content" 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> 68 68

88 Tweaking Layout & Performance <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=" android" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" > <EditText android:layout_weight="1" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> 69 69

89 Tweaking Layout & Performance <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=" android" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" > <EditText android:layout_weight="1" android:layout_width="wrap_content" android:layout_height="wrap_content" /> Added a weight to let this view consume the available space <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/button_send" /> </LinearLayout> 69 69

90 Tweaking Layout & Performance <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=" android" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" > <EditText android:layout_weight="1" android:layout_width="wrap_content" android:layout_height="wrap_content" /> Added a weight to let this view consume the available space This depreciates the calculation of the contents width <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/button_send" /> </LinearLayout> 69 69

91 Tweaking Layout & Performance <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" > <EditText android:layout_weight="1" android:layout_width="0dip" android:layout_height="wrap_content" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> 70 70

92 Tweaking Layout & Performance <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" > <EditText android:layout_weight="1" android:layout_width="0dip" android:layout_height="wrap_content" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> 70 70

93 Tweaking Layout & Performance <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" > <EditText android:layout_weight="1" android:layout_width="0dip" android:layout_height="wrap_content" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> 70 70

94 Understanding the Weight Default is all zero Numbers are added Taken space is weight/summ e.g. 1, 2, 0, 1 = 4 1/4, 2/4, 0/4, 1/

95 Understanding the Weight Default is all zero Numbers are added Taken space is weight/summ e.g. 1, 2, 0, 1 = 4 1/4, 2/4, 0/4, 1/

96 Understanding the Weight Default is all zero Numbers are added Taken space is weight/summ e.g. 1, 2, 0, 1 = 4 1/4, 2/4, 0/4, 1/

97 Understanding the Weight Default is all zero Numbers are added Taken space is weight/summ e.g. 1, 2, 0, 1 = 4 1/4, 2/4, 0/4, 1/

98 Understanding the Weight Default is all zero Numbers are added Taken space is weight/summ e.g. 1, 2, 0, 1 = 4 1/4, 2/4, 0/4, 1/

99 Understanding the Weight Default is all zero Numbers are added Taken space is weight/summ e.g. 1, 2, 0, 1 = 4 1/4, 2/4, 0/4, 1/

100 Application Structure Professur Schaltkreisund Systementwurf 72

101 Application Basics Activities A single (independent) screen with a user interface An application may consist of several activities Activities can be called by other Applications Services A component that runs in the background No user interface Content providers Manages a shared set of application data Broadcast receivers Responds to system-wide broadcast announcements 73 73

102 Application Basics Apps do not have a main() function Activities always run in the context of the owning Application (not in the caller context) Therefore a intend - a special type of message to the system - is needed Intend Asynchronous messages which allow the application to request functionality from other components 74 74

103 Activities Better / own Image 75 75

104 Application Basics Widgets Interactive components mostly used on the home screen Typically display some kind of data and allow to perform actions Even more... E.g. Live Folders and Live Wallpapers 76 76

105 Application Basics Views and ViewGroups The GUI of an app is build up on Views and ViewGroups View objects are usually UI widgets such as buttons or text fields ViewGroup objects are invisible view containers such as a grid or a vertical list. Source: Developpers.google.com 77 77

106 Application Basics Fragments Run in the context of an Activity Encapsulate application code Improve reuse Support different sized devices An example of how two UI modules defined by fragments can be combined into one activity for a tablet design but separated for a handset design. Source: Developpers.google.com 78 78

107 No line of java, yet? Up to this point there was no need to write a single line of Java code. But we have a running Android App

108 No line of java, yet? Up to this point there was no need to write a single line of Java code. But we have a running Android App... package de.tuchemnitz.etit.sse.sesafirstapp; import android.os.bundle; import android.app.activity; import android.view.menu; public class MainActivity extends Activity public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); } public boolean oncreateoptionsmenu(menu menu) { getmenuinflater().inflate(r.menu.activity_main, menu); return true; } 79 79

109 Google Android - Extending the App Professur Schaltkreisund Systementwurf 80

110 Syncing In case of problems (or just to make sure...) Use version provided by me Close eclipse cd into your workspace rm -rf SESAFirstApp curl rsrc/sesafirstapp.v0.1.0.tar tar xv 81 81

111 Push the Button Professur Schaltkreisund Systementwurf 82

112 Push the Button <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=" android" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" > <EditText android:layout_weight="1" android:layout_width="0dp" android:layout_height="wrap_content" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:onclick="sendmessage" /> </LinearLayout> 83 83

113 Push the Button <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=" android" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" > <EditText android:layout_weight="1" android:layout_width="0dp" android:layout_height="wrap_content" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:onclick="sendmessage" /> </LinearLayout> 83 83

114 Push the Button <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=" android" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" > <EditText android:layout_weight="1" android:layout_width="0dp" android:layout_height="wrap_content" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:onclick="sendmessage" /> This nominates the callback function in the activity </LinearLayout> 83 83

115 Adding the Callback /** Called when the user clicks the Send button */ public void sendmessage(view view) { // Do something in response to button } 84 84

116 Adding the Callback /** Called when the user clicks the Send button */ public void sendmessage(view view) { // Do something in response to button } And fill it with code to start a second Activity... /** Called when the user clicks the Send button */ 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); } 84 84

117 Magic Keys Several unknown keywords (red underlined) Try Ctrl+Shift+O This will automatically add missing imports Try Ctrl+Shift+F This will format your code /** Called when the user clicks the Send button */ 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); } 85 85

118 What does the Code? Intent intent = new Intent(this, DisplayMessageActivity.class); Object that provides runtime binding between separate components (such as two activities). Represents an app s "intent to do something". Used for a wide variety of tasks most often used to start another activity Here: start an activity called DisplayMessageActivity 86 86

119 What does the Code? EditText edittext = (EditText) findviewbyid(r.id.edit_message); Create an EditText object in the Activity Connect it to the edit_message in the view findviewbyid is often used to get handles from views in the layout 87 87

120 What does the Code? String message = edittext.gettext().tostring(); intent.putextra(extra_message, message); Create a String object Fill it with the content of the edit_message view Hand it over to the intent An Intent can carry a collection of various data types as key-value pairs 88 88

121 What does the Code? public class MainActivity extends Activity { public final static String EXTRA_MESSAGE = "com.example.myfirstapp.message";... } The key must be known to both activities Thus defining it as a public constant is a good way It s a good practice to prefix the key with the app s package name 89 89

122 What does the Code? public class MainActivity extends Activity { public final static String EXTRA_MESSAGE = "com.example.myfirstapp.message"; public... class MainActivity extends Activity { } /** String constants for Intents */ public final static String EXTRA_MESSAGE = "de.tuchemnitz.etit.sse.sesafir stapp.message"; The key must be known to both Thus public void defining oncreate(bundle it as savedinstancestate) a public constant { is a good super.oncreate(savedinstancestate); way setcontentview(r.layout.activity_main); }... It s a good practice to prefix the key with the app s package name 89 89

123 What does the Code? startactivity(intent); Create a String object Fill it with the content of the edit_message view Hand it over to the intent An Intent can carry a collection of various data types as key-value pairs 90 90

124 A Second Activity Professur Schaltkreisund Systementwurf 91

125 A Second Activity Eclipse SDK helps here as well Using the New Project wizard Add all needed files Changes the manifest and strings 92 92

126 Create the Activity 93 93

127 Create the Activity 94 94

128 Activity Basic Information 95 95

129 96 96

130 96 96

131 The Second Activity 97 97

132 Changed Manifest Automatically done: Add Activity to manifest Add some strings </intent-filter> </activity> <activity android:name="de.tuchemnitz.etit.sse.sesafirstapp.displaymessageactivity" android:parentactivityname="de.tuchemnitz.etit.sse.sesafirstapp.mainactivity" > <meta-data android:name="android.support.parent_activity" android:value="de.tuchemnitz.etit.sse.sesafirstapp.mainactivity" /> </activity> </application> 98 98

133 Use the public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); // get the Intent Intent intent = getintent(); // get the message we placed in String message = intent.getstringextra(mainactivity.extra_message); // Create a TextView and fill it with the message TextView textview = new TextView(this); textview.settextsize(40); textview.settext(message); // Set the text view as the activity layout setcontentview(textview); } /* * saved for later use * setcontentview(r.layout.activity_display_message); */ getactionbar().setdisplayhomeasupenabled(true); 99 99

134 Use the Intent Get the intent Recall the string by using the key Remember: key-value-pair... // get the Intent Intent intent = getintent(); // get the message we placed in String message = intent.getstringextra(mainactivity.extra_message);

135 Use the Intent... // Create a TextView and fill it with the message TextView textview = new TextView(this); textview.settextsize(40); textview.settext(message); // Set the text view as the activity layout setcontentview(textview);... Create TextView and fill it Change some attributes For now we don t use xml layout... But create the layout programmatically

136 Try It

137 A xml Layout Professur Schaltkreisund Systementwurf 103

138 Use xml public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); // get the Intent Intent intent = getintent(); // get the message we placed in String message = intent.getstringextra(mainactivity.extra_message); } // Create a TextView and fill it with the message TextView textview = (TextView) findviewbyid(r.id.view_message); textview.settext(message); // adapt the view setcontentview(r.layout.activity_display_message);... Better use.xml Layout Better to maintain and to develop

139 xml Layout <RelativeLayout xmlns:android=" android" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerhorizontal="true" android:layout_centervertical="true" android:textsize="40sp" tools:context=".displaymessageactivity" /> </RelativeLayout>

140 xml Layout <RelativeLayout xmlns:android=" android" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerhorizontal="true" android:layout_centervertical="true" android:textsize="40sp" tools:context=".displaymessageactivity" /> </RelativeLayout>

141 xml Layout <RelativeLayout xmlns:android=" android" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerhorizontal="true" android:layout_centervertical="true" android:textsize="40sp" tools:context=".displaymessageactivity" /> </RelativeLayout>

142 #Error So for now - The App stopped working Next Point to Sync curl SESA/rsrc/SESAFirstApp.v0.2.0.tar tar xv

143 Debugging Professur Schaltkreisund Systementwurf 107

144 LogCat Logger for messages from the phone / emulator Offering a lot of features Filters,... Write own messages by using Log

145 Using the Logger /** String prefix for Logging */ private static final String TAG = "SFA_Main"; /*SESAFirstApp Main Activity public void oncreate(bundle savedinstancestate) { } Log.d(TAG, "oncreate called"); super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main);

146 Using the Logger /** String prefix for Logging */ private static final String TAG = "SFA_Main"; /*SESAFirstApp Main Activity public void oncreate(bundle savedinstancestate) { } Log.d(TAG, "oncreate called"); super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); v(string, String) (verbose) d(string, String) (debug) i(string, String) (information) w(string, String) (warning) e(string, String) (error)

147 Add Debugging Information printf debugging is widely used Helpful in many situations It s not as good as assertions or as accurate as using a debugger public void sendmessage(view view) {... Log.i(TAG, "Adding: " + message + " to intent"); intent.putextra(extra_message, message); startactivity(intent); }

148 Add Debugging Information printf debugging is widely used Helpful in many situations It s not as good as assertions or as accurate as using a public void oncreate(bundle savedinstancestate) {... // get the message we placed in String message = intent.getstringextra(mainactivity.extra_message); Log.i(TAG, "Got: " + message + " from Intent");... // adapt the view setcontentview(r.layout.activity_display_message); }

149 Check the Application It s still not working What does LogCat show? Use Filters to reduce the number of messages

150 More public void oncreate(bundle savedinstancestate) {... // Create a TextView and fill it with the message TextView textview = (TextView) findviewbyid(r.id.view_message); if (textview!= null) { Log.d(TAG, "Found the TextView"); } else { Log.d(TAG, "Text view not found!"); } textview.settext(message); Log.d(TAG, "After insertion"); } // adapt the view setcontentview(r.layout.activity_display_message); Log.d(TAG, "oncreate Finished"); Narrow down the error by guarding all actions with a print

151 Found the Bug if (textview!= null) { Log.d(TAG, "Found the TextView"); } else { Log.d(TAG, "Text view not found!"); } textview.settext(message); Log.d(TAG, "After insertion"); No TextView is found matching this id Why?

152 Simple Solution... // get the message we placed in String message = intent.getstringextra(mainactivity.extra_message); Log.i(TAG, "Got: " + message + " from Intent"); // adapt the view setcontentview(r.layout.activity_display_message); Log.d(TAG, "Created the Layout"); // Create a TextView and fill it with the message TextView textview = (TextView) findviewbyid(r.id.view_message);

153 Simple Solution... // get the message we placed in String message = intent.getstringextra(mainactivity.extra_message); Log.i(TAG, "Got: " + message + " from Intent"); // adapt the view setcontentview(r.layout.activity_display_message); Log.d(TAG, "Created the Layout"); // Create a TextView and fill it with the message TextView textview = (TextView) findviewbyid(r.id.view_message);

154 Using the Debugger

155 Using the Debugger

156 Using the Debugger

157 Add Variables to Watch Add all variables of interest Right-Click and choose Watch Hold the mouse over a variable to see the current state

158 Running Step by Step Run Stop Step into Step over Step over to execute the line Step into to enter the next level of depth

159 textview is still null after executing findviewbyid()

160 Google Android - Application Lifecycle Professur Schaltkreisund Systementwurf 122

161 The Activity Lifecycle All other states are only transient!

162 The Activity Lifecycle static states All other states are only transient!

163 Static States Resumed The activity is in the foreground and the user can interact with it. Paused Activity is partially obscured by another activity Activity does not receive user input and cannot execute any code Stopped Activity is completely hidden and not visible to the user The activity instance and all its state informations such as member variables is retained, but it cannot execute any code

164 Activity Startup Startup order for each activity is oncreate() onstart() onresume() Which Activity is called after pressing the Apps icon is defined in the manifest <activity android:name=".mainactivity" <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter> </activity>

165 Activity Startup oncreate() The App is created / started Perform basic application startup logic that should happen only once for the entire life of the activity onstart() The Activity becomes visible onresume() The Activity becomes active

166 Activity Shutdown ondestroy() The last method called when App is destroyed Activity instance is being completely removed from the system memory In (nearly) all cases onpause() and onstop() are called in advance of ondestroy() Often not needed Local class references are (automatically) destroyed with the activity Most cleanup should be done during onpause() and onstop()

167 All States of Main public void oncreate(bundle savedinstancestate) { Log.i(TAG, "oncreate called"); super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); protected void onstart() { Log.i(TAG, "onstart called"); super.onstart(); // The activity is about to become visible. protected void onresume() { Log.i(TAG, "onresume called"); super.onresume(); // The activity has become visible (it is now "resumed"). protected void onpause() { Log.i(TAG, "onpause called"); super.onpause(); // Another activity is taking focus (this activity is about to be // "paused"). protected void onstop() { Log.i(TAG, "onstop called"); super.onstop(); // The activity is no longer visible (it is now "stopped") EditText edittext = (EditText) findviewbyid(r.id.edit_message); edittext.settext(""); protected void ondestroy() { Log.i(TAG, "ondestroy called"); super.ondestroy(); // The activity is about to be destroyed. } 128 Don t try to copy it! 128

168 States of DisplayMessageActivity public class DisplayMessageActivity extends Activity { /** String prefix for Logging */ private static final String TAG = "SFA_Display"; /* SESAFirstApp Display Activity public void oncreate(bundle savedinstancestate) { Log.i(TAG, "oncreate called"); super.oncreate(savedinstancestate); setcontentview(r.layout.activity_display_message); public void onstart() { Log.i(TAG, "onstart called"); // call parents onstart() super.onstart(); // Get the message from the intent Intent intent = getintent(); String message = intent.getstringextra(mainactivity.extra_message); TextView text = (TextView) findviewbyid(r.id.displaytextview); text.settext(message); protected void onresume() { Log.i(TAG, "onresume called"); super.onresume(); // The activity has become visible (it is now "resumed"). protected void onpause() { Log.i(TAG, "onpause called"); super.onpause(); // Another activity is taking focus (this activity is about to be // "paused"). protected void onstop() { Log.i(TAG, "onstop called"); super.onstop(); // The activity is no longer visible (it is now "stopped") protected void ondestroy() { Log.i(TAG, "ondestroy called"); super.ondestroy(); // The activity is about to be destroyed. } 129 Don t try to copy it! 129

169 States of DisplayMessageActivity public class DisplayMessageActivity extends Activity { /** String prefix for Logging */ private static final String TAG = "SFA_Display"; /* SESAFirstApp Display Activity public void oncreate(bundle savedinstancestate) { Log.i(TAG, "oncreate called"); super.oncreate(savedinstancestate); setcontentview(r.layout.activity_display_message); public void onstart() { Log.i(TAG, "onstart called"); // call parents onstart() super.onstart(); // Get the message from the intent Intent intent = getintent(); String message = intent.getstringextra(mainactivity.extra_message); TextView text = (TextView) findviewbyid(r.id.displaytextview); text.settext(message); protected void onresume() { Log.i(TAG, "onresume called"); super.onresume(); // The activity has become visible (it is now "resumed"). protected void onpause() { Log.i(TAG, "onpause called"); super.onpause(); // Another activity is taking focus (this activity is about to be // "paused"). protected void onstop() { Log.i(TAG, "onstop called"); super.onstop(); // The activity is no longer visible (it is now "stopped") protected void ondestroy() { Log.i(TAG, "ondestroy called"); super.ondestroy(); // The activity is about to be destroyed. } 130 Don t try to copy it! 130

170 States of DisplayMessageActivity public class DisplayMessageActivity extends Activity { /** String prefix for Logging */ private static final String TAG = "SFA_Display"; /* SESAFirstApp Display Activity public void oncreate(bundle savedinstancestate) { Log.i(TAG, "oncreate called"); super.oncreate(savedinstancestate); setcontentview(r.layout.activity_display_message); public void onstart() { Log.i(TAG, "onstart called"); // call parents onstart() super.onstart(); // Get the message from the intent Intent intent = getintent(); String message = intent.getstringextra(mainactivity.extra_message); TextView text = (TextView) findviewbyid(r.id.displaytextview); text.settext(message); protected void onresume() { Log.i(TAG, "onresume called"); super.onresume(); // The activity has become visible (it is now "resumed"). protected void onpause() { Log.i(TAG, "onpause called"); super.onpause(); // Another activity is taking focus (this activity is about to be // "paused"). protected void onstop() { Log.i(TAG, "onstop called"); super.onstop(); // The activity is no longer visible (it is now "stopped") protected void ondestroy() { Log.i(TAG, "ondestroy called"); super.ondestroy(); // The activity is about to be destroyed. } Download & Extract now! curl SESA/rsrc/SESAFirstApp.v0.2.1.tar tar xv 130 Don t try to copy it! 130

171 Remember the public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); // get the Intent Intent intent = getintent(); // get the message we placed in String message = intent.getstringextra(mainactivity.extra_message); } // Create a TextView and fill it with the message TextView textview = (TextView) findviewbyid(r.id.view_message); textview.settext(message); // adapt the view setcontentview(r.layout.activity_display_message);... Recreate the Code with the bug!!

172 A Second Approach OnStart() Application is about to get visible Here the layout is already set This also seems to be a good place for the text public void onstart() { // call parents onstart() super.onstart(); // Get the message from the intent Intent intent = getintent(); String message = intent.getstringextra(mainactivity.extra_message); TextView text = (TextView) findviewbyid(r.id.displaytextview); text.settext(message); }

173 One more Example Add to the protected void onstop() { Log.d(TAG, "onstop called"); super.onstop(); // The activity is no longer visible (it is now "stopped") // so we clean the TextEdit EditText edittext = (EditText) findviewbyid(r.id.edit_message); edittext.settext(""); } Reset the TextView in onstop()

174 SESAFirstApp

175 SESAFirstApp Find complete example: curl SESA/rsrc/SESAFirstApp.v0.3.0.tar tar xv

176 Sensors and Keys Professur Schaltkreisund Systementwurf 135

177 Volume Changer Create a new Android project. Create a suitable logo. Create a sufficiently complex layout. Create needed strings. Find this Application at: curl SESA/rsrc/ChangeAllVolumes.v0.1.0.git tar xv