Gauthier Picard - Accueil

71
Android Programming Gauthier Picard MINES Saint-Étienne October , This presentation is based on Jean-Paul Jamont’s one (Université Pierre Mendès France, IUT de Valence) Android Programming Gauthier Picard /

Transcript of Gauthier Picard - Accueil

Page 1: Gauthier Picard - Accueil

Android™ Programming

Gauthier Picard

MINES Saint-Étienne

October 24, 2018

This presentation is based onJean-Paul Jamont’s one

(Université Pierre Mendès France, IUT de Valence)

Android™ Programming Gauthier Picard 1 / 53

Page 2: Gauthier Picard - Accueil

Agenda

Android Overview

Basics

Android Projects

Activities

XML Layout

Manifest

Some Android-speci�c Classes

References

Android™ Programming Gauthier Picard 2 / 53

Page 3: Gauthier Picard - Accueil

AgendaAndroid Overview

Basics

Android Projects

Activities

XML Layout

Manifest

Some Android-speci�c Classes

References

Android™ Programming Gauthier Picard 3 / 53

Page 4: Gauthier Picard - Accueil

What is Android?

An open source operating systemI A mobile-device-oriented operating system

I It consists in a set of software to interface hardware and applicative softwareI An open source operating system

I source code is availableI huge developper community

I An operating system based on the Linux kernelI A free development environment

I Programming with Java or C languageI Development kit (SDK Android) available at

http://developer.android.com/sdk/index.html

Android™ Programming Gauthier Picard 4 / 53

Page 5: Gauthier Picard - Accueil

Android Version History

A lot of versions...The di�erent versions of Android are all named as desserts since version 1.5 and followan alphabetical order:

100%

90%

80%

70%

60%

50%

40%

30%

20%

10%

0%

Dec 2

009

Feb

2010

Apr 2

010

Jun

2010

Aug 2

010

Oct 2

010

Dec 2

010

Feb

2011

Apr 2

011

Jun

2011

Aug 2

011

Oct 2

011

Dec 2

011

Feb

2012

Apr 2

012

Jun

2012

Aug 2

012

Oct 2

012

Dec 2

012

Feb

2013

Apr 2

013

Jun

2013

Aug 2

013

Dec 2

013

Feb

2014

Apr 2

014

Oct 2

013

Jun

2014

Aug 2

014

Dec 2

014

Feb

2015

Oct 2

014*

* no d

ata

Apr 2

015

Jun

2015

Aug 2

015

* no d

ata

Jul 2

015*

Oct 2

015

Dec 2

015

Feb

2016

Apr 2

016

Jun

2016

100%

90%

80%

70%

60%

50%

40%

30%

20%

10%

0%

Aug 2

016

Oct 2

016*

Dec 2

016

* no d

ata

Feb

2017

Apr 2

017

Jun

2017

Aug 2

017

Oct 2

017

Dec 2

017

Feb

2018

Android version1.1

1.5

1.6

2.0

2.0.1

2.1

2.2

2.3-2.3.2

2.3.3-2.3.7

3.0

3.1

3.2

4.0-4.0.2

4.0.3-4.0.4

4.1

4.2

4.3

4.4

Cupcake

Donut

Eclair

Froyo

Gingerbread

Honeycomb

Ice CreamSandwich

Jelly Bean

KitKat

Gingerbread

Eclair

Eclair

Honeycomb

Honeycomb

Jelly Bean

Jelly Bean

5.0 Lollipop

Ice CreamSandwich

5.1 Lollipop

6.0 Marshmallow

7.0-7.1 Nougat

8.0-8.1 Oreo

Android™ Programming Gauthier Picard 5 / 53

Page 6: Gauthier Picard - Accueil

Android Platforms: More and more equipments

Phones and PDA

Tablets

Google TV

!

Consoles

Android™ Programming Gauthier Picard 6 / 53

Page 7: Gauthier Picard - Accueil

Android and its competitors

Open Handset AllianceI Creation: 5th November 2007, initiated by GoogleI Objectives: Develop open norms for mobile phone devicesI Members: 84 technology and mobile companies

CompetitorsI Apple with iOSI Research In Motion (RIM) with BlackBerry OSI Microsoft with Windows PhoneI Samsung with Bada (even Samsung is more and more using Android)I HP with Palm webOS then webOS (stopped in 2011)I Nokia with Symbian OS (stopped in 2011, Nokia is using now Windows Phone)I ...

