Sharing the Code

Programming stuff that might be useful to others

Android – backward compatibility

As a web developer I’m used to getting stuff to work on a number of different browsers. With the web and mobile phones, software has become available to a far wider audience so I think one should take advantage of that strength. With both the iPhone and Android version of my mobile app I targeted the current OS version but implemented it so it would degrade gracefully for previous versions of the OS. In the Android version I set the minimum Android version to 1.6 because that is the minimum requirement for in-app purchases.

When creating an Android project you set the build target to the current OS version or the one you have installed on your development phone.

And then in your manifest file set the minimum version you support:
[sourcecode language=”xml”]



[/sourcecode]

Each Android version has a corresponding integer version number, so 4 corresponds to 1.6 above. You can see a list of them here.

When accessing the API docs set the filter level (top right-hand corner) to the minimum SDK version you have decided apon. This will ensure you don’t include classes or methods that are not supported on earlier devices.

To include methods that are not supported by the minimum SDK version you use reflection to dynamically get the method at runtime:

[sourcecode language=”java”]
public class CameraActivity extends Activity {
private static Method sSetDisplayOrientation=null;

static {
initCompatibility();
}

public void surfaceCreated(SurfaceHolder holder) {

setDisplayOrientation(mCamera, cameraRotation);

}

private void setDisplayOrientation(Camera camera, int rotation){
if (sSetDisplayOrientation!=null){
try {
sSetDisplayOrientation.invoke(camera, rotation);
} catch (Exception ignored){}
}
}

private static void initCompatibility() {
try {
sSetDisplayOrientation=Camera.class.getMethod(“setDisplayOrientation”, int.class);
} catch (NoSuchMethodException ignored) {}
}
}
[/sourcecode]

Comments are closed