Java

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!

Comment icon 1 Comment »