Android™ Programming Gauthier Picard 7 / 53

Page 8: Gauthier Picard - Accueil

Android and its competitors (cont.)

Share of worldwide 2009 to 2017 smartphone sales to end users by operating system, according to Statistica

Android™ Programming Gauthier Picard 8 / 53

Page 9: Gauthier Picard - Accueil

The Challenges

Android FunctionnalitiesI Applicative FrameworkI Dalvik Virtual MachineI Integrated Web BrowserI 2D and 3D Graphical LibraryI SQLiteI Audio and Video CodecsI WiFi, EDGE, 3G, Bluetooth...I Camera, GPS, Accelerometer, Compass...

Android™ Programming Gauthier Picard 9 / 53

Page 10: Gauthier Picard - Accueil

The Challenges (cont.)

ConstraintsI Low frequency CPUI Little available RAMI Low write access on �ash diskI Application-speci�c lifecycle (energy-e�ciency, limited resources)I Low rate and intermittent networksI Speci�c HMI design

I Small screens: HVGA (320x480)I portrait and landscapeI Small fonts can be unreadable (DPI)I Low resolution of tactil sensor (25 pixels)

Android™ Programming Gauthier Picard 10 / 53

Page 11: Gauthier Picard - Accueil

Downloading and Uploading Apps

Google Play Store (former Android Market)Standard system to upload/download appsI No �ltering/veri�cation of appsI Navigation more di�cult than AppMarket (search by category, keywords, price)I Requires a certi�ed terminal (camera, 3G, compass...)I Authorization management before installationI 2.7 million apps published in 2017 (57% free-of-charge)

If you want to sell your apps:I 25$ to register as a developerI 85% of the app price to the developer, 15% to GoogleI Revenue earned from the Google Play is paid to developers via Google Wallet

Android™ Programming Gauthier Picard 11 / 53

Page 12: Gauthier Picard - Accueil

Downloading and Uploading Apps (cont.)

Other PlatformsThere exist other legal application distribution platforms (i.e. authorized by Google).They allow access to non certi�ed devicesI AppsLib (Archos) : http://appslib.comI AndroLib : http://www.androlib.comI Market SamsungI ...

Android™ Programming Gauthier Picard 12 / 53

Page 13: Gauthier Picard - Accueil

AgendaAndroid Overview

Basics

Android Projects

Activities

XML Layout

Manifest

Some Android-speci�c Classes

References

Android™ Programming Gauthier Picard 13 / 53

Page 14: Gauthier Picard - Accueil

Important Terms

ActivityI Building block for user interfacesI Equivalent to a window (Windows, Linux) or a dialog boxI An activity may not have any user interface (in case of services)

Content providerI Abstraction level for any data stored in the deviceI Android encourages the provision of its own data to other programs⇒ the content provider enables this by proposing an access control mechanism

Android™ Programming Gauthier Picard 14 / 53

Page 15: Gauthier Picard - Accueil

Important Terms (cont.)IntentI An intent is a kind of system message called event to glue activitiesI Emitted by the device to alert applications that a certain event occured (systemevent) or by any other app (applicative event).I System: insertion of SD card, SMS receivedI Applicative: “App HelloWorld starts”, “The user is arriving in Paris”

ServiceI A Service is an application component representing either an application’s desireto perform a longer-running operation while not interacting with the user or tosupply functionality for other applications to use

I Does not need any UII Examples:

I Service verifying RSS �ux updatesI Service enabling to listen a given playlist (independently from any activity)

Android™ Programming Gauthier Picard 15 / 53

Page 16: Gauthier Picard - Accueil

Important Terms (cont.)

ManifestI Starting point for every Android appI Declares what the app contains (activities, services, ...)I Speci�es how components are linked to Android (e.g. what is displayed in themenu?)

I Speci�es permissions for the app (e.g. webcam, network, location access, ...)

WidgetI Portmanteau combining window and gadgetI Concretely it is a GUI component (labels, text �elds, buttons, ...)

Android™ Programming Gauthier Picard 16 / 53

Page 17: Gauthier Picard - Accueil

Important Terms (cont.)

