Search code examples
javaandroidbackwards-compatibility

Backwards compatibility and methods in Android


I'm currently updating a library I maintain and I want to offer a method that uses MediaDataSource in the method signature, however this is only available in API 23+. I know the Android documentation states that you should ensure backwards compatibility via checks such as:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
    // some API specific code

I also know resources can be customized backed on the folder naming, for example layout-v13. My question is, is it possible to add a check of this sort or something similar such that my code will still work on < API 23. Does Android offer a construct like:

@Version Build.VERSION_CODES.HONEYCOMB // not real code, just what I'm thinking
public void setData(MediaDataSource mediaDataSource) {
    // some code
}

Solution

  • Yes, usually when you run into API compat issues Android Studio gives you a variety of solutions when you press alt+enter on the warning.

    Take the example of NotificationChannel in Android that are only available to Oreo users (API 26). You have the following to target them.

    Option 1: If else statement You have already mentioned this in your question

    Option 2: @TargetAPI Annotation

    @TargetApi(Build.VERSION_CODES.O)
    private void createNotification() {
    NotificationChannel notificationChannel = new NotificationChannel("123", "newNotification", NotificationManager.IMPORTANCE_DEFAULT);}
    

    Option 3: @RequiresAPI Annotation

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void createNotification() {
    NotificationChannel notificationChannel = new NotificationChannel("123", "newNotification", NotificationManager.IMPORTANCE_DEFAULT);
    }