richcollins
richcollins

Reputation: 1544

Backwards Compatible Android/Java Code

I'm writing some code that is going to be used by some partners that maintain SDKs. The SDKs are used by developers on Android 1.5 through 2.3.7. My code uses features that are only available on 2.2 and later. How can I write my code so developers using the partner SDKs don't get compile errors on Android < 2.2?

I tried using reflection and avoiding imports / declarations that used classes that weren't available before 2.2, but the code didn't work post 2.2 due to failure to dispatch to methods where I had changed the desired class type to Object.

Upvotes: 4

Views: 909

Answers (1)

Philipp Reichart
Philipp Reichart

Reputation: 20961

You could try to split up the code into a baseline (Android 1.5) and provide additional JAR(s) for higher API levels, similarly to how the Android compat librabry comes in a Android 1.6-compatible "v4" flavor and a "v11" for Android 3.2 and up.

At some points, you might also be able to take code from AOSP and backport selected 2.2 features. I did this e.g. to be able to use getExternalCacheDir() on API level 7:

private static File getExternalCacheDir(final Context context) {
    // return context.getExternalCacheDir(); API level 8

    // e.g. "<sdcard>/Android/data/<package_name>/cache/"
    final File extCacheDir = new File(Environment.getExternalStorageDirectory(),
        "/Android/data/" + context.getApplicationInfo().packageName + "/cache/");
    extCacheDir.mkdirs();
    return extCacheDir;
}

Reflection-heavy code will be maintenance nightmare -- as much as you want to avoid those red compiler error dongles for your customers/partners, you want to see them instead of some obscure runtime exception caused by outdated constants in your reflection code.

Upvotes: 4

Related Questions