ViewI Represents the basic building block for user interface componentsI Occupies a rectangular area on the screen and is responsible for drawing and eventhandling

I View is the base class for widgets

Container (View Group)I A View Group is a special view that can contain other views (called children)I Used to have a set of widgets to the desired presentationI Most tools to build GUIs provide layout managers that are most frequentlyorganized in containers

Android™ Programming Gauthier Picard 17 / 53

Page 18: Gauthier Picard - Accueil

Important Terms (cont.)

XMLI Extensible Markup LanguageI Used to structure data

XML LayoutI Used to design GUI easier than using JavaI Used to instantiate widgets, position views and viewgroupsI The XML �le is often generated using tools to build graphically GUIs

Android™ Programming Gauthier Picard 18 / 53

Page 19: Gauthier Picard - Accueil

Important Terms (cont.)

Uniform Resource Identi�er (URI)I is a string of characters used to identify a name of a web resource (real or not)I respects the Internet norm RFC 3986I Some URIs:

I Uniform Resource Locator (URL): identi�es a resource on a network and provides meansof acting upon or obtaining a representation of the resource by providing both theprimary access mechanism, and the network "location"Example: http://www.wikipedia.org/ identi�es a resource (Wikipedia’s homepage) and implies arepresentation of this resource (HTML page) can be obtained via the HTTP protocol from an network host whosename is www.wikipedia.org

I Uniform Resource Name (URN): identi�es a resource by its name in a speci�c namespaceExample: urn:isbn:0-395-36341-1 identi�es a resource by an ISBN number, allows to reference a book, but doesnot indicate where nor how to obtain a physical copy of it

Android™ Programming Gauthier Picard 19 / 53

Page 20: Gauthier Picard - Accueil

Important Terms (cont.)

Android Virtual DevicesI AVDs allows to simulate the execution of an Android device on a computerI These devices are customizable (Android version, CPU model, memory, ...)⇒ Eases the development and the la implementation of apps

Android™ Programming Gauthier Picard 20 / 53

Page 21: Gauthier Picard - Accueil

Android Software Architecture

Major componentsI The Linux KernelI Hardware Abstraction Layer (HAL)I Android RuntimeI Native C/C++ LibrariesI Java API FrameworkI System Apps

Android™ Programming Gauthier Picard 21 / 53

Page 22: Gauthier Picard - Accueil

AgendaAndroid Overview

Basics

Android Projects

Activities

XML Layout

Manifest

Some Android-speci�c Classes

References

Android™ Programming Gauthier Picard 22 / 53

Page 23: Gauthier Picard - Accueil

Create a project from an existing sample

Android™ Programming Gauthier Picard 23 / 53

Page 24: Gauthier Picard - Accueil

Create a project from an existing sample

Android™ Programming Gauthier Picard 23 / 53

Page 25: Gauthier Picard - Accueil

Create a project from an existing sample

Android™ Programming Gauthier Picard 23 / 53

Page 26: Gauthier Picard - Accueil

Create a project from an existing sample

Android™ Programming Gauthier Picard 23 / 53

Page 27: Gauthier Picard - Accueil

Create your own project

Android™ Programming Gauthier Picard 24 / 53

Page 28: Gauthier Picard - Accueil

Create your own project

Android™ Programming Gauthier Picard 24 / 53

Page 29: Gauthier Picard - Accueil

Create your own project

Android™ Programming Gauthier Picard 24 / 53

Page 30: Gauthier Picard - Accueil

Create your own project

Android™ Programming Gauthier Picard 24 / 53

Page 31: Gauthier Picard - Accueil

Create your own project

Android™ Programming Gauthier Picard 24 / 53

Page 32: Gauthier Picard - Accueil

Android Project Directory Structure

Android™ Programming Gauthier Picard 25 / 53

Page 33: Gauthier Picard - Accueil

Android Project Files

.idea : Directory for IntelliJ IDEA settingsapp : Application module directories and �les

build : This directory stories the build output for all project modulesgradle : Contains the gradler-wrapper �les

.gitignore : Speci�es the untracked �les that Git should ignorebuild.gradle : Customizable properties for the build systemgradle.properties : Project-wide Gradle settings

gradlew : Gradle startup script for Unixgradlew.bat : Gradle startup script for Windowslocal.properties : Customizable computer-speci�c properties for the build system,

