The Good, the Bad and the Ugly things to do with android


Published on

The Java2Days 2011 conference Android presentation.
The Good, the Bad and the Ugly things to do with android

Published in: Technology
1 Like
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

The Good, the Bad and the Ugly things to do with android

  1. 1. The Good, The Bad, Mobile2Days and The Ugly… Things to do with AndroidStanojko Markovik03.11.2011@Java2Days
  2. 2. Your presenter…• Speaks a few languages (Java, C++, Python…)• Currently works at the ARTEMIS R&D department at SudParis Telecom Institute• Worked with android from v1.1both for app development and custom ROMs• Linux geek• JUGMK member
  3. 3. While developingfor Android youcan do…
  4. 4. Good stuff
  5. 5. Bad Stuff
  6. 6. UGLYstuff…
  7. 7. What will we talk about?? • Good practices and the 1 proper way to do things • Bad things people tend 2 to do and how to evade… • The ugly things no one 3 wants to talk about.
  8. 8. THE GOOD
  9. 9. The standard stuff first• Always keep Clean and concise code• DRY KISS - Always• Be weary of memory usage• Try to use libraries as external JAR files. - modularity - easier development sloop• If you comment something out.. Erase it.. You will probably never use it again
  10. 10. Android Specific stuff - UI • Android uses a modified version of the MVC patter, Views are made in XML. Populated by code • Android is aware of the display size. So use this, and have different graphics. For each size of the screen
  11. 11. Android Specific stuff - UI • Try to utilize the 9patch drawables as much as possible Example 1 Example 2
  12. 12. Android Specific stuff - UI • If the shapes are simple.. Write them in XML Sample Round shape definition in XML
  13. 13. Android Specific stuff - Code• Differentiate the LinkedList from the ArrayList in the mobile world, it matters…• Android uses a Google re-written Java, so most of the standard java classes you use are “optimized”, optimizations have bugs .• Cleanup code before using it.. The Android compiler does not exclude unused classes. This will greatly reduce your application size
  14. 14. Android Specific stuff - SDK• Always have a target SDK, and a target device. Maybe the code can be uniform and meant for all device, but the UI cannot.• Forget String-s use StringBuilders• Use a Debug condition for your Log statements. Remember that : logs concat strings and are NOISY!• Android has a GC, but System.gc() doesn’t work! Have it in mind…
  15. 15. Android Specific stuffVisual Scaling• Try to get used to thinking in DIPs and SP.• A good developer always wraps his content!• Android has a GC, but System.gc() doesn’t work! Have it in mind…
  16. 16. View.getTag() methodThis is the “hidden” pocket meant for the object towhich the view is refering• Use it on buttons to hold a state, or reference• Use it with cursor adapters to hold an object or database ID• Use it with custom views to hold misc data for the extra data you need.
  17. 17. notifyChange() methodVery often you have to write applications that useadapters from databases or webservices.The notifyChange() method is very important forautomatic update and/or content change.Whenever you insert/update any data in the source it isimportant to call this method to tell all the users torefresh or re-query their data.
  18. 18. THE BAD…
  19. 19. Developers tend to be lazy…• Respect The Activity Lifecycle
  20. 20. Database Cursors• Database connections are often left open or half open- This wreaks havoc in the android heap and memory management, Never forget to cursor.close()- If this is hard, then either call the manageCursor to link the cursor to the activity lifecycle or use cursor helper.
  21. 21. Use XML resources with careXML layouts are a very handy, but developers over orunder use them very often.- Handle the system services (layoutInflater)- Inflate to combine layouts, much better and easier than writing it in code.- Don’t forget to recycle the Inflated layouts !- Externalize ALL Strings to strings.xml- Use values for system configurations
  22. 22. Don’t over nest“Lazy” developers tend to overuse the LinearLayout Instead of using RelativeLayout Eclipse Demo here…
  23. 23. Cursor adapters and lists• Use relative layout for the list items• Use recyclable views and adapter• Load images in the backgroudEclipse Demo here…
  24. 24. Background and Services• Differentiate when to use binded and unbinded services.• Understand the onStartCommand() method and it’s return statement.• Differentiate threads and asynctasks• Never use Toast or Dialog from a service
  25. 25. View HierarchyDevelopers tend to create complex view hierarchieswhich are difficult for the GPU to render and refresh.Views should be simple and a better resolution is for theview hierarchy to be wide than tall.Use the HierarchyViewer tool to find the skeleton ofyour activity.
  26. 26. View Hierarchy GOOD example
  27. 27. View Hierarchy BAD example
  28. 28. THE UGLY…
  29. 29. ANR• Affected : Activity, Service, BroadcastReceiver• Reason : Lifecycle rules broken• Fix Run heavy processing outside of the main thread, use asynctask or another thread.
  30. 30. Fantom Apps The error Sample LogCat output.
  31. 31. Fantom Apps - The CauseIn general this is a very difficult error to trace- No Java StackTrace- No Error screenHowever if you look at the debug dump, you can seeThat the heap is being overflowed.To checkRuntime.getRuntime().maxMemory() – heap size
  32. 32. Fantom Apps - The SolutionVMRuntime.getRuntime().setMinimumHeapSize(BIGGER_SIZE)(how googers help them self with memory)Or:- Avoid operations that require threadpools. Control your background processes.- Try to find out if you overuse strings since + is a very heavy duty operation!- Use MemoryAnalyzer to find the “memory hoag”
  33. 33. Bitmaps and GraphicsAndroid 2.x does not work with bitmaps well• VM does not load Bitmaps in heap,• Bitmaps are immutable• Matrix transformations are EXTREMELY risky
  34. 34. Bitmaps and GraphicsRepetitive problemsERROR/AndroidRuntime(7906):java.lang.OutOfMemoryError:bitmap size exceeds VM budgetERROR/AndroidRuntime(7906)
  35. 35. Other Memory issuesThis is actually caused by unclosed cursors and huge bitmapsjava.lang.RuntimeException: No memory in memObj atandroid.database.CursorWindow.native_init atandroid.database.CursorWindow.<init> atandroid.database.CursorWindow.<init> atandroid.database.CursorWindow$1.createFromParcel atandroid.database.CursorWindow$1.createFromParcel atandroid.content.ContentProviderNative.onTransact atandroid.os.Binder.execTransact
  36. 36. The problemYou are stranded with a slow application.• Memory is failing• Application is Slow• Sometimes it fails• Sometimes it just “dissapears”
  37. 37. The tools of trade!• TraceView• Eclipse MAT• DDMS system
  38. 38. TraceView
  39. 39. Eclipse MAT
  40. 40. DDMS console
  41. 41. Threads vs. Async Tasks• Async Task Queue Limit• Thread overrun• AsyncTaskEx• NeverEnding cursors
  42. 42. Again the notifyChange() methodThis can sometimes wreak havoc.An example (that happened to me):I download news from a website, upon download I havea list of 50 items. NotifyChange() is called 50 times!Definition of an UGLY SCENARIO
  43. 43. The logging facilityAndroid Log is great, but People tend to1. Overlog2. Forget the logs3. Concatenate a huge amount of strings4. Leave logs in loops (for, while, do-while)5. Add stupid tags6. Offer the consumer private information
  44. 44. CONCLUSION…
  45. 45. It’s HardNo, It’s not!It’s fun!It’s easy! New Employee 1 yr 2 yr 3 yrIt’s lucrative It’s cool!
  46. 46. You only have to :1. Be aware of the rules of engagement!2. Know your target3. Be weary of memory!4. Remember that it’s a VM5. Have Respect for the other platforms, and you just might learn something new…