Search code examples
androidsdkcompatibility

Android: Using Target SDK?


I understand that the minimum SDK defines a minimum required OS level for your application to run and that target SDK tells the device the highest API version you used features from, assuming backwards compatibility has been implemented.

But that's what I don't understand. How do you implement backwards compatibility for entirely new API features?

For example:

I've been using the old Notification system during development of my current app, not Notification.Builder. If I choose to use Notification.Builder, will the OS or compiler automatically replace this with compatible code for platforms previous to when this was introduced? Or do I have to check the OS version and write separate code?


Solution

  • You have to account for the new methods yourself, for example by using,

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        // Use methods introduced in API 11. (i.e. Notification.Builder)
    } else {
        // Use old methods to ensure backwards compatibility.
    }
    

    A nice place to put these checks is in a utility class (i.e. CompatUtils.java). So for example, you might create a static method that takes a Context argument and returns a new Notification:

    public static buildNotification(Context ctx) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            // Create and return the Notification using Notification.Builder
        } else {
            // Create and return the Notification using pre-HoneyComb methods
        }
    }
    

    Then simply call CompatUtils.buildNotification(this) within your Activity to create the new Notification. Abstracting out these sorts of details keeps your Activity concise, and is easily changeable if you ever need to later on.

    Of course, it might be a better idea to just use the old methods to create your Notification, since you need to implement them anyway and the Notification.Builder is mostly just for convenience. Nonetheless, this is definitely something that you should keep in mind in case you run into similar issues later on!


    Edit:

    Notification.Builder is also provided in the Android Support Package, so you should just use that in this case... however, for methods that are not provided in the compatibility package, you should use the design pattern described above.