Friday, May 4, 2012

How to write cross-API apps

If you are developing an Android application you probably want to make it available to as many devices as possible. However doing that forces you to target your app for an old api-level, sacrificing all the new stuff that has been since that api-level.

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...


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:
    LazySetIcon.seticon(preference, icon);

Then we create the class which looks like this:


import android.preference.Preference;

public class LazySetIcon { 
    public static void seticon(Preference preference, int 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