such as the path to the SDK installation.iml : Module �le created by the IntelliJ IDEA to store module information

settings.gradle : Speci�es the sub-projects to build

Android™ Programming Gauthier Picard 26 / 53

Page 34: Gauthier Picard - Accueil

Android Application Modules

build/ : Contains build folders for the speci�ed build variantslibs/ : Contains private librariessrc/ : Contains your stub Activity �le, which is stored at

src/main/java//ActivityName>.java

androidTest/ : Contains the instrumentation testsmain/java/com.>project<.>app< : Contains Java code source for the app activitiesmain/gen/ : Contains the Java �les generated by Android Studio, such as your R.java

�lemain/assets/ : This is empty ; you can use it to store raw asset �les

Android™ Programming Gauthier Picard 27 / 53

Page 35: Gauthier Picard - Accueil

Android Application Modules (cont.)main/res/ : Contains application resources, such as drawable �les, layout �les, and

string values in the following directoriesanim/ : For XML �les that are compiled into animation objects

color/ : For XML �les that describe colorsdrawable/ : For bitmap �les (PNG, JPEG, or GIF), 9-Patch image �les, and

XML �les that describe Drawable shapes or Drawable objectsthat contain multiple states (normal, pressed, or focused)

layout/ : XML �les that are compiled into screen layouts (or part of ascreen)

menu/ : For XML �les that de�ne application menusraw/ : For arbitrary raw asset �les

values/ : For XML �les that de�ne resources by XML element typexml/ : For miscellaneous XML �les that con�gure application

componentsAndroidManifest.xml : The control �le that describes the nature of the application and

each of its components.gitignore/ : Speci�es the untracked �les ignored by git

app.iml/ : IntelliJ IDEA modulebuild.gradle : Customizable properties for the build system

Android™ Programming Gauthier Picard 28 / 53

Page 36: Gauthier Picard - Accueil

AgendaAndroid Overview

Basics

Android Projects

Activities

XML Layout

Manifest

Some Android-speci�c Classes

References

Android™ Programming Gauthier Picard 29 / 53

Page 37: Gauthier Picard - Accueil

What is an Activity?De�nition (Activity)

An Activity is an application component that provides a screen with which userscan interact in order to do something, such as dial the phone, take a photo, sendan email, or view a map. Each activity is given a window in which to draw itsuser interface. The window typically �lls the screen, but may be smaller than thescreen and �oat on top of other windows.

I An Activity is a UI for a use case (à la UML):Example: Consider a SMS sending appI One activity to choose the contactI One activity to write the messageI One activity to display the message history

I From an operational point of view:I An activity must extends the android.app.ActivityI An activity is independent from the other activities BUT:

I You must specify a starting activity (the �rst one to be used)I You must chain the activities (an activity activates another one)

I We consider (for simpli�cation) that one activity corresponds to one XML layout

Android™ Programming Gauthier Picard 30 / 53

Page 38: Gauthier Picard - Accueil

Activity Lifecycle

onCreate():I called when the activity is createdI if this is the �rst activity of the app, thismethod is executed when the user call the app

I this method is used to initialize:I the XML viewI if necessary, the temporary �les and data

Android™ Programming Gauthier Picard 31 / 53

Page 39: Gauthier Picard - Accueil

Activity Lifecycle

onRestart():I called after the activity has been stopped, justprior to it being started again

I always followed by onStart()I this method is therefore called when the appbecomes the foreground app after a longpause

Android™ Programming Gauthier Picard 31 / 53

Page 40: Gauthier Picard - Accueil

Activity Lifecycle

onStart():I called just before the activity becomes visibleto the user

I this method is called after each call toonCreate() or onRestart()

I followed by onResume() if the activity comesto the foreground, or onStop() if it becomeshidden

I if necessary, it reloads data saved before theprevious interruption

Android™ Programming Gauthier Picard 31 / 53

Page 41: Gauthier Picard - Accueil

Activity Lifecycle

onResume():I called just before the activity starts interactingwith the user (foreground)

I called after each onStart()I at this point the activity is at the top of theactivity stack, with user input going to it

I always followed by onPause()I typically:

I it manages the connexion to the databaseI it updates data that may be changed before

onResume()

