Yes you can do it. There are actually more than one way. (Note: the only specific part of this answer for Android is how you find out the version of the platform.)
Suppose class X has the void y() method in version 2.0, but not before.
One way to call this method without introducing any compile-time dependencies is to use reflection to find the method and invoke on it. For example:
X x = ... if (BUILD.VERSION.RELEASE.compareTo("2.0") >= 0) { // (exception handling omitted ...) Method m = c.getClass().getDeclaredMethod("y"); m.invoke(x); }
Another way is to create the version compatibility adapter API for your application as follows:
interface Compat { void doY(); } class CompatV1 { public void y(X x) {
The second version looks a little heavyweight, but it has the advantage that the dynamic (slow, insecure) code is executed only once and that the specific version code is isolated from the rest of the code. In real life, you would probably put a number of methods in the adapter interface.
This approach requires a bit more understanding in order to develop how to develop a compatibility API so that it completely isolates version dependencies from the rest of the code. You may also need to revise the adapter API and create new adapter classes for each new (incompatible) major version.
Finally, if the platform API changes, you need to adapt to using classes or methods in the old version that are removed in the newer version, then you will need to compile various adapter classes (for example, CompatV* classes) using different Android SDKs. This will make your build processes more complex.
For others, βtakeβ this problem, read the following Android blog articles:
Stephen c
source share