In this post we shall discuss some of the best practices for Android engineers while developing any feature for an android app.

Main thread safe

By default an Android app runs on a single thread called Main thread. Try to make your feature main thread safe. Shift your long and complex operations from main thread to a background thread. Otherwise they are going to be the reasons why your app is laggy. ANRs is one the end results of such operations.

Decouple UI and business logic

An activity can go through various lifecycle states through implicit actions like phone call, low battery or explicit actions like pressing home button or switching between apps. Hence the Android system can destroy your activity at anytime. Our business logic should be least dependent on UI. Querying network or database, manipulating data shouldn’t rely on UI such as activity context. This is the most common mistake for crashes.

Don’t store activity context

As explained in the previous section, the activity can be destroyed at anytime. We shouldn’t rely on saved contexts anywhere in the app. Rather we should have a robust system incorporating lifecycle states of UI elements mainly activity and fragments. Storing of contexts is also called memory leaks.

Don’t store data in UI elements

As explained earlier, the UI is not a reliable place to store data. Don’t rely on the text of UI elements like TextViews or Buttons. Instead have a UI state class which listens to changes from data layer (Network or Database) and updates the UI accordingly. This is also the single source of truth principle.

Persist network data for low bandwidth users

Make your app work in low network bandwidth. Try to store network data locally in your app and have a refresh window around it, if the same request comes within this window, resend the data.

Write Clean Code

This is one of the fundamentals for a professional software engineer. Always try to improve your code readability. Make it as easy like someone is reading a book. I suggest reading Clean code by Robert C. Martin.

These are the principles that I follow and learned through various projects.

By Vivek

Leave a Reply

Your email address will not be published. Required fields are marked *