Android™ Programming Gauthier Picard 31 / 53

Page 42: Gauthier Picard - Accueil

Activity Lifecycle

onPause():I Called when:

I the system is about to start resuming anotheractivity

I the user asks a finish() for this activityI the system needs to free some memory

I automatically called before onStop()I typically:

I commit unsaved changes to persistent dataI stop animationsI disconnect the database. . .

I It should do whatever it does very quickly,because the next activity will not be resumeduntil it returns

Android™ Programming Gauthier Picard 31 / 53

Page 43: Gauthier Picard - Accueil

Activity Lifecycle

onStop():I called when the activity is no longer visible tothe user (destruction or another activity isforeground)

I followed either by onRestart() if the activityis coming back to interact with the user, or byonDestroy() if this activity is going away

I free resources

Android™ Programming Gauthier Picard 31 / 53

Page 44: Gauthier Picard - Accueil

Activity Lifecycle

onDestroy():I called before the activity is destroyedI this is the �nal call that the activity will receiveI it could be called either because the activity is�nishing (someone called finish() on it), orbecause the system is temporarily destroyingthis instance of the activity to save space

I onCreate() should be called again to launchthe activity

I if necessary free temporary �les

Android™ Programming Gauthier Picard 31 / 53

Page 45: Gauthier Picard - Accueil

AgendaAndroid Overview

Basics

Android Projects

Activities

XML Layout

Manifest

Some Android-speci�c Classes

References

Android™ Programming Gauthier Picard 32 / 53

Page 46: Gauthier Picard - Accueil

Simple XML Example (reminder)

Example (A sample XML declaration for a library stock)1 <?xml version="1.0" encoding="ISO-8859-1"?> <!-- header of the XML file (i.e. prologue) -->2 <BIBLIOTHEQUE> <!-- start tag for BIBLIOTHEQUE -->34 <MAGAZINE> <!-- declaration of a MAGAZINE -->5 <TITRE>Science et Vie</TITRE>6 <DATEPARUTION>01-02-2012</DATEPARUTION>7 <PRIX devise="Euro">4.20</PRIX> <!-- "PRIX" is a tag, "devise" is an attribute, "32.30" is a value -->8 </MAGAZINE>9

10 <LIVRE type="education" > <!-- declaration of a LIVRE of type "education" -->11 <TITRE>L'art du développement Android</TITRE>12 <AUTEUR>Mark Murphy</AUTEUR>13 <PRIX devise="Euro">32.30 </PRIX>14 </LIVRE>1516 <LIVRE type="roman"> <!-- declaration of a LIVRE of type "roman" -->17 <TITRE>Le livre d'Android</TITRE>18 <AUTEUR>Patrick Beuzit</AUTEUR>19 <PRIX devise="Dollar">22.25</PRIX>20 </LIVRE>2122 </BIBLIOTHEQUE> <!-- end tag for BIBLIOTHEQUE -->

Android™ Programming Gauthier Picard 33 / 53

Page 47: Gauthier Picard - Accueil

XML Layout ExampleExample (Sample XML Layout)

1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"2 android:id="@id/actionbar_compat"3 android:layout_width="fill_parent"4 android:layout_height="fill_parent"5 android:orientation="vertical" >67 <TextView8 android:id="@+id/textView1"9 android:layout_width="wrap_content"

10 android:layout_height="wrap_content"11 android:text="Hello, I am a TextView" />1213 <Button14 android:id="@+id/button1"15 android:layout_width="wrap_content"16 android:layout_height="wrap_content"17 android:text="Hello, I am a Button" />1819 <ImageView20 android:id="@+id/imageView1"21 android:layout_width="168dp"22 android:layout_height="0dip"23 android:layout_weight="0.36"24 android:src="@drawable/ic_menu_share" />2526 </LinearLayout>

LinearLayout (lines 1 to 5)

1 <LinearLayout ... / >: speci�es the view group (here widgets will be inline)2 android:id="...": declaration of the name (id) of the resource3 android:layout_width="...": the width set to �ll the parent (the screen)4 android:layout_height="...": the height set to �ll the parent (the screen)5 android:orientation="...": the contained views are be vertically lined up

Android™ Programming Gauthier Picard 34 / 53

Page 48: Gauthier Picard - Accueil

XML Layout ExampleExample (Sample XML Layout)

