A Deep Dive into Open Source Android Development

  • Published on
    06-May-2015

  • View
    9.761

  • Download
    0

Embed Size (px)

DESCRIPTION

The increasing popularity of the Android platform over the past two years has encouraged many talented developers to contribute. Developers no longer need to invent their own wheels from scratch. Instead, many open source tools and libraries are becoming available for Android developers. In this talk we will take a deep dive into Android programming and how developers can leverage open source tools to bootstrap their Android apps. We will also talk about how developers can contribute back to the open source community.

Transcript

  • 1.A Deep Dive into Open Source AndroidDevelopmentDavid Wu@wumanblog.wu-man.com Taipei Google Technology User Group (2013/01/02)Taipei Open Source Software User Group (2012/12/18) (2012/12/07)1

2. about.me/wuman 2 3. Overview Why use open source? Popular open source Android libraries Why open source? How to open source Conclusion3 4. Why use open source? 4 5. Better Quality Developed by many passionate developers Innovation and enhancements over time Improvements and bug xes by more people Closest to user needs 5 6. Freedom Make custom changes to tailor to own needs Good open source software usually adheres toopen standards and promotes interoperability 6 7. Learn from the Masters Open source developers are usually good at whatthey do The fastest way to improve is to learn fromreading their code Discussions are usually carried out in the openvia mailing lists7 8. Not Possible Otherwise It is much harder to develop an Android appwithout using open source software Platform compatibility UI compatibility8 9. Android appdevelopment isNOT easy! 9 10. Version CodenameAPI Distribution Eclair & older1.5Cupcake30.1% Jelly Bean1.6 Donut 40.3%Froyo2.1Eclair 72.7%2.2 Froyo 8 10.3%Ice Cream Sandwich 2.3 - 2.3.290.2%Gingerbread2.3.3 - 2.3.7 1050.6%3.1 12 0.4%Honeycomb3.2 13 1.2%Gingerbread HoneycombIce Cream4.0.3 - 4.0.4 1527.5%Sandwich4.1 16 5.9%Jelly Bean4.2 17 0.8%Apps targeting the widest audience need tocare about platform compatibility10 11. UI Requirements for Featured Apps Follow Android Design guidelines Navigation Action Bar Use common UI patterns and icons 11 12. Action Bar Incompatibility Before 3.0, there was nocommon pattern or API forin-app navigation. Action Bar API and patternguidelines (tablet-only) areintroduced in ICS. Additional API changes forthe phone are introduced inJelly Bean. 12 13. Theme Incompatibility There is not a common cross-platform defaulttheme for developers to derive from. 13 14. Common UI Pattern Implementations Some common UI patterns are not provided aspart of the Android framework. Pull-to-refresh ListView Sliding Drawer Menu (ViewDeck)14 15. Common Tools and Usage Patterns Some common tools and usage patterns are notprovided as part of the Android framework. LRU cache that persists to disk Image loading with cache support Logging and user feedback support 15 16. Popular Open Source Libraries16 17. UI and Compatibility 17 18. ActionBarSherlockhttp://actionbarsherlock.com/18 19. Action Bar General Layout App icon and up affordance View switch control Action buttons Action overflow 19 20. Split Action Bar Main action bar Top bar via tabs or spinner Bottom bar with actionbuttons and overflow20 21. Contextual Action Bars 21 22. HoloEverywhere Back ports the Holo themesfrom Jelly Bean to Eclair andabovehttps://github.com/ChristopheVersieux/HoloEverywhere 22 23. NineOldAndroids Back ports the android.animation.* API fromHoneycomb to all previous platforms Drawing vs. View properties ObjectAnimator.ofFloat(myObject, "translationY",-myObject.getHeight()).start(); http://nineoldandroids.com/23 24. UniedPreference https://github.com/saik0/UniedPreference 24 25. Android Support Package Back ports multi-pane Fragment support fromHoneycomb to Donut25 26. Android Support Package Includes ViewPager, PagerTitleStrip,PagerTabStrip implementations 26 27. Android Support Package Back ports all Notication features from JellyBean to Donut 27 28. Android Support Package Back ports asynchronous background Loadersupport from Honeycomb to Donut Includes implementation for a memory-basedLruCache 28 29. Android-MenuDrawer https://github.com/SimonVT/android-menudrawer 29 30. Android-PullToRefreshhttps://github.com/chrisbanes/Android-PullToRefresh30 31. Polarishttps://github.com/cyrilmottier/Polaris31 32. Croutonhttps://github.com/keyboardsurfer/Crouton32 33. Android-Query Enables easier UI manipulation via methodchainingAQuery aq = new AQuery(view); aq.id(R.id.icon).image(R.drawable.icon).visible().clicked(this, "someMethod");aq.id(R.id.name).text(content.getPname());aq.id(R.id.time).text(FormatUtility.relativeTime( System.currentTimeMillis(), content.getCreate())).visible();aq.id(R.id.desc).text(content.getDesc()).visible(); http://code.google.com/p/android-query/ 33 34. Caching andNetworking34 35. DiskLruCache Back ports the DiskLruCache from Ice CreamSandwich to all versions of Android https://github.com/JakeWharton/DiskLruCache 35 36. TwoLevelLruCache A two-level LRU cachecomposed of rst level memory-based LruCache second level disk-based DiskLruCachehttp://wuman.github.com/TwoLevelLruCache/36 37. AndroidImageLoader Asynchronous imageloading Images are downloaded and saved to TwoLevelLruCache via a pool of background threads Supports Bitmap transformations http://wuman.github.com/AndroidImageLoader/ 37 38. HttpResponseCache Back ports the persistent HttpResonseCachefrom Ice Cream Sandwich to all versions ofAndroid Provides transparent and automatic persistentcaching of HTTP and HTTPS requests that usethe HttpUrlConnection classhttps://github.com/candrews/HttpResponseCache38 39. HTTP-Request Provides a simpler and easier interface toHttpURLConnection Uses method chainingHttpRequest.get("http://google.com").receive(System.out); https://github.com/kevinsawicki/http-request39 40. Concurrency andCommunication40 41. Tape Provides a persistent task queueServerClient UITaskQueue peek() remove() add() UploadTask UploadTaskServicehttp://square.github.com/tape/41 42. Otto An event bus forked from EventBus of GoogleGuava targeting the Android platform Publish Subscribe FragmentFragment Fragment BusFragment ServiceActivityhttp://square.github.com/otto/ 42 43. Data Representationand Processing43 44. GSON POJO to JSON bi-directional conversion Built-in serializers and deserializers for primitivedata types Supports extensions for complex objectshttp://code.google.com/p/google-gson/44 45. Jackson JSON Processor Streaming JSON parser and serializer Supposedly faster than the built-in ones http://wiki.fasterxml.com/JacksonHome 45 46. Json-Path XPath- and jQuery-like selector for JSON{ "store": { "book": [ { "category": "reference", "author": "Nigel Rees", "title": "Sayings of the Century", "price": 8.95 }, { "category": "fianceection", "author": "Evelyn Waugh", "title": "Sword of Honour", String author = JsonPath.read(json, "$.store.book[1].author"); "price": 12.99, "isbn": "0-553-21311-3" } ], "bicycle": { "color": "red", "price": 19.95 } }} http://code.google.com/p/json-path/46 47. jOOX - Java Object Oriented XML XML manipulative parser with selector syntax XML document creationhttps://github.com/jOOQ/jOOX 47 48. JSoup HTML parser for Java using jQuery-like selectorsyntax Manipulates HTML elements, attributes and text Pretties HTML http://jsoup.org/48 49. OrmLite ORM library that persists POJO to SQLitedatabasespublic class SimpleData {! @DatabaseField(generatedId = true)! int id;! @DatabaseField(index = true)! String string;! @DatabaseField! long millis;! @DatabaseField! Date date;! @DatabaseField! boolean even;! SimpleData() {! ! // needed by ormlite! }! public SimpleData(long millis) {! ! this.date = new Date(millis);! ! this.string = (millis % 1000) + "ms";! ! this.millis = millis;! ! this.even = ((millis % 2) == 0);! }}http://ormlite.com/49 50. Google Guava Many utilities to make Java development easierhttp://code.google.com/p/guava-libraries/50 51. Dependency Injection 51 52. AndroidAnnotations Runtime injection of Android views, extras,system services, resources, etc. Method annotation to indicate which thread torun in Method annotation to bind event listeners toevents http://androidannotations.org/52 53. RoboGuice Runtime injection of Android views, systemservices, resources, POJO, etc. http://code.google.com/p/roboguice/ 53 54. Dagger Compile-time dependency injection (bindingvalidation) for Android Not as feature-rich as other dependencyinjection frameworks but much faster API very similar to Google Guice http://square.github.com/dagger/54 55. Testing55 56. Android Test Framework Built-in Android Test Project support Use AndroidTestCase to test non-visualcomponents Use Instrumentation to control visual parts of anapplication Command line monkey tool to send randomevents to device56 57. Robotium Black-box testing framework for Android Improved readability of test cases compared tostandard Instrumentation tests Handles multiple Android activities http://code.google.com/p/robotium/57 58. Robotium // Check that we have the right activity solo.assertCurrentActivity("wrong activiy", SimpleActivity.class); // Click a button which will start a new Activity // Here we use the ID of the string to find the right button solo.clickOnButton(solo.getString(R.string.button1)); // Validate that the Activity is the correct one solo.assertCurrentActivity("wrong activiy", SimpleListActivity.class); // Open the menu solo.sendKey(Solo.MENU); solo.clickOnText("Preferences"); solo.clickOnText("User"); solo.clearEditText(0); Assert.assertTrue(solo.searchText("")); solo.enterText(0, "http//:www.vogella.com"); Assert.assertTrue(solo.searchText("http//:www.vogella.com")); solo.goBack();http://www.vogella.com/articles/AndroidTesting/article.html58 59. Mochito Android mocking framework API makes mocking tests very readablepublic void makePurchase(CreditCardManager creditCard) {if (creditCard.getCardType() == CREDIT_CARD_VISA) {creditCard.makePurchase(500);}}public void testMasterCardTransaction() {CreditCardManager creditCard = Mockito.mock(CreditCardManager.class);Mockito.when(creditCard.getCardType()).thenReturn(CREDIT_CARD_MASTER);makePurchase(creditCard);Mockito.verify(creditCard).getCardType();Mockito.verifyNoMoreInteractions(creditCard);}http://code.google.com/p/mockito/59 60. Robolectric Allows JVM unit testing with the JUnit4framework Reduces testing time from minutes to seconds Intercepts Android class loading and forwardmethod bodies to shadow objects http://pivotal.github.com/robolectric/60 61. Robolectric// Test class for MyActivity@RunWith(RobolectricTestRunner.class)public class MyActivityTest {private Activity activity;private Button pressMeButton;private TextView results;@Beforepublic void setUp() throws Exception {activity = new MyActivity();activity.onCreate(null);pressMeButton = (Button) activity.findViewById(R.id.press_me_button);results = (TextView) activity.findViewById(R.id.results_text_view);}@Testpublic void shouldUpdateResultsWhenButtonIsClicked() throws Exception {pressMeButton.performClick();String resultsText = results.getText().toString();assertThat(resultsText, equalTo("Testing Android Rocks!"));}}http://pivotal.github.com/robolectric/61 62. User Feedback62 63. ACRA Sends a detailed bug or crash report to Google Docshttp://acra.ch/ 63 64. BugSense/Crittercism Collects bug and crash reports Generates analytics for crash reports Supports x versioning and noticationshttp://www.bugsense.com/docs/android 64 65. Google Analytics for Android Collect user engagement data and generate realtime analytics Demohttps://developers.google.com/analytics/devguides/collection/android/v2/ 65 66. Bootstrap Project Generator66 67. Android Bootstrap Includes a full working implementation of Android support package android-maven-plugin RoboGuice ActionBarSherlock http-request GSON Robotium API on Parse.comhttp://www.androidbootstrap.com/ 67 68. AndroidKickstartR Includes a full working implementation of Android support package android-maven-plugin AndroidAnnotations ActionBarSherlock NineOldAndroids ACRAhttp://androidkickstartr.com/68 69. Tools69 70. Android Asset Studio Demo http://android-ui-utils.googlecode.com/hg/asset-studio/dist/index.html70 71. Subtle Patterns Collection of free tilable textured patterns Demo http://subtlepatterns.com/71 72. Charles HTTP proxy that enables developers to view allHTTP/HTTPS trafc between the device and theInternethttp://www.charlesproxy.com/ 72 73. Others 73 74. More Detailed Listing App Dev Wiki http://appdevwiki.com/wiki/show/HomePage The Ultimate Android Library http://www.theultimateandroidlibrary.com/ AppBrain Android Developer Tools http://www.appbrain.com/stats/libraries/dev74 75. Why open source? 75 76. Better App Quality Normally for various practical reasons we dontopen source the entire app Open source useful components within the appinto a library More debugging for you The process of open sourcing forces you torethink your architecture critically76 77. Reciprocity A way to give back to the community Feels good77 78. Portfolio Buildup GitHub, not LinkedIn 78 79. Grow Faster The more you engage in the open sourcecommunity, the faster you learn and grow as atech professional. The process of open sourcing encompassesalmost all areas of software development.79 80. Better World What goes around comes around The template for this Keynote presentation isderived from an open source project!https://github.com/JakeWharton/AndroidDesignKeynoteTheme 80 81. How to Open Source 81 82. DisclaimerWhat follows is based on the presentation EffectiveOpen Source given by Jake Wharton andadditionally, a more elaborate presentation based onmy own experiences. https://github.com/JakeWharton/EffectiveOpenSource82 83. Component Identication Identify the part of your app that can beextracted out as an isolated, reusablecomponent. The component should serve to do a focusedtask very well. 83 84. Code Abstraction Extract the component into a separate packageor module and expose only via a small set ofpublic API. This is kind of like refactoring. The app shouldcontinue to work as expected and the moduleshould be treated just like an externaldependency. Reiterate the refactoring step several times until the exposed public API is minimal and clean the client code has good readability 84 85. Library Project Directory Structure Make the module either an independent Javalibrary project or an Android library projectdepending on whether Android resources areneeded in the library. Follow a common directory structure as denedin a maven archetype: org.apache.maven.archetypes/maven-archetype-quickstart de.akquinet.android.archetypes/android-release 85 86. Android Library Project Directory Structure library/ Android Library projecttest/ Android Test projectsamples/ Samples project (Android project)README Projects readmeLICENSE Projects licenseNotices and attributions required by NOTICElibraries that the project depends on86 87. Java Library Project Directory Structure library/Java library projectlibrary/src/main/java/ Java library sourceslibrary/src/test/java/Test sourcessamples/Samples project (Android project)READMEProjects readmeLICENSEProjects license Notices and attributions required by NOTICE libraries that the project depends on 87 88. Include Tests Good libraries are always bundled with tests. Itgives people condence and ensures quality. Tests are never enough. Write as many as youcan think of. Ensure all the tests are passed. 88 89. Code Quality and Style Standardize co...