setForeground() missing in Android 3.0 services

While upgrading my application’s code to use the Android 3.0 SDK, I stumbled upon a small problem in my service code: the setForeground() function has been removed from Android 3.0 completely, making the compilation process fail. The function removal broke the compatibility methods I had copied straight from the Android documentation ages ago for backwards compatibility:

Note: The methods startForeground() and stopForeground() were introduced in Android 2.0 (API Level 5). In order to run your service in the foreground on older versions of the platform, you must use the previous setForeground() method—see the startForeground() documentation for information about how to provide backward compatibility.

(So in other words, if the user’s device has Android 2.x, the startForeground() function must be called. If the user’s device has 1.x, setForeground() should be called instead. setForeground() will not work on Android 2.x, and vice-versa).

Fortunately, this was an easy fix – the documentation has been updated with a new, more future-proof code sample for calling the right functions depending on the device’s Android version. In my case I had modified the old sample code to my liking, so I decided to add a small function to my service that will call the setForeground() method through reflection instead:

Problem solved!

One Response to “setForeground() missing in Android 3.0 services”

  1. Wow, this is annoying. Does the documentation provide justification as to why they just decide to remove part of their API? I could understand had these methods been hidden, but if you provide a method as part of an API you really should not just remove it unless it is absolutely necessary. Thanks for the heads up!

Leave a Reply