1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"2 android:id="@id/actionbar_compat"3 android:layout_width="fill_parent"4 android:layout_height="fill_parent"5 android:orientation="vertical" >67 <TextView8 android:id="@+id/textView1"9 android:layout_width="wrap_content"

10 android:layout_height="wrap_content"11 android:text="Hello, I am a TextView" />1213 <Button14 android:id="@+id/button1"15 android:layout_width="wrap_content"16 android:layout_height="wrap_content"17 android:text="Hello, I am a Button" />1819 <ImageView20 android:id="@+id/imageView1"21 android:layout_width="168dp"22 android:layout_height="0dip"23 android:layout_weight="0.36"24 android:src="@drawable/ic_menu_share" />2526 </LinearLayout>

TextView (lines 7 to 11)

7 <TextView ... / >: the view is a label (text)8 android:id="@+id/text": the id associated to this view is textView19 android:layout_width="wrap_content": the width is adapted to the contained text

10 android:layout_height="wrap_content": the height is adapted to the contained text11 android:text="Hello, I am a TextView": the displayed text

Android™ Programming Gauthier Picard 34 / 53

Page 49: Gauthier Picard - Accueil

XML Layout ExampleExample (Sample XML Layout)

1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"2 android:id="@id/actionbar_compat"3 android:layout_width="fill_parent"4 android:layout_height="fill_parent"5 android:orientation="vertical" >67 <TextView8 android:id="@+id/textView1"9 android:layout_width="wrap_content"

10 android:layout_height="wrap_content"11 android:text="Hello, I am a TextView" />1213 <Button14 android:id="@+id/button1"15 android:layout_width="wrap_content"16 android:layout_height="wrap_content"17 android:text="Hello, I am a Button" />1819 <ImageView20 android:id="@+id/imageView1"21 android:layout_width="168dp"22 android:layout_height="0dip"23 android:layout_weight="0.36"24 android:src="@drawable/ic_menu_share" />2526 </LinearLayout>

Button (lines 13 to 17)

13 <Button .../ >: the view is a button14 android:id="@+id/button1": the id of the button is button1 (cf. Java code)

In Java, we can create an instance of class Button to manipulate this view:Button myButton = (Button) findViewById(R.id.button);

Android™ Programming Gauthier Picard 34 / 53

Page 50: Gauthier Picard - Accueil

XML Layout ExampleExample (Sample XML Layout)

1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"2 android:id="@id/actionbar_compat"3 android:layout_width="fill_parent"4 android:layout_height="fill_parent"5 android:orientation="vertical" >67 <TextView8 android:id="@+id/textView1"9 android:layout_width="wrap_content"

10 android:layout_height="wrap_content"11 android:text="Hello, I am a TextView" />1213 <Button14 android:id="@+id/button1"15 android:layout_width="wrap_content"16 android:layout_height="wrap_content"17 android:text="Hello, I am a Button" />1819 <ImageView20 android:id="@+id/imageView1"21 android:layout_width="168dp"22 android:layout_height="0dip"23 android:layout_weight="0.36"24 android:src="@drawable/ic_menu_share" />2526 </LinearLayout>

ImageView (lines 19 to 24)

19 <ImageView ... / >: the view is an image20 android:id="@+id/imageView1": the id of the image view is imageView121 android:layout_width="161dp": the width of the image is 168dot point22 android:layout_height="wrap_content": the height is adapted to the content23 android:layout_weight="0.36": see the property android:layout_weight24 android:src="@android:drawable/ic_menu_share": URI of the image

Android™ Programming Gauthier Picard 34 / 53

Page 51: Gauthier Picard - Accueil

Integrate Layouts in Your App

StepsI In your XML editor (e.g. Android Studio):

1. Create an XML layout (pay particular attention to the views’ ids)I Dans le programme Java:

2. Load the layout3. Instantiate the views upon which your want to act

Android™ Programming Gauthier Picard 35 / 53

Page 52: Gauthier Picard - Accueil

(1) Create an XML layoutManual EditionI Documentation available on

http://developer.android.com/guide/topics/ui/declaring-layout.htmlI Create a new .xml �le in the directory res/layoutI Edit the layout with an XML editor

Android™ Programming Gauthier Picard 36 / 53

