Clay Allsopp

Android Best Practices and Tips

Jun 22, 2012

I may have cut my teeth on iOS, but I have a soft spot for Android.

On one hand, it's much easier to create fluid, scalable layouts using their XML system. And thankfully, independent Activities make it difficult to write the spaghetti code you might find in poorer iOS apps (self.navigationController.viewControllers[2] anyone?).

But then again, it's Java (ProblemFactory anyone?), and Google keeps changing their minds about what good apps should look like (see: 4.0 being a total rewrite of their interface guidelines).

I've worked on some really beautiful Android apps (Circle), so I thought I'd share some knowledge I've picked up along the way:

  • Use RoboGuice, Google's port of Guice to Android. Takes out a LOT of glue code with both plain-Java dependency injection and really awesome view injections (see this).
  • Learn the Activity lifecycle. Remember to zero any dangling references at the correct times so leaks don't occur (so your on[Create/Start/Resume] should basically mirror your on[Destroy/Stop/Pause]).
  • Speaking of Activities, be wary of controllers/activities getting thick. On mobile there's a temptation to do a lot of animation or layout logic in the controllers. Create tertiary objects ("presenters") which handle animations + UI-only logic, which the activities call when necessary.
  • Design your views so they flow and expand to multiple sizes/orientations. Don't make them absolutely positioned or sized, so use dips for your measurements and align views relatively.
  • Learn and use Fragments now. They're relatively new in Android-land, available on phones only since 4.0, but Google is deprecating many older APIs in favor of new Fragment-based ones. They're sort of like embeddable Activities, which means you can take one Fragment you used as an entire Activity on a phone and use it as a component of a larger interface on a tablet. Kind of neat, right?
  • In general, practice good MVC. Activities should just take data from the models and insert them into the views, or take events from a view and tell the data to do something. Don't run URL requests or other raw data fetches in controllers.
  • Learn the Activity lifecycle. Intentional repetition.

Do those and you're on your way to having a solid Android app.

This was originally an answer to a Quora question