It’s all about maintenance

Programming is like sex: one mistake and you have to support it for the rest of your life.

— Michael Sinz

How would I guess, back when writing the first version of I’m sleeping,  that I would constantly need to come back to it with each release of a major Android version?

Even though Android has a mechanism which is supposed to eliminate such kind of burden, it wouldn’t work in this particular app’s case.

The purpose of the app is simple: wake at a precise time, twice per day to set or unset the volume of the phone’s ringer.

Easy enough! Simply use the framework’s AlarmManager:

alarmManager.set()

No, wait! Starting from Android KitKat (4.4), set() doesn’t guarantee precise timing anymore because of battery saving reasons. One has to use a new call:

alarmManager.setExact()

No, wait! In Android Marshmallow (6.0), setExact() doesn’t work when the device is in idle mode (ie. left alone on a table without moving), which means you’ll miss alarms. One has to use another new call:

alarmManager.setExactAndAllowWhileIdle()

The annoying thing is that each of these API changes would simply break my app if I wasn’t closely monitoring the framework’s evolution. I really hope there’s won’t be a setExactAndAllowWhileIdleAndDeepFreeze() or so call in a future revision of the framework.

This is a good example of why perfectly working and stable code still needs to be maintained because of all the changes around it (OS, drivers and libraries).

Update:

They did it again! From Android 12+, the following permission is required:

SCHEDULE_EXACT_ALARM

Enough is enough. I give up.

Using the proper data type

How to represent datatypes? For example in a JSON output.

Dates

Don’t do things like:

2014-01-17T18:01:30+01:00

Seriously. Do you have any idea how difficult and computationally intensive this is to parse? And I’m not even talking about the variants with timezones like GMT, PST, Z, +- offsets and so on.

Instead, do the following:

1389978090000

This is the number of milliseconds since the beginning of times, that is 1st January 1970 with an UTC time zone. It’s easy to parse and there’s no room for interpretation. Every library understands that format.

Durations

Don’t do

3111.44

This uses floats. Not only it can give rounding errors but it’s slower than integers. Instead do:

3111044

which is the number of milliseconds. Again easy to parse and every timer related library understands integer milliseconds, not necessarily floats.

Keep it simple and efficient.