Page 53: Gauthier Picard - Accueil

(1) Create an XML layout (cont.)

(1.a) Choosing a LayoutI LinearLayout: arranges its children in a single column or a single rowI AbsoluteLayout : lets you specify exact locations (x/y coordinates) of its childrenI RelativeLayout : the positions of the children can be described in relation to eachother or to the parent

I TableLayout : arranges its children into rows and columns

(1.b) Choosing and Positionning the Views

Android™ Programming Gauthier Picard 37 / 53

Page 54: Gauthier Picard - Accueil

(1) Create an XML layout (cont.)

I EditText : an editable text �eldI Toast :a view containing a quickpopup message for the user

I ImageView : an arbitrary image,such as an icon

I CheckBox : a speci�c type oftwo-states button that can beeither checked or unchecked

I Button : a push-button widget thatcan be pressed, or clicked, by theuser to perform an action

I RadioButton : a two-states buttonthat can be either checked orunchecked

I ImageButton: a button with animage (instead of text) that can bepressed or clicked by the user

I DatePicker : a widget for selectinga date

I SlidingDrawer : hides content outof the screen and allows the userto drag a handle to bring thecontent on screen

Android™ Programming Gauthier Picard 38 / 53

Page 55: Gauthier Picard - Accueil

(1) Create an XML layout (cont.)Creation with Android Studio

Android™ Programming Gauthier Picard 39 / 53

Page 56: Gauthier Picard - Accueil

(1) Create an XML layout (cont.)Creation with Android Studio

Android™ Programming Gauthier Picard 39 / 53

Page 57: Gauthier Picard - Accueil

(1) Create an XML layout (cont.)Creation with Android Studio

Android™ Programming Gauthier Picard 39 / 53

Page 58: Gauthier Picard - Accueil

(2) Load the Layout

Linking Java Code and LayoutsI When the app is compiled, each XML layout is compiled as a View resourceI The application code must load the layout in the onCreate() method of the activitycalling the setContentView() method

I The setContentView() method takes as input the rerefence of the layout (its id) ,e.g. R.layout.layout1

Example (A minimal onCreate() method loading a layout)public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);setContentView(R.layout.main_layout);

}

Android™ Programming Gauthier Picard 40 / 53

Page 59: Gauthier Picard - Accueil

(3) Instantiate the ViewsManipulating views by idI Create an instance of each object on which you want to add a handler in the

onCreate() method of your activityI Use the findViewById() to get the instance for your view (using the id de�ned inthe XML layout)

I Manipulate your view (e.g. add an event listener for a button, get the content of aneditable text �eld)

Example (A sample onCreate() method adding an event listener to aButton)public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);setContentView(R.layout.layout1);Button button1 = findViewById(R.id.button1)

.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {

// perform an action on click}

});}

Android™ Programming Gauthier Picard 41 / 53

Page 60: Gauthier Picard - Accueil

AgendaAndroid Overview

Basics

Android Projects

Activities

XML Layout

Manifest

Some Android-speci�c Classes

References

Android™ Programming Gauthier Picard 42 / 53

Page 61: Gauthier Picard - Accueil

What is the manifest �le?

De�nition (Manifest File)Every application must have an AndroidManifest.xml �le (with precisely thatname) in its root directory. The manifest presents essential information aboutthe application to the Android system, information the system must have beforeit can run any of the application’s code.

I XML �leI Specify the architecture of the appI AndroidManifest.xml is at the root of the project

Android™ Programming Gauthier Picard 43 / 53

Page 62: Gauthier Picard - Accueil

ContentsIn a glance...I It names the Java package for the app (the package name ≡ unique identi�er forthe app!)

I It describes the components of the appI It lists the activities, services, and content providers that the app is composed ofI It names the classes that implement each of the components and publishes their

capabilities (e.g. which Intent messages they can handle)⇒ These let the Android system know what the components are and under what

conditions they can be launchedI It determines which processes will host app componentsI It declares which permissions the app must have in order to access protected partsof the API (GPS, internet, etc.) and interact with other apps

I It declares the minimum level of the Android API that the app requiresI It lists the libraries that the app must be linked againstI It lists the Instrumentation classes that provide pro�ling and other information asthe app is running (for development issues)

Android™ Programming Gauthier Picard 44 / 53

