Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Architecture et Bonnes pratiques Android #DevoxxFr2016 Part2

1,435 views

Published on

Depuis maintenant 7 ans que je développe sous Android, ma principale préoccupation a toujours été l'architecture.

Et si nous prenions quelques heures pour en discuter ?
Je vous propose une vision globale et synthétique s'appuyant sur des exemples concrets, sur les principes et conseils de référence des équipes Google et sur des modèles d'architecture (MVP/n-tiers) et leur mises en place.
Au programme:
Le contexte Android,
L'objectif utilisateur,
La responsabilité du développeur,
Les bonnes pratiques (celles de Chet Haase, Romain Guy et les miennes),
Les principes d'architecture (n-tiers, MVP et MVVM),
Leur application sur Android (services, threads, Application ...),
Le déploiement continue,
Les librairies incontournables du moment,
Un exemple concret d'utilisation d'un service REST (up et download)
et bien sûr un projet github est associé à cette conférence pour que le code soit avec vous !

Published in: Mobile
  • DOWNLOAD THE BOOK INTO AVAILABLE FORMAT (New Update) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { https://urlzs.com/UABbn } ......................................................................................................................... Download Full EPUB Ebook here { https://urlzs.com/UABbn } ......................................................................................................................... Download Full doc Ebook here { https://urlzs.com/UABbn } ......................................................................................................................... Download PDF EBOOK here { https://urlzs.com/UABbn } ......................................................................................................................... Download EPUB Ebook here { https://urlzs.com/UABbn } ......................................................................................................................... Download doc Ebook here { https://urlzs.com/UABbn } ......................................................................................................................... ......................................................................................................................... ................................................................................................................................... eBook is an electronic version of a traditional print book THE can be read by using a personal computer or by using an eBook reader. (An eBook reader can be a software application for use on a computer such as Microsoft's free Reader application, or a book-sized computer THE is used solely as a reading device such as Nuvomedia's Rocket eBook.) Users can purchase an eBook on diskette or CD, but the most popular method of getting an eBook is to purchase a downloadable file of the eBook (or other reading material) from a Web site (such as Barnes and Noble) to be read from the user's computer or reading device. Generally, an eBook can be downloaded in five minutes or less ......................................................................................................................... .............. Browse by Genre Available eBOOK .............................................................................................................................. Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, CookBOOK, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult, Crime, EBOOK, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, ......................................................................................................................... ......................................................................................................................... .....BEST SELLER FOR EBOOK RECOMMEND............................................................. ......................................................................................................................... Blowout: Corrupted Democracy, Rogue State Russia, and the Richest, Most Destructive Industry on Earth,-- The Ride of a Lifetime: Lessons Learned from 15 Years as CEO of the Walt Disney Company,-- Call Sign Chaos: Learning to Lead,-- StrengthsFinder 2.0,-- Stillness Is the Key,-- She Said: Breaking the Sexual Harassment Story THE Helped Ignite a Movement,-- Atomic Habits: An Easy & Proven Way to Build Good Habits & Break Bad Ones,-- Everything Is Figureoutable,-- What It Takes: Lessons in the Pursuit of Excellence,-- Rich Dad Poor Dad: What the Rich Teach Their Kids About Money THE the Poor and Middle Class Do Not!,-- The Total Money Makeover: Classic Edition: A Proven Plan for Financial Fitness,-- Shut Up and Listen!: Hard Business Truths THE Will Help You Succeed, ......................................................................................................................... .........................................................................................................................
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • This already saved me $120 on a car battery! When my car battery died, I decided to try out the EZ Battery Reconditioning method instead of buying a new (expensive) battery. And in just 25 minutes, I reconditioned the battery and it works fantastic again! This already saved me $120 on a car battery! I can�t wait to try this on other batteries now. ◆◆◆ http://t.cn/AiFAb0DL
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • DOWNLOAD THIS BOOKS INTO AVAILABLE FORMAT (2019 Update) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download Full EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download Full doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... ......................................................................................................................... ................................................................................................................................... eBook is an electronic version of a traditional print book THIS can be read by using a personal computer or by using an eBook reader. (An eBook reader can be a software application for use on a computer such as Microsoft's free Reader application, or a book-sized computer THIS is used solely as a reading device such as Nuvomedia's Rocket eBook.) Users can purchase an eBook on diskette or CD, but the most popular method of getting an eBook is to purchase a downloadable file of the eBook (or other reading material) from a Web site (such as Barnes and Noble) to be read from the user's computer or reading device. Generally, an eBook can be downloaded in five minutes or less ......................................................................................................................... .............. Browse by Genre Available eBooks .............................................................................................................................. Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, ......................................................................................................................... ......................................................................................................................... .....BEST SELLER FOR EBOOK RECOMMEND............................................................. ......................................................................................................................... Blowout: Corrupted Democracy, Rogue State Russia, and the Richest, Most Destructive Industry on Earth,-- The Ride of a Lifetime: Lessons Learned from 15 Years as CEO of the Walt Disney Company,-- Call Sign Chaos: Learning to Lead,-- StrengthsFinder 2.0,-- Stillness Is the Key,-- She Said: Breaking the Sexual Harassment Story THIS Helped Ignite a Movement,-- Atomic Habits: An Easy & Proven Way to Build Good Habits & Break Bad Ones,-- Everything Is Figureoutable,-- What It Takes: Lessons in the Pursuit of Excellence,-- Rich Dad Poor Dad: What the Rich Teach Their Kids About Money THIS the Poor and Middle Class Do Not!,-- The Total Money Makeover: Classic Edition: A Proven Plan for Financial Fitness,-- Shut Up and Listen!: Hard Business Truths THIS Will Help You Succeed, ......................................................................................................................... .........................................................................................................................
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • DOWNLOAD THIS BOOKS INTO AVAILABLE FORMAT (2019 Update) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download Full EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download Full doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... ......................................................................................................................... ................................................................................................................................... eBook is an electronic version of a traditional print book THIS can be read by using a personal computer or by using an eBook reader. (An eBook reader can be a software application for use on a computer such as Microsoft's free Reader application, or a book-sized computer THIS is used solely as a reading device such as Nuvomedia's Rocket eBook.) Users can purchase an eBook on diskette or CD, but the most popular method of getting an eBook is to purchase a downloadable file of the eBook (or other reading material) from a Web site (such as Barnes and Noble) to be read from the user's computer or reading device. Generally, an eBook can be downloaded in five minutes or less ......................................................................................................................... .............. Browse by Genre Available eBooks .............................................................................................................................. Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, ......................................................................................................................... ......................................................................................................................... .....BEST SELLER FOR EBOOK RECOMMEND............................................................. ......................................................................................................................... Blowout: Corrupted Democracy, Rogue State Russia, and the Richest, Most Destructive Industry on Earth,-- The Ride of a Lifetime: Lessons Learned from 15 Years as CEO of the Walt Disney Company,-- Call Sign Chaos: Learning to Lead,-- StrengthsFinder 2.0,-- Stillness Is the Key,-- She Said: Breaking the Sexual Harassment Story THIS Helped Ignite a Movement,-- Atomic Habits: An Easy & Proven Way to Build Good Habits & Break Bad Ones,-- Everything Is Figureoutable,-- What It Takes: Lessons in the Pursuit of Excellence,-- Rich Dad Poor Dad: What the Rich Teach Their Kids About Money THIS the Poor and Middle Class Do Not!,-- The Total Money Makeover: Classic Edition: A Proven Plan for Financial Fitness,-- Shut Up and Listen!: Hard Business Truths THIS Will Help You Succeed, ......................................................................................................................... .........................................................................................................................
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • DOWNLOAD THIS BOOKS INTO AVAILABLE FORMAT (2019 Update) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download Full EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download Full doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... ......................................................................................................................... ................................................................................................................................... eBook is an electronic version of a traditional print book THIS can be read by using a personal computer or by using an eBook reader. (An eBook reader can be a software application for use on a computer such as Microsoft's free Reader application, or a book-sized computer THIS is used solely as a reading device such as Nuvomedia's Rocket eBook.) Users can purchase an eBook on diskette or CD, but the most popular method of getting an eBook is to purchase a downloadable file of the eBook (or other reading material) from a Web site (such as Barnes and Noble) to be read from the user's computer or reading device. Generally, an eBook can be downloaded in five minutes or less ......................................................................................................................... .............. Browse by Genre Available eBooks .............................................................................................................................. Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, ......................................................................................................................... ......................................................................................................................... .....BEST SELLER FOR EBOOK RECOMMEND............................................................. ......................................................................................................................... Blowout: Corrupted Democracy, Rogue State Russia, and the Richest, Most Destructive Industry on Earth,-- The Ride of a Lifetime: Lessons Learned from 15 Years as CEO of the Walt Disney Company,-- Call Sign Chaos: Learning to Lead,-- StrengthsFinder 2.0,-- Stillness Is the Key,-- She Said: Breaking the Sexual Harassment Story THIS Helped Ignite a Movement,-- Atomic Habits: An Easy & Proven Way to Build Good Habits & Break Bad Ones,-- Everything Is Figureoutable,-- What It Takes: Lessons in the Pursuit of Excellence,-- Rich Dad Poor Dad: What the Rich Teach Their Kids About Money THIS the Poor and Middle Class Do Not!,-- The Total Money Makeover: Classic Edition: A Proven Plan for Financial Fitness,-- Shut Up and Listen!: Hard Business Truths THIS Will Help You Succeed, ......................................................................................................................... .........................................................................................................................
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here

Architecture et Bonnes pratiques Android #DevoxxFr2016 Part2

  1. 1. @android2ee by(Mathias Seguy== Android2EE){ French AndroidTrainer}
  2. 2. 2 And so ? 2 Avec un objectif utilisateur fort Dans un contexte de pénurie et un monde complexe De grosses responsabilités Des bonnes pratiques Des habitudes Des Design Patterns Et une p**n d'archi générique Je m'en sors comment, moi?
  3. 3. l'objet Application Les services métiers
  4. 4. 4 Quand mon application est en foreground, je veux toute la puissance dont j'ai besoin ! Objectif
  5. 5. 5 Quand mon application part en background, je veux restituer le plus de ressources possible au système (pour que les autres puissent l'utiliser). Fuck I am going in background Take that services ! Objectif
  6. 6. 6 Et comme je ne veux pas que mes utilisateurs subissent ça Objectif
  7. 7. Et comme je ne veux pas que mes utilisateurs subissent ça 7 Ma philosophie est le LazyLoading Objectif
  8. 8. 8 Tout se joue ArchiDroid ICI
  9. 9. Aparté
  10. 10. 10 L'Objet Application Application
  11. 11. 11 Démarre avant n'importe laquelle de vos classes L'Objet Application Conserve l'état global de l'application Se termine après n'importe laquelle de vos classes Est le Contexte de votre application Application
  12. 12. Application 12 L'Objet Application Vous devez vous l'approprier public class DesignApplication extends Application { } <manifest package= <application ... android:name=".DesignApplication">
  13. 13. Application 13 L'Objet Application Et le retrouver où que vous soyez: Design Pattern du Singleton public class DesignApplication extends Application { private static DesignApplication instance; public static DesignApplication getInstance() { return instance;} public void onCreate() { super.onCreate(); instance = this;…}
  14. 14. Application 14 L'Objet Application Il peut être appelé de n'importe où (de n'importe quel Thread). Toutes ses méthodes publiques doivent être synchronized.
  15. 15. 15 setUser(…) onStop StartActivity LoginActivty MainActivity Application getUser(…) onStart MainActivity Application getUser(…) NullPointerException 1 2 3 4 5 6 7 8 L'Objet Application L'exemple typique : l'utilisateur
  16. 16. 16 Application User user=null; public void getUser() { if(user==null) { //Do what you need to do //1)startActivity(LoginActivtyIntent); //ou 2)retireve it from a SharedPreference||DataBase||File... } return user; } La classe Application est responsable de l'instanciation des champs qu'elle persiste L'Objet Application
  17. 17. 17 Les Services Services AndroidServices SingletonServices
  18. 18. Les Services "Service (la classe Android): Service is how an application indicates to the operating system that it needs to perform a longer-running operation outside of the normal Activity UI flow. It may be self-running (through Context.startService()), or running on behalf of of another process (through Context.bindService()). If you do not need either of these behaviors, you should not use a Service." Service Android == Service Système
  19. 19. Les Services La couche Service (architecture n-tier): Elle correspond à la partie fonctionnelle de l'application, celle qui implémente la « logique », et qui décrit les opérations que l'application opère sur les données. Les différentes règles de gestion et de contrôle du système sont mises en œuvre dans cette couche.
  20. 20. Les Services Les services Android sont-ils des services métiers? Les services métiers sont-ils des services Android ? Don't fuck around with the system !
  21. 21. Les Services Doit être considéré comme une Activity sans IHM... 21 Services AndroidServices SingletonServices Assurer l'unique instance (best to do that using a ServiceManager instead of static) S'exécute dans le Thread UI Est fait pour des tâches longues Quand actif est conservé dans le LRUCache as long as possible.... Plus gros qu'un simple pojo Est légère (simple pojo) Ainsi sont les Services métiers côté serveur On peut/doit aussi maîtriser leur cycle de vie ??
  22. 22. Les Services Services AndroidServices SingletonServices ?? Besoin d'être lancé par le système? Besoin de faire du cache de données?
  23. 23. Les Services Services AndroidServices SingletonServices ?? Besoin de continuer même sans Activité visible (Music Player)? Pas de besoin particulier
  24. 24. Fin de l'aparté
  25. 25. Les instancier à la demande 25 Il faut qu'on arrive avec nos services métiers à: ArchiDroid Ne les instancier QU'une seule fois Mettre en place l'asynchronicité Ne pas suivre le cycle de vie des activités mais le cycle de vie de l'application Les laisser terminer leur traitement
  26. 26. 26 Instanciation à la demande private void launchServiceAsync() { // load your service... ServiceManager.instance.getHumanService(new OnServiceCallBack() { public void onServiceCallBack(MService service) { // so just call the method you want of your service ((HumanService) service).getHuman("toto"); }});} the callBack pattern View Presenter HumanService LazyLoading Services Manager Activity AndroidServices SingletonServices
  27. 27. 27 Threads View Presenter HumanService Manage Threads Services Manager DAO Cancelable KeepAlive ThreadsPools
  28. 28. 28 public class ServiceManager { /** * The list of the bound services to this used to unbind the service. A service is pointed by its serviceConnection. */ List<ServiceConnection> boundServices = null; List<Service> serviceAndroid = null; List<ServiceBusiness> singletonServices = null; /** * Empty constructor to instantiate the list of bound services */ private ServiceManager() {boundServices = new ArrayList<ServiceConnection>();...} /** Destructor **/ /** * This method is called by MApplication to unbind all the services and let them die when your application die */ public synchronized void unbindAndDie() {// Browse all the services and unbind them all for (ServiceConnection sConn : boundServices) { //first unbind the service MAppInstance.ins.getApplication().unbindService(sConn); } for (Service servAndroid: servicesAndroid) { servAndroid = null;} boundServices.clear(); //Do the same with your Singleton Service for (ServiceBuisness singleton : singletonServices) { singleton=null;} //Kill your executor services //the ones that has to let your thread finish //the ones that has to finish right now } Instanciation à la demande
  29. 29. 29 private ExecutorService keepAliveThreadsExcecutor = null; /*** @return the cancelableThreadsExceutor */ public final ExecutorService getKeepAliveThreadsExecutor() { if (keepAliveThreadsExceutor == null) { keepAliveThreadsExceutor = Executors.newFixedThreadPool(4, new BackgroundThreadFactory()); } return keepAliveThreadsExceutor; } /**ShutDown the ExecutorService but wait for thread to finish their job */ private void killKeepAliveThreadExecutor() { if (keepAliveThreadsExceutor != null) { keepAliveThreadsExceutor.shutdown(); // Disable new tasks from being submitted try {// as long as your threads hasn't finished while (!keepAliveThreadsExceutor.isTerminated()) { // Wait a while for existing tasks to terminate if (!keepAliveThreadsExceutor.awaitTermination(5, TimeUnit.SECONDS)) { // Cancel currently executing tasks keepAliveThreadsExceutor.shutdown(); Log.e("MyApp", "Probably a memory leak here"); } } } catch (InterruptedException ie) { keepAliveThreadsExceutor.shutdownNow(); keepAliveThreadsExceutor=null; Log.e("MyApp", "Probably a memory leak here too"); } } keepAliveThreadsExceutor=null;} Instanciation à la demande
  30. 30. 30 Persister l'instanciation Application View Presenter HumanService LazyLoading Services Manager DAO Cancelable KeepAlive ThreadsPools Ne pas suivre le cycle de vie des activités mais le cycle de vie de l'application
  31. 31. 31 Persister l'instanciation Application 0-1 HumanService Services Manager 0-1 But wait ! AndroidServices
  32. 32. 32 Persister l'instanciation Application 0-1 HumanService Services Manager 0-1 Dead Lock occurs ! AndroidServices
  33. 33. Garde le Service en vie (car conserve le ServiceManager en vie) Garde l'application en vie (car toujours Bound avec le ServiceManager) 33 Persister l'instanciation Application 0-1 HumanService Services Manager 0-1 Dead Lock occurs ! AndroidServices
  34. 34. Garde le Service en vie (car conserve le ServiceManager en vie) Garde l'application en vie (car toujours Bound avec le ServiceManager) 34 Persister l'instanciation Application 0-1 HumanService Services Manager 0-1 Dead Lock occurs ! AndroidServices
  35. 35. Garde le Service en vie (car conserve le ServiceManager en vie) Garde l'application en vie (car toujours Bound avec le ServiceManager) 35 Persister l'instanciation Application 0-1 HumanService Services Manager 0-1 Dead Lock occurs ! AndroidServices Ne pas suivre le cycle de vie des activités mais le cycle de vie de l'application La solution :
  36. 36. Cycle de vie de l'application C'est quoi le cycle de vie de l'application ? Quand il n'y a plus d'activités visibles depuis une seconde, je peux considérer que mon application est terminée.
  37. 37. Cycle de vie de l'application Le one second pattern: A release memory pattern IsActivity Alive 37 Application View Services Manager onStop onStart Runnable mServiceKiller; Launch it In1Second if(false) unbindAndDie() if false /** Destructor **/ /** * This method is called by MApplication to unbind all the services and let them die when your application die */ public synchronized void unbindAndDie() { // Browse all the services and unbind them all for (ServiceConnection sConn : boundServices) { //first unbind the service unbindService(sConn);} dService = null;boundServices.clear();} registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() { public void onActivityStopped(Activity activity) {isActivityAlive.set(false);} public void onActivityCreated(Activity activity) {isActivityAlive.set(true);}}); // launch the Runnable mServiceKiller in 1 seconds getServiceKillerHanlder().postDelayed(getServiceKiller(), 1000); IsActivity Alive
  38. 38. Cycle de vie de l'application Réagissez au CallBack onMemoryLow ApplicationServices Manager onLowMemory (...) System unbindAndDie() Le LazyLoading est votre philosophie
  39. 39. 39 Assurer l'Asynchronicité Sur Android, il faut être asynchrone, tous le monde le sait ! Ceux qui codent la couche DAO le savent Ceux qui codent la couche vue le savent Thread(Thread(Thread(Thread(do something)))) Ceux qui codent la couche de com le savent Ceux qui codent la couche Service le savent
  40. 40. 40 Assurer l'Asynchronicité Un seule règle: La couche service est votre barrière d'Asynchronicté. Chaque méthode publique de chaque service s'exécute dans un Thread. Et nulle part ailleurs de Thread est lancé. (à part les Animations Thread de gingerbread, putain de gingerbread)
  41. 41. 41 Assurer l'Asynchronicité public class MyBusinessService{... public void loadDataAsync(int itemId) { MyApp.instance.getServiceManager() .getCancelableThreadsExecutor() .submit(new RunnableLoadData(itemId)); } private class RunnableLoadData implements Runnable { public int itemId; public RunnableLoadData(int itemId) {this.itemId=itemId} public void run() { loadDataSync(itemId);} } public void loadDataSync(int itemId) { // your code here}
  42. 42. Assurer l'Asynchronicité Vous pouvez utiliser PoolExecutor + Runnable Vous pouvez utiliser les IntentService Vous pouvez utiliser les AysncTask https://www.youtube.com/watch?v=jtlRNNhane0&index=4&list=PLWz5rJ2 EKKc9CBxr3BVjPTPoDPLdPIFCE Vous pouvez utiliser les HandlerThread Vous pouvez utiliser les AysncTask
  43. 43. Chaque appel à un service se fait de manière asynchrone 43 HumanService View Presenter doSomething() { //code... Human hum =getHumanService().getHuman("toto"); //other code using hum txvHumanName.setText(hum.getName()); } call Failed It's asynchronous What we used to do before Asynchronicité
  44. 44. 44 Services View Presenter doSomething() { getHumanService().getHuman("toto"); } call What we need to do now doSomethingPart2(Human hum) { //other code using hum txvHumanName.setText(hum.getName() );} async return Yes good way Assurer l'Asynchronicité Chaque appel à un service se fait de manière asynchrone Les méthodes des Activités doivent être segmentées
  45. 45. Les instancier à la demande 45 Il faut qu'on arrive avec nos services métiers à: ArchiDroid Ne les instancier QU'une seule fois Mettre en place l'asynchronicité Ne pas suivre le cycle de vie des activités mais le cycle de vie de l'application Les laisser terminer leur traitement
  46. 46. Disponible sur mon GitHub 46 J'utilise le Live Template Et le code arch_Service_Method_WithArgs arch_ServManager_CancelableThread arch_ServManager_KeepAliveThread arch_Service_Method et plus ...
  47. 47. Architecture But wait ! C'est pas un peu compliqué ton truc? Pour la petite histoire
  48. 48. En upload En download
  49. 49. Quelle est ma stratégie? (oversync:( G.U.I. Thread Background Thread View Presenter ServiceData DataCom DataDao Services Manager ServiceUpdater call BIND START load return data Intent|Event call return data Caching return data fire DataUpdateEvent Intent ContentObserver DownLoad Application TimeStamp
  50. 50. Quelle est ma stratégie? (oversync:( G.U.I. Thread Background Thread View Presenter ServiceData DataCom DataDao Services Manager ServiceUpdater call BIND START load return data Intent|Event call return data Caching return data fire DataUpdateEvent Intent ContentObserver DownLoad Application onStop onCreate
  51. 51. G.U.I. Thread Background Thread ViewPresenter ServiceData DataCom DataDao Services Manager ServiceUpdater call BIND START return data Intent|Event Caching DownLoad Application onStop onCreate
  52. 52. Quelle est ma stratégie? (oversync:( G.U.I. Thread Background Thread View Presenter ServiceData DataCom DataDao Services Manager ServiceUpdater call BIND START save call Caching UpLoad TimeStamp Application TimeStamp
  53. 53. 54 DataDaoServiceUpdater push Message GoogleCloud Messaging Quand il y a de nouvelles données à diffuser +PayLoad + Token (DataVersion) store Backend server BroadcastReceiver start WakeUp! Vous êtes à jour GoogleCloudMessaging
  54. 54. Les tests Intégration et Déploiement continue
  55. 55. Test Merci AndroidStudio Merci Gradle
  56. 56. Test No test No trust Algo
  57. 57. Test No test No trust Algo Unit
  58. 58. Test No test No trust Algo Unit Locale
  59. 59. Test No test No trust Algo VersionUnit Locale
  60. 60. Test No test No trust Algo Perm VersionUnit Locale
  61. 61. Test No test No trust Algo Perm VersionUnit Screen Dpi Locale
  62. 62. Test No test No trust Algo Perm Version Screen Size Unit Screen Dpi Locale
  63. 63. Test No test No trust Algo Perm Version Screen Size Intent Unit Screen Dpi Locale
  64. 64. Test No test No trust Algo Perm Réseau Version Screen Size Intent Unit Screen Dpi Locale
  65. 65. Test Vous devez tester toutes vos configurations matérielles GooglePla yServices RéseauVersion Screen Size Screen Dpi Locale 2316 463 6912
  66. 66. Test Vous devez tester toutes vos configurations matérielles GoogleP S RéseauVersion Screen Size Screen Dpi Locale 2316 463 168
  67. 67. Test Vous devez automatiser le passage des tests
  68. 68. Test Comment on fait ? Instrumentation Tests Unit Tests S'exécute sur Android Pas de fake du système S'exécute sur la JVM Fake des composants système (Mockito)
  69. 69. Test Unit Tests public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { System.out.println("ExampleUnitTest"); assertEquals(4, 2 + 2); } }
  70. 70. Test Instrumentation Tests public class CityServiceTest extends AndroidTestCase { public void setUp() {super.setUp(); EventBus.getDefault().register(this); } public void tearDown() { super.tearDown(); EventBus.getDefault().unregister(this); } public void testFindCityByNameAsync() { MyApplication.instance .getServiceManager() .getCityService() .findCityByNameAsync(testedCityName) }}
  71. 71. Test Instrumentation Tests @Subscribe public void onEvent(FindCitiesResponseEvent event){ assertNotNull(event); assertNotNull(event.getFindCitiesResponse()); assertNotNull(event.getFindCitiesResponse().getCities()); assertNotNull(event.getFindCitiesResponse().getCities().get(0)) DataCheck.getInstance() .checkCity(event.getFindCitiesResponse().getCities().get(0)); }
  72. 72. Test BroadcastReceiver Communication Com D.A.O. DAO ExceptionManagerTools Tester Tests JUNIT Tests Tests Transverse Transverse Instrumentation Tests Unit Tests
  73. 73. Test Mais là, comment on fait ? Services AndroidServices SingletonServices Service knows Communication Com I N T F knows D.A.O. DAO I N T F Tests JUNIT On joue avec les saveurs ? ? ?
  74. 74. Test On joue avec les saveurs et les injecteurs Mais là, comment on fait ? public class Injector { public static ServiceManagerMocked getServiceManager(){ return new ServiceManagerMocked(); } } public class Injector { public static ServiceManagerMocked getServiceManager(){ return new ServiceManager (); } }
  75. 75. Test On joue avec les saveurs et les injecteurs Mais là, comment on fait ? // If you need to add more flavors, consider using flavor dimensions. productFlavors { mock { applicationIdSuffix = ".mock" } prod { } }
  76. 76. Modèle n-tier Services AndroidServices SingletonServices Service knows Communication Com I N T F knows D.A.O. DAO I N T F Tests JUNIT Tester mockDebug
  77. 77. Modèle n-tier MockView View = MVP Presenter ViewIntf 1 1 JUNIT Services AndroidServices SingletonServices Service I N T F Tests Tester mockDebug
  78. 78. Modèle n-tier View = MVP Presenter View 1 1 Services AndroidServices SingletonServices Service I N T F Espresso AndroidTest SDK Tests Tester mockDebug
  79. 79. Test Et après ? Industrialisation via l'intégration continue. mais c'est toujours un peu l'enfer... on ne vous le cache pas
  80. 80. Test Et après ? Le déploiement continue. Oui c'est possible.
  81. 81. Square et les autres
  82. 82. Librairies Un besoin Une fonctionnalité Une librairie Utilisez une librairie parce que vous en avez besoin, pas pour le plaisir ! Moins vous avez de librairies sur votre projet, mieux vous vous porterez. Choisissez avec attention vos librairies, c'est critique, ne merdez pas.
  83. 83. Librairies Avant tout SupportLibrary
  84. 84. Librairies Juste après DesignLibrary
  85. 85. Librairies Se simplifier la vie avec la couche de communication Http Retrofit
  86. 86. 90 public interface WebServerIntf { /** Get Method (this is the way to declare them using Retrofit 2.0) @GET("posts/1") Call<Post> getPostOne(); @GET("posts/{id}") Call<Post> getPostById(@Path("id") int id); @GET("posts") Call<List<Post>> getPostsList(); } Définition getPostOneCall = getSimpleClient().getPostOne(); getPostOneCall.enqueue(new Callback<Post>() { @Override public void onResponse(Response<Post> response) { } @Override public void onFailure(Throwable t) { } }); Usage public static final String BASE_URL = "http://jsonplaceholder.typicode.com/"; public static WebServerIntf getSimpleClient(){ Retrofit ra=new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(MoshiConverterFactory.create()) .build(); WebServerIntf webServer=ra.create(WebServerIntf.class); return webServer; } Instanciation Retrofit
  87. 87. Librairies Une couche Http sans bugs quelque soit la version OkHttp
  88. 88. 92 OkHttp OkHttpClient client=null; private OkHttpClient getClient(){ if(client==null) { File myCacheDir = new File(getCacheDir(), "OkHttpCache"); int cacheSize = 1024 * 1024; Cache cacheDir = new Cache(myCacheDir, cacheSize); client = new OkHttpClient.Builder().cache(cacheDir).build(); } return client; } Définition
  89. 89. 93 OkHttp String urlGet = "http://jsonplaceholder.typicode.com/posts/1"; private String getAStuff() throws IOException { Request request = new Request.Builder() .url(urlGet) .get() .build(); //the synchronous way (Here it's ok we are in an AsyncTask already) Response response = getClient().newCall(request).execute(); String ret = response.body().string(); response.body().close(); return ret; } Utilisation
  90. 90. Librairies Optimiser les écritures disques Okio
  91. 91. 95 OkIo /** * Read the file you just create */ private void readCachFile() { //open File myFile = new File(getCacheDir(), "myFile"); try { BufferedSource okioBufferSrce = Okio.buffer(Okio.source(myFile)); str = okioBufferSrce.readUtf8(); //don't forget to close, else nothing appears okioBufferSrce.close(); }}
  92. 92. 96 OkIo /** * Write a file */ private void writeCachFile() { //open File myFile = new File(getCacheDir(), "myFile"); //then write if (!myFile.exists()) {myFile.createNewFile();} BufferedSink okioBufferSink = Okio.buffer(Okio.sink(myFile)); okioBufferSink.writeUtf8(str); //don't forget to close, else nothing appears okioBufferSink.close(); }
  93. 93. Librairies Optimiser la manipulation JSon Moshi
  94. 94. 98 Moshi Moshi moshi = new Moshi.Builder().build(); JsonAdapter<MyJsonObject> adapter = moshi.adapter(MyJsonObject.class); MyJsonObject myObj=null; //write File myFile = new File(ctx.getCacheDir(), "myJsonObjectFile"); BufferedSink okioBufferSink = Okio.buffer(Okio.sink(myFile)); adapter.toJson(okioBufferSink, new MyJsonObject()); //don't forget to close, else nothing appears okioBufferSink.close();
  95. 95. 99 Moshi Moshi moshi = new Moshi.Builder().build(); JsonAdapter<MyJsonObject> adapter = moshi.adapter(MyJsonObject.class); MyJsonObject myObj=null; //or read BufferedSource okioBufferSource = Okio.buffer(Okio.source(myFile)); myObj = adapter.fromJson(okioBufferSource);
  96. 96. Librairies Cohérence des librairies Retrofit OkHttp OkIo Moshi
  97. 97. Librairies Supprimer les Intents pour la communication interne Les bus évènementiels OTTO EventBus
  98. 98. Librairies Supprimer les Intents pour la communication interne Les bus évènementiels OTTO EventBus A n'utiliser que pour les retours d'appels ou les évènements
  99. 99. EventBus @Subscribe(threadMode = ThreadMode.MAIN) public void onEventMainThread(ErrorEvent event){ int errorMessageId=event.getErrorMessageId(); String errorMessage; if(errorMessageId==0){ errorMessage=event.getErrorMessage(); }else{ errorMessage=getResources().getString(errorMessageId); } displayError(errorMessage); } EventBus.getDefault().post(ErrorEvent);
  100. 100. GreenDao Librairies Se simplifier la couche DAO Les O.R.M SugarOrm OrmLite Realm
  101. 101. public class City extends SugarRecord { private int cityId; private String name; private Coordinates coordinates; @Ignore private List<WeatherMetaData_City> metaDataList = null; /**Because of SugarOrm bad management of one to many relationship*/ public List<WeatherMetaData_City> getMetaDataList() { if(metaDataList==null){ //load them metaDataList= WeatherMetaData_City.find(WeatherMetaData_City.class, "CITY = ?", Long.toString(getId())); } return metaDataList; } SugarOrm
  102. 102. SugarOrm public long save(City city){ long id; //you need to manually save others elements (first) Coordinates.save(city.getCoordinates()); WeatherDetails.save(city.getWeatherDetails()); Wind.save(city.getWind()); Clouds.save(city.getClouds()); Ephemeris.save(city.getEphemeris()); id = City.save(city);
  103. 103. SugarOrm public void delete(City city){ if(city.getId()!=null) { //you need to manually delete others elements (first) Coordinates.delete(city.getCoordinates()); WeatherDetails.delete(city.getWeatherDetails()); Wind.delete(city.getWind()); Clouds.delete(city.getClouds()); Ephemeris.delete(city.getEphemeris()); City.delete(city); } }
  104. 104. SugarOrm List<City> cities= City.find(City.class, "CITY_ID =?", Integer.toString(cityId));
  105. 105. Librairies Analyse du besoin utilisateur Fabric (CrashLytics) Analytics For Android Flurry
  106. 106. Librairies Simplifier le téléchargement d'images vers les ImageView Glide Picasso
  107. 107. Librairies Gestion des Fonts Calligraphy
  108. 108. Librairies Gestion des Dates JodaTime
  109. 109. Librairies Stratégie de mises à jour GoogleCloudMessaging
  110. 110. Librairies Le futur RxJava Realm Retrofit Kotlin
  111. 111. G.U.I. Thread Background Thread View Model ServiceData DataCom DataDao Services Manager ServiceUpdater Caching DownLoad Application TimeStamp Retrofit SugarOrm Dagger EventBusEventBus
  112. 112. Librairies pour les Tests
  113. 113. Librairies L'inversion de contrôle pour les tests (et injecter le bon contexte prod/mock) Dagger IOC sur Android est un suicide
  114. 114. Librairies
  115. 115. Librairies Pour Mocker (parodier) les objets et jouer des tests unitaires Mockito
  116. 116. Librairies Pour tester les IHM Espresso
  117. 117. Librairies Pour remonter les bugs à l'équipe de développement Crashlytics
  118. 118. Librairies Pour surveiller les fuites mémoires CanaryLeaks
  119. 119. Librairies
  120. 120. Librairies Pour exécuter ses tests sur un émulateur Genymotion
  121. 121. Librairies Pour exécuter ses tests en parallèle (et capture d'écran) Spoon
  122. 122. Librairies dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:23.1.1' compile 'com.android.support:recyclerview-v7:23.1.1' compile 'com.android.support:cardview-v7:23.1.1' compile 'com.android.support:design:23.1.1' // I want eventBus compile 'org.greenrobot:eventbus:3.0.0' // I want SugarOrm compile 'com.github.satyan:sugar:1.4' // I want Retrofit,OkIo, OkHttp and Moshi compile 'com.squareup.retrofit2:retrofit:2.0.0-beta3' compile 'com.squareup.okhttp3:okhttp:3.0.0-RC1' compile 'com.squareup.retrofit2:converter-moshi:2.0.0-beta3' compile 'com.squareup.okhttp3:logging-interceptor:3.0.0-RC1' compile 'com.squareup.okio:okio:1.6.0' // I want Dagger 2 //I want JodaTime not to drive nuts managing date compile 'net.danlew:android.joda:2.9.2' //For the Tests !!! // Dependencies for unit tests testCompile 'junit:junit:4.12' //for unit tests testCompile "org.mockito:mockito-all:$rootProject.ext.mockitoVersion" // Android Testing Support Library's runner and rules androidTestCompile "com.android.support.test:runner:$rootProject.ext.runnerVersion" androidTestCompile "com.android.support.test:rules:$rootProject.ext.rulesVersion" // Espresso UI Testing dependencies. androidTestCompile "com.android.support.test.espresso:espresso-core:$rootProject.ext.espressoVersion" androidTestCompile "com.android.support.test.espresso:espresso-intents:$rootProject.ext.espressoVersion" // Espresso-contrib for DatePicker, RecyclerView, Drawer actions, Accessibility checks, CountingIdlingResource androidTestCompile "com.android.support.test.espresso:espresso-contrib:$rootProject.ext.espressoVersion" compile "com.android.support.test.espresso:espresso-idling-resource:$rootProject.ext.espressoVersion" }
  123. 123. la météo sur github
  124. 124. Tuto sur Github Le projet ForecastYahooRest
  125. 125. articles et conférences
  126. 126. Must read/watch https://medium.com/@chethaase https://www.youtube.com/watch?v=BlkJzgjzL0c&list=PLWz5rJ2EKKc_Tt7q77qwyKRgytF1RzRx8&index=2 https://skillsmatter.com/skillscasts/5971-an-android-journey https://www.youtube.com/watch?v=br3drCNFti8 https://www.youtube.com/watch?v=WvyScM_S88c https://www.youtube.com/watch?v=KIAoQbAu3eA Architecture https://github.com/konmik/konmik.github.io/wiki/Introduction-to-Model-View-Presenter-on-Android https://vaadin.com/blog/-/blogs/is-mvp-a-best-practice- http://blog.cleancoder.com/uncle-bob/2016/01/04/ALittleArchitecture.html http://fr.slideshare.net/pileromain/ingredients-for-a-healthy-codebase https://github.com/ivacf/archi https://speakerdeck.com/rallat/android-development-like-a-pro https://github.com/reark/reark https://medium.com/android-news/android-architecture-2f12e1c7d4db#.e4z6np1sn http://blog.sqisland.com/2015/11/mvp-missing-link.html Librairies
  127. 127. Architecture (suite) http://fr.slideshare.net/DarxVal/model-view-presenter-presentation http://aviadezra.blogspot.fr/2009/08/mvp-mvvm-winforms-data-binding.html https://blogs.msdn.microsoft.com/erwinvandervalk/2009/08/14/the-difference-between-model-view-viewmodel-and- other-separated-presentation-patterns/ Tour d'horizon et bonne pratique http://blog.octo.com/retour-dexperience-mobile-le-monde-partie-2/ https://github.com/futurice/android-best-practices http://www.curious-creature.com/2008/12/18/avoid-memory-leaks-on-android/ Librairie http://square.github.io/retrofit/http://inthecheesefactory.com/blog/retrofit-2.0/en https://speakerdeck.com/jakewharton/simple-http-with-retrofit-2-droidcon-nyc-2015 https://github.com/codepath/android_guides/wiki/Must-Have-Libraries https://docs.google.com/presentation/d/1BzFcK2t_PdkM6tQZIhpx8yeeIxaB15mf6U6kzvSnE90/edit#slide=id.p https://android-arsenal.com/ Librairies
  128. 128. Tests, Intégration continue et déploiement continue http://jeremie-martinez.com/2016/01/14/devops-on-android/ http://chiuki.github.io/advanced-android-espresso/#/ https://www.youtube.com/watch?v=JlHJFZvZyxw http://developer.android.com/training/testing/start/index.html https://speakerdeck.com/tguerin/robotium-vs-espresso https://docs.google.com/presentation/d/10Y9wGn1tgIasq6DqG30Qz27KJlndZAoHX1KI41aNkdM/edit#slide=id.g2a03d 18b6_080 http://robolectric.org/writing-a-test/ https://corner.squareup.com/2013/04/the-resurrection-of-testing-for-android.html https://www.youtube.com/watch?v=3WONuRSUHmw http://riggaroo.co.za/setting-circle-ci-test-deploy-build-android-app/ https://google.github.io/android-testing-support-library/downloads/release-notes/ Google Tests Lab https://developers.google.com/cloud-test-lab/overview#devicetypes
  129. 129. GCM NetworkManager https://www.bignerdranch.com/blog/optimize-battery-life-with-androids-gcm-network-manager/ http://developer.android.com/training/efficient-downloads/efficient-network-access.html#RadioStateMachine
  130. 130. Je cherche un client Pour m'engager Sur la réussite de son produit Android (avec un objectif de haute qualité) en remote (ou Presque) en tant que tech lead en freelance
  131. 131. Lieu : Paris Date : 10 - 13 Mai 2016 Durée : 4 jours 138 Lieu : Lyon Date : 23 - 27 Mai 2016 Durée : 5 jours Lieu : Paris Date : 06 - 10 Juin 2016 Durée : 5 jours
  132. 132. #android2ee mathias.seguy@android2ee.com www.android2ee.com
  133. 133. Thank you!Mathias Seguy Android2EE @android2ee Slides: http://fr.slideshare.net/Android2EE Code: https://github.com/MathiasSeguy-Android2EE Android2EE http://android2ee.com
  134. 134. Thank you!Mathias Seguy Android2EE @android2ee Slides: http://fr.slideshare.net/Android2EE Code: https://github.com/MathiasSeguy-Android2EE Android2EE http://android2ee.com

×