So you want to write an app that works even for Android 1.6 to so you target it for api-level 4. Then you start realizing that there are a handful of nice stuff, that while not being crucial for the application, still would be nice to be able to use.
But wait, what if you target your app for a newer api...
...and set minSDK to a lower api in your manifest?
<uses-sdk android:minSdkVersion="4" />
Then you could add checks to make sure you only use the new stuff where it is supported...
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
preference.setIcon(icon);
Well, that is what I thought would be enough but it turned out it would force close before it even reached that part of the code. In fact it crashes when it loads your class. After some searching on the net I found a solution that take advantage of something called "Lazy loading".
What it means is that if you put the high-api specific code in a separate class it will not be loaded unless that part of the code is reached and it will no longer force close on low-api devices.
So we change the example above to:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
LazySetIcon.seticon(preference, icon);
LazySetIcon.seticon(preference, icon);
Then we create the class LazySetIcon.java which looks like this:
package com.example.app;
import android.preference.Preference;
public class LazySetIcon {
import android.preference.Preference;
public class LazySetIcon {
public static void seticon(Preference preference, int icon) {
preference.setIcon(icon);
}
}
And that's it. Write an app for a low-api devices but use high-api goodies on newer devices, when possible. A little bit more work but if the high-api code you use is limited to simple things like setting a preference icon like in the example above then it will probably be worth it.
No comments:
Post a Comment