Page 63: Gauthier Picard - Accueil

AndroidManifest.xml

ConventionsI Only two elements are required:

I <manifest>: contains the package, the version... this root englobes the whole manifestI <application>: describes the app and contains the list of its components

I All values are set through attributes, not as character data within an elementI All attribute names begin with an android: pre�x (except for some attributes of theroot <manifest> element)

ResourcesI Instead of containing data per se, the manifest refers to resources using thefollowing format: @[package:]type:namee.g. <activity android:icon="@drawable/smallPic"...>

I Resources are stored in the res directory of the app

Android™ Programming Gauthier Picard 45 / 53

Page 64: Gauthier Picard - Accueil

AndroidManifest.xml (cont.)

PermissionsI If an application needs access to a feature protected by a permission, it mustdeclare that it requires that permission

I Speci�y permission with a <uses-permission> element in the manifestI There exist several standard permissions:

I android.permission.CALL_EMERGENCY_NUMBERSI android.permission.READ_OWNER_DATAI android.permission.SET_WALLPAPERI android.permission.DEVICE_POWER

I It is also possible to de�ne your own permissions

Android™ Programming Gauthier Picard 46 / 53

Page 65: Gauthier Picard - Accueil

AndroidManifest.xml (cont.)

Example (A sample manifest �le declaring permissions)1 <manifest ... >2 <permission android:name="com.example.project.DEBIT_ACCT" ... />3 <uses-permission android:name="com.example.project.DEBIT_ACCT" />4 ...5 <application ...>6 <activity android:name="com.example.project.FreneticActivity"7 android:permission="com.example.project.DEBIT_ACCT"8 ... >9 ...

10 </activity>11 </application>12 </manifest>

Android™ Programming Gauthier Picard 47 / 53

Page 66: Gauthier Picard - Accueil

AndroidManifest.xml (cont.)

Intent FilterI Components advertise their capabilities â the kinds of intents they can respond toâ through intent �lters

I A component may have any number of �lters, each one describing a di�erentcapability (e.g. a �lter to edit an existing document, a �lter to initialize a newdocument, etc.)

I A �lter must point to an action

Android™ Programming Gauthier Picard 48 / 53

Page 67: Gauthier Picard - Accueil

AndroidManifest.xml(cont.)

Example (A sample manifest �le)1 <?xml version="1.0" encoding="utf-8"?>2 <manifest xmlns:android="http://schemas.android.com/apk/res/android"3 package="com.eyrolles.android.multimedia"4 android:versionCode="1"5 android:versionName="1.0">6 <application android:icon="@drawable/icon" android:label="@string/app_name">7 <activity android:name=".CapturePhoto"8 android:label="@string/app_name">9 <intent-filter>

10 <action android:name="android.intent.action.MAIN" />11 <category android:name="android.intent.category.LAUNCHER" />12 </intent-filter>13 </activity>14 </application>15 <uses-sdk android:minSdkVersion="3" />16 <uses-permission android:name="android.permission.CAMERA"/>17 </manifest>

Android™ Programming Gauthier Picard 49 / 53

Page 68: Gauthier Picard - Accueil

AgendaAndroid Overview

Basics

Android Projects

Activities

XML Layout

Manifest

Some Android-speci�c Classes

References

Android™ Programming Gauthier Picard 50 / 53

Page 69: Gauthier Picard - Accueil

Deep into the Android-speci�c classes

Let’s look at the online documentation...I android.widget.ToastI android.app.AlarmManagerI android.media.AudioManagerI android.os.AsyncTaskI android.hardware.CameraI android.hardware.Sensor

Android™ Programming Gauthier Picard 51 / 53

Page 70: Gauthier Picard - Accueil

AgendaAndroid Overview

Basics

Android Projects

Activities

XML Layout

Manifest

Some Android-speci�c Classes

References

Android™ Programming Gauthier Picard 52 / 53

Page 71: Gauthier Picard - Accueil

ReferencesBooks

www.it-ebooks.info

Other documents (lectures...)I Romain Raveaux, Cours Android — Développement et API, Laboratoire L3I, IUT de La RochelleI Nazim Benbourahla, several resources at developpez.comI Philippe Lacomme, Raksmey Phan, Créer des applications Android

Android™ Programming Gauthier Picard 53 / 53