Backward Compatibility Android / Java Code

I am writing code that will be used by some partners who support the SDK. SDKs are used by developers on Android 1.5 to 2.3.7. My code uses features that are only available in version 2.2 and later. How can I write my code, so developers using affiliate SDKs do not get compilation errors on Android <2.2?

I tried to use reflection and avoid import / declarations that used classes that were not available before 2.2, but the code did not work after 2.2 due to the refusal to send to methods in which I changed the class type to Object.

+4
source share
1 answer

You can try to break the code down to a basic level (Android 1.5) and provide additional JARs for higher API levels, similar to how Android compat librabry comes in Android 1.6-compatible “v4” flavor and “v11” for Android 3.2 and higher.

In some cases, you can also take the code from AOSP and backport, selected in 2.2. I did it for example. to be able to use getExternalCacheDir() at API level 7:

 private static File getExternalCacheDir(final Context context) { // return context.getExternalCacheDir(); API level 8 // eg "<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 a serving nightmare - as much as you want to avoid red compiler errors for your clients / partners, you want to see them instead of some obscure runtime exception caused by outdated constants in your reflection code.

+4
source

All Articles