La présentation est en train de télécharger. S'il vous plaît, attendez

La présentation est en train de télécharger. S'il vous plaît, attendez

Android View, onClick, Activity, Modèle Vue Contrôleur

Présentations similaires


Présentation au sujet: "Android View, onClick, Activity, Modèle Vue Contrôleur"— Transcription de la présentation:

1 Android View, onClick, Activity, Modèle Vue Contrôleur
jean-michel Douin, douin au cnam point fr version : 26 Septembre 2012 Notes de cours

2 Bibliographie utilisée
Android : Développer des applications mobiles pour les Google Phones, de Florent Garin, chez Dunod Le cours de Victor Matos Android A Programmers Guide - McGraw Hill Professional Android Application Development – Wrox

3 Avertissement, pré-requis et sommaire
Pré requis indispensable Avoir réalisé le tp mvc, Un tp utilisant une calculette à pile Au sommaire Comment assurer un couplage faible des classes Observable/Observateur IHM/Vue et Listener/Contrôleur

4 Pré requis, rappel Pré requis TP Calculette à pile déjà réalisé J2SE
Thème : Modèle Vue Contrôleur Usage de l’applette à cette URL est conseillée >appletviewer

5 Pré requis, MVC

6 Pré requis, l’architecture retenue pour le TP
Le Modèle est une pile (classe PileModele<T>). La Vue correspond à l'affichage de l'état de la pile (classe Vue). Le Contrôleur gère les évènements issus des boutons +, -, *, /,[] (classe Controleur). L'applette crée, assemble le modèle, la vue et le contrôle (classe AppletteCalculette). Le Modèle est une pile (classe PileModele<T>). Le Modèle lors d'un changement d'état prévient ses observateurs La Vue correspond à l'affichage de l'état de la pile (classe Vue). La vue s'inscrit auprès du Modèle lors de l'appel du constructeur d'une Vue, à chaque notification, la vue s'enquiert de l'état du modèle et l'affiche Le Contrôleur gère les évènements issus des boutons +, -, *, /,[] (classe Controleur). Le contrôleur gère localement les écouteur(Listener) des boutons de l'IHM, notons que la gestion des boutons utilise une architecture MVC L'applette crée, assemble le modèle, la vue et le contrôle (classe AppletteCalculette).

7 Cette architecture engendre des discussions
Le Modèle est ici une pile (classe PileModele<T>). La Vue correspond à l'affichage de l'état de la pile (classe Vue). Le Contrôleur gère les évènements issus des boutons +, -, *, /,[] L'applette crée, assemble le modèle, la vue et le contrôle (classe AppletteCalculette).

8 Discussions … entre nous
Le modèle pourrait être la calculette constituée pour ses calculs internes d'une pile, Pourquoi les "listeners" des boutons sont-ils locaux au contrôleur ? Pourquoi un JPanel pour le contrôleur ? Ce choix de découpage MVC vous parait-il réaliste ? Discussion, blabla, blabla, blabla

9 Architecture classique … une valeur sûre
L’utilisateur clique L’utilisateur visualise Ici le Modèle hérite de java.util.Observable La Vue implemente java.util.Observer

10 MVC encore Model extends Observable View implements Observer
Controller implements XXXXListener, YYYYListener

11 Nouvelle architecture
En conséquence Au tp Le Modèle est une pile (classe PileModele<T>). La Vue correspond à l'affichage de l'état de la pile (classe Vue). Le Contrôleur gère les évènements issus des boutons +, -, *, /,[]. Architecture retenue Le Modèle est une calculette La Vue correspond à l’IHM (au complet). Le Contrôleur gère les évènements issus des boutons +, -, *, /,[]

12 Architecture retenue Le Modèle La Vue Le Contrôleur
La calculette munie de ses opérations (+,-,/,*,…) Hérite de la classe java.util.Observable Les sources du modèle sont ici La Vue L’IHM affichage, zone de saisie, boutons … Implémente java.util.Observer Le Contrôleur Réalisation, implémentation des listeners, (le comportement de l’IHM) Implémente plusieurs ActionListener -> pour Android, quel découpage ?, quelles classes ?

13 Android, la classe Activity
Activité comme application élémentaire À cette activité lui correspond une IHM, ce que l’on voit … public class Calculette extends Activity { Cette IHM est décrite par un fichier XML (la vue) L’activité réagit aux sollicitations de l’utilisateur (le contrôleur)

14 L’IHM de la calculette Un fichier XML décrit complètement cette interface L’activité Calculette affiche, présente cette interface

15 Android, la calculette L’activité affiche l’IHM
Le modèle ne change pas Cf. le TP Android : Démonstration …

16 IHM : Layout, View , Button…
LinearLayout TextView EditText TableRow Button ProgressBar Description de cette interface en XML Fichier res/layout/main.xml

17 Interface, IHM : Approche déclarative ./res/
Chaque composant possède un id (android:id=

18 Chaque composant a son id
etatPile donnee TableRow clear div plus jauge sub mul push <Button

19 IHM, un outil de conception sous eclipse
Item comme classe Nom de la balise comme Nom de la classe Properties de chaque item Attribut XML, cf. Properties Mais aussi comme Attribut de la classe,

20 Adéquation XML <-> java, le fichier R
En XML <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:enabled="true" android:visibility="visible" android:clickable="false" android:layout_margin="5dip"   android:numeric= "decimal" android:inputType= "number" android:text="1" /> <Button En Java EditText donnee = (EditText) findViewById(R.id.donnee); Button empiler = (Button) findViewById (R.id.push);

21 Intégration de l’IHM, R.layout.main
Au sein d’une Activity XML : accès en java via R Les ressources XML sont accessibles via le fichier R R.java est généré par Android Convention : /layout/main -> R.layout.main, R.id. R.string. … R cf. dossier /gen/

22 Intégration de l’IHM, R.layout.main
Au sein d’une Activity Au préalable l’affectation de l’interface par l’appel de setContentView(R.layout.main); Les composants de l’IHM deviennent accessibles Button empiler = (Button) findViewById(R.id.push); findViewById est une méthode héritée de la classe Activity Le source java ne manquera pas de R, ni d’appels de R (facile …)

23 Une Activity, « démarrage » par onCreate
public class TPCalculette extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Affectation de l’IHM issue des fichiers XML setContentView(R.layout.main);

24 Une Activity accès aux composants
public class TPCalculette extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // accès aux composants de l’IHM Button empiler = (Button) findViewById(R.id.push); ProgressBar jauge = (ProgressBar) findViewById(R.id.jauge); // accès aux chaînes de caractères ( plusieurs langues) String str = getString(R.string.app_name);

25 Comportement : OnClickListener et plus
Un seul « Listener » par composant Button empiler = (Button) findViewById(R.id.push); empiler.setOnClickListener(new View.OnClickListener(){ public void onClick(View v){ // traitement associé }

26 Ou bien usage de l’Attribut onClick
Extrait de layout/main.xml <Button android:layout_height="wrap_content" android:layout_width="wrap_content" android:onClick="onClickEmpiler"> </Button> Dans la classe de l’activity public void onClickEmpiler(View v){ // traitement associé }

27 Démonstration Une démonstration Avec au moins un bouton … de bienvenue
À chaque clic la chaîne hello world est modifiée

28 Android : la description de l’application
Quelles activités ? Plusieurs activités pour une application Quelles permissions ? SMS, Réseau, GPS, … Quelles librairies ? Dans un fichier XML AndroidManifest.xml

29 AndroidManifest.xml, tp4Calculette
La description de l’application, destinée à l’hébergeur

30 MVC et Android Nous avons : Alors MVC ? Une IHM décrite en XML
Une activité qui implémente le comportement Alors L’activité est le contrôleur de la vue, de l’IHM décrite en XML L’activité met l’IHM au premier plan, l’activité a accès aux composants graphiques MVC ? Le modèle est une calculette La vue du modèle est l’activité

31 MVC, Mise en Pratique : discussions
Calculette Modèle extends java.util.Observable implements CalculetteI update(.. enter, add, sub, … Activity Contrôleur Listeners « XML » IHM extends Activity implements java.util.Observer L’activity Android est une vue du Modèle Calculette (implements Observer) L’activity Android est le contrôleur de l’IHM décrite en XML (extends Activity)

32 packages mode modèle

33 Le Modèle : la Calculette
public interface CalculetteI { // operations void enter(int i) throws CalculetteException; void add() throws CalculetteException; void sub() throws CalculetteException; void div() throws CalculetteException; void mul() throws CalculetteException; void clear(); int pop() throws CalculetteException; // interrogations int result() throws CalculetteException; boolean isEmpty(); boolean isFull(); int size(); int capacity(); } public class Calculette extends java.util.Observable implements CalculetteI

34 TP4CalculetteActivity, la vue du modèle + le Contrôleur de l’IHM
public class Tp4CalculetteActivity extends Activity implements Observer{ private Calculette calculette; public void onCreate(Bundle savedInstanceState) { // appelée par Android super.onCreate(savedInstanceState); this.calculette = new Calculette(); // une calculette est créée this.calculette.addObserver(this); // c’est une vue du modèle calculette setContentView(R.layout.main); // l’IHM est associée à cette activité …. } public void onClickEmpiler(View v){ // attribut onClick balise <Button public void update(Observable arg0, Object arg1) { // à chaque notification

35 TP4CalculetteActivity, le Contrôleur de l’IHM
public class Tp4CalculetteActivity extends Activity implements Observer{ private Calculette calculette; public void onCreate(Bundle savedInstanceState) { // appelée par Android …. } public void onClickEmpiler(View v){ // attribut onClick balise <Button try{ int operande = … this.calculette.empiler(operande); // opération empiler sur le modèle }catch(CalculetteException nfe){} public void onClickAdd(View v){ public void update(Observable arg0, Object arg1) { // à chaque notification

36 TP4CalculetteActivity, est une vue du modèle
public class Tp4CalculetteActivity extends Activity implements Observer{ private Calculette calculette; public void onCreate(Bundle savedInstanceState) { // appelée par Android …. } public void onClickEmpiler(View v){ // attribut onClick public void update(Observable arg0, Object arg1) { // à chaque notification du TextView etat = (TextView) findViewById(R.id.etatPile); // modèle etat.setText(calculette.toString()); ProgressBar jauge = (ProgressBar) findViewById(R.id.jauge); jauge.setProgress(calculette.size()); actualiserInterface();

37 Application Calculette en résumé
Architecture retenue Application Calculette en résumé Observable : Le modèle, la calculette Observer : l’Activity, mise à jour de l’interface View : le fichier XML (l’IHM) Controller : l’Activity

38 Android, la calculette Discussion, réalisation …

39 Android et MVC, discussion
Calculette Modèle extends java.util.Observable implements CalculetteI update(.. enter, add, sub, … Activity Contrôleur Listeners « XML » IHM extends Activity implements java.util.Observer public class CalculetteActivity extends Activity implements Observer{

40 Comportements attendus, cycle de vie
3 + 2 == 5 ? Appui sur la touche « retour » Fin de l’activité Appui sur la touche « HOME » L’activité est en Pause … Pendant que je calcule 3 + 2, je reçois un urgent appel téléphonique telnet localhost 5554 gsm call 5554 Une rotation de l’écran a lieu Ctrl-F11, Ctrl-F12

41 Cycle de vie d’une activity, je calcule
….

42 Cycle de vie d’une activity, j’ai fini
….

43 Cycle de vie d’une activity, je lance une autre activity
….

44 Cycle de vie d’une activity, je calcule de nouveau
….

45 Cycle de vie d’une activity, un appel urgent
telnet localhost 5554 gsm call 5554 ….

46 Cycle de vie d’une activity, je réponds
….

47 Cycle de vie d’une activity, je raccroche
….

48 Illustration du cycle de vie
Démonstration Touche « Retour » onPause, onDestroy ….ok Touche Menu onSaveInstanceState, onPause, onStop ...ok Sauvegarde par défaut … Un appel idem Rotation de l’écran Ctrl-F11, Ctrl-F12 … !!! Android détruit votre vue en cas de rotation pour construire la nouvelle vue Android détruit votre vue en cas de changement d’orientation pour construire la nouvelle vue

49 Cycle de vie d’une activity, onSaveInstanceState
….

50 Cycle de vie d’une activity, onRestoreInstanceState
….

51 Mise en Pratique, suite Suite du TP :
Sauvegarde de l’état de la calculette Cf. cycle de vie protected void onSaveInstanceState(Bundle out){ out.putInt("taille",calculette.size()); protected void onRestoreInstanceState(Bundle in){ int taille = in.getInt("taille"); Sauvegarde et restitution via le bundle

52 Cycle de vie d’une activity …
In order to understand the Android application architecture you need some basic knowledge regarding Android applications key concepts. Understanding these elements will allow you to control: application components application lifecycle application resources In this post are described all these key concepts  in order to highlight their role, utility and importance. Other posts will describe in more detail how are used in order to develop an Android mobile application. The main characteristics of an Android application (more detailed information on developer.android.com) are: it is a Java application executed by a Dalvik Virtual Machine; the Dalvik VM runs .dex files, obtained from Java .class files; it is distributed in an Android Package, which is a .apk file; it is executed by the Android Operating System (a multi-user Linux) in a sandbox; each application has a unique user ID and its resources can be accessed only by that user; each application runs in its own Linux process and its own Virtual Machine instance; despite this, two different applications can be assigned same user ID in order to share their resources; critical operations (access to Internet, read or write contacts, monitor SMS, access GPS module) can be restricted or can require user permission, using the application manifest file, AndroidManifest.xml; more detailed info on the Android application security are available at an Android application is represented by one or more activities (an activity can be associated with a user screen or window, but is more than that) and Linux process; an activity lifecycle is not related to the application process lifecycle; the activity can run even if its process doesn’t exists any more (this is different than C,C++ or classic Java applications where an application has a process); an application can start a component (activity) from another application; the component is executed by its parent application process; an Android application does NOT have a single entry point, like the main() method in Java, C or C++ applications; Other topics that are part of this Android tutorial are accessible through Android Tutorial – Overview and contents. Components of Android applications The most important components of the Android application are: Activity represents a user interface screen, window or form; an Android application can have one or more activities; an agenda application can have an activity to manage contacts, an activity to manage meetings and one to edit an agenda entry; each Activity has its own lifecycle independent from the application process lifecycle; each Activity has its own state and it is possible to save it and restore it; activities can be started by different applications (if it is allowed); has a complex lifecycle because applications can have multiple activities and only one is in the foreground; using the Activity Manager, the Android System manages a stack of activities which are in different states (starting, running, paused, stopped, destroyed); in the Android SDK is implemented using a subclass of Activity class which extends the Context class; Intent represents an entity used to describe an operation to be executed; is a message transmitted to another component in order to announce an operation; somehow similar to the event-handler concept from .NET or Java; an asynchronous message used to activate activities, services and broadcast receivers; implemented by the Intent class; Service a task that runs in the background without the user direct interaction; implemented by a subclass of Service; Content provider a custom API used to manage application private data; an data management alternative to the file system, the SQLite database or any other persistent storage location; implemented as a subclass of ContentProvider; a solution to share and control (with permissions) data transfer between applications (i.e. Android system provides a content provider for the user’s contact information); Broadcast receiver a component that responds to system-wide broadcast announcements; somehow similar to the global (or system event) handler concept; implemented as a subclass of BroadcastReceiver Activity LifeCycle The Android application Activity is one of the most important component (with services and broadcast receivers) of Android applications because it is related to the user interface. An activity is used to manage a user screen and is equivalent to the window or form form desktop applications. Understanding and knowing how to control the Activity allows you to: use the Activity lifecycle to create, view, use and stop activities; save user data before the Activity is stopped and restore it when it is brought back to the foreground; create applications with multiple views or activities; The Activity lifecycle describes the state in which an Activity can be at one moment: Running – the Activity has been created (onCreate()) and started (onStart()) and it is displayed on the device screen; if the Activity was used before and the application has saved its state (onSaveInstanceState()), it is resumed from that point (onRestoreInstanceState() and onResume()); in this state the user interacts with the Activity through the device input interface (keyboard, touchscreen, display); Paused – the Activity looses the foreground position (onPause()) because another Activity is executed, like a dialog box or alert; also, if the device enters sleep mode, the Activity is paused; the activity may resume its execution (onResume()) and placed back to the foreground; Stopped – the Activity is not more in use and because it is stopped (onStop()) is not visible; in order to be reactivated (the Activity already exists), the Activity must be restarted (onRestart() and onStart()) and resumed (onResume()); Destroyed – The Activity is destroyed (onDestroy()) and its memory is released because it will not be needed or the systems needs more memory; because memory management is an important issue for the Linux OS of the mobile device, the process that hosts the paused, stopped or destroyed Activity can be killed to release memory for new activities; only processes that hosts running activities are protected; Android Activity Lifecycle Diagram As you can see in the previous image the Activity has multiple states with clear transitions between them. Despite things may look complicated, in reality they are much more simpler if you keep in mind the next facts: only one Activity can be in the foreground; the system manages the states and the transitions, NOT the programmer (not directly, because when you start a new Activity you implicitly change the state of the current one) IMPORTANT the system notifies you when the Activity is going to change its state providing handlers (the onXXX() methods) for the transitions events; as a programmer, you can add your own code by overriding these methods: onCreate(Bundle) – called when the Activity is created; using the method argument you can restore the Activity state that has been saved from a previous session; once the Activity has been created is going to be started (onStart()); onStart() – called when the Activity is going to be displayed; from this point the Activity can come to the foreground (onResume()) or stay hidden (onStop()); onRestoreInstanceState(Bundle) – called when the Activity is initialized with data from a previous saved state; by default, the system restores the state of the user interface; onResume() – called when the Activity is visible and the user can interact with it; from this state, the Activity can go in the background becoming paused (onPause()); onRestart() – called when the Activity is going back to the foreground from a stopped state; after that, the Activity is started (onStart()) once again; onPause() – called when the system is bringing into the foreground another Activity; the current Activity is set into the background and later it may be stopped (onStop()) or resumed and displayed (onResume()); this is a good moment to save application data to a persistent storage (files, database) onSaveInstanceState(Bundle) – called to save the Activity state; by default, the system saves the state of the user interface; onStop() – called when the Activity is not longer used and not visible as another Activity is interacting with the user; from this point, the Activity can be restarted (onRestart()) or destroyed (onDestroy()); onDestroy() – called when the Activity is deleted and its memory released; this can happen if the system requires more memory or if the programmer terminates it by calling the Activity finish() method; Because the state transitions are regulated by different calls to onXXX() methods, the Activity lifecycle can be described by their possible calling sequence: Events Handlers for Android Application Activity In order to override the methods you must pay attention to their name and signature. It’s safer to use annotation and request a validation from the compiler (if the defined method does not override a method from the base class then you will get a compiler error). For onCreate() or onPause() the solution is: public class SomeActivity extends Activity { // The activity is being public void onCreate(Bundle savedInstanceState) { // DO NOT forget to call the base method super.onCreate(savedInstanceState); }   // Another activity is put in the protected void onPause() { // DO NOT forget to call the base method super.onPause(); } } Important ! When you override one of the onXXX() methods, you must call (must be the first statement in the method) the base class (Activity) method because the scope of this approach is to add your own code to the Activity events and NOT to reinvent them. As you can see in the previous two figures, the Activity can have states, like Stopped and Destroyed, in which the device OS can kill the process that hosts the Activity. The OS will release the Activity memory without calling the onStop() and onDestroy() methods. In conclusion, the onPause() event is the recommended moment for saving Activity state before it will be destroyed. Android Application Resources Applications use text strings, bitmaps, video and audio files to enhance the user experience. All these represent resources. Despite they are controlled from the source code they are external resources and the recommendation is to externalize (not storing them in the application code) them in order to support: internalization by providing different languages and format user interface application portability on different devices Resources are stored in the res directory inside the Android project. In order to manage different types of resources, the project res directory contains specific subfolders: DirectoryResourceres/animator/XML files that define property animations.res/anim/XML files for tween animations.res/color/XML files that define colors and color state list resource.res/drawable/Bitmap files (.png, .jpg, .gif) or XML files that define drawable resource subtypes.res/layout/XML files that define a user interface layout.res/menu/XML files that define application menus.res/raw/arbitrary files in their raw format (binary or text files)res/values/XML files that contain simple values, such as strings, integers, and colors. It is recommended to use filename conventions for particular types of resources: arrays.xml (typed arrays), colors.xml (color values), dimens.xml (dimension values), strings.xml (string values), styles.xml (styles).res/xml/XML files that can be read by calling Resources.getXML() All the resources from the res subdirectories are packed by the compiler. In order to facilitate the access and control of resources from the application cod, the compiler generates a class, called R, that contains static identifiers used to reference each resource. Because resource files are compiled, DO NOT save resource files directly inside the res/ folder because it will cause a compiler error. For example, it is recommended to define and store constant String values inside the res/values/strings.xml and NOT to write them directly into the code. Being defined outside the code it means that you can modify them without affecting the Java source code. The strings.xml file may look like this <?xml version="1.0" encoding="utf-8"?> <resources> <string name="hello">Hello World, Activity!</string> <string name="app_name">Android</string> </resources> As said before, for each resource the compiler generates a static unique identifier in the R class. The static indentifier has the same name as the strings.xml element. package itcsolutions.eu;   public final class R { //...   public static final class string { //unique ID for app_name string in strings.xml public static final int app_name=0x7f040001; //unique ID for hello string in strings.xml public static final int hello=0x7f040000; } } So, if I want to get the hello element value and copy it into a String variable, I will use the static reference: String stringHello = this.getString(R.string.hello);

53 Illustration du cycle de vie
Ecran de veille alors que la calculette était au premier plan onPause Noté semi-visible dans la biblio … Android détruit votre vue en cas de changement d’orientation pour construire la nouvelle vue

54 Cycle de vie d’une activity, écran de veille, touche F7
….

55 Cycle de vie d’une activity, au réveil, touche F7
….

56 Un extra pour la calculette
A chaque mauvais format du nombre, un sms est envoyé ! Une exception Over The Air … 1) l’activité Calculette envoie le SMS SmsManager sm = SmsManager.getDefault(); Si j’ai la permission 2) L’activité standard d’envoi de SMS est appelée Intent sendIntent = new Intent(Intent.ACTION_VIEW); startActivity(sendIntent);  

57 Au sein de votre application
private void sendSMS(String msg){ try{ SmsManager sm = SmsManager.getDefault(); String body = getString(R.string.app_name) + " : " + msg + "\n"; sm.sendTextMessage(getString(R.string.numero_tel), null, body, null, null); // ou bien un Toast Toast.makeText(getBaseContext(), " envoi d’un sms " + msg, Toast.LENGTH_LONG).show(); }catch(Exception e){ Toast.makeText(getBaseContext(), getString(R.string.erreur), Toast.LENGTH_LONG).show(); } Mais avez-vous la permission ?, -> AndroidManifest

58 Une Activity en démarre une autre
Intent ou comment transmettre des paramètres à une activité Intent sendIntent = new Intent(Intent.ACTION_VIEW); sendIntent.putExtra("sms_body", "The SMS text");  sendIntent.setType("vnd.android-dir/mms-sms"); startActivity(sendIntent);   Une pile d’activité en interne Cycle de vie

59 Cycle de vie d’une activity, startActivity(sendIntent);
….

60 Cycle de vie d’une activity, sms envoyé +
….

61 Quelques remarques Attention à la persistance
Lorsque l’activité est en Pause ou Stoppée Android peut décider de supprimer l’activité

62 Cycle de vie d’une activity, android killer
….

63 Cycle de vie d’une activity, android killer

64 L’architecture se précise
Une Activity peut en déclencher une autre A chaque activity son écran (son fichier XML) Nécessaire gestion de ces activités, android utilise une pile

65 Extension possible : à chaque exception un sms !
Trop de sms …. Un mauvais format de Nombre  Contrôle de la saisie android:numeric="decimal" android:inputType="number"

66 La pile des Activity

67 Annexe : un tutorial

68

69 http://www. itcsolutions

70

71 Vocable

72 Vocable


Télécharger ppt "Android View, onClick, Activity, Modèle Vue Contrôleur"

Présentations similaires


Annonces Google