What is the purpose of the condition "if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {" in the Firebase Cloud Messaging sample project?

Jaime Montoya picture Jaime Montoya · Nov 24, 2017 · Viewed 14.6k times · Source

I am implementing the Firebase Cloud Messaging Quickstart sample project available at https://github.com/firebase/quickstart-android/tree/master/messaging, incorporating it to my app. In https://github.com/firebase/quickstart-android/blob/master/messaging/app/src/main/java/com/google/firebase/quickstart/fcm/MainActivity.java I can see the following block of code:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    // Create channel to show notifications.
    String channelId  = getString(R.string.default_notification_channel_id);
    String channelName = getString(R.string.default_notification_channel_name);
    NotificationManager notificationManager =
            getSystemService(NotificationManager.class);
    notificationManager.createNotificationChannel(new NotificationChannel(channelId,
            channelName, NotificationManager.IMPORTANCE_LOW));
}

What is the purpose of using the condition if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){}? From what I understand, Build.VERSION.SDK_INT returns the API Level of the device where the app is installed, and Build.VERSION_CODES.O is what I define as the API level to compile against in the app/build.gradle file, for example: compileSdkVersion 26. Is the code asking to not execute the code that creates the channel to show notifications, if the user has a device with an API level that is lower than the compileSdkVersion that I am using to define which SDK version I am compiling against? I am not understanding the purpose of that condition. By the way, I am testing with a phone whose API Level is 23 and expected, since I am using compileSdkVersion 26 in my build.gradle file, the entire block of code is not being executed. I will appreciate if you could help to clarify the purpose of this code, and of course it is not code that I wrote. I took it from https://github.com/firebase/quickstart-android/blob/master/messaging/app/src/main/java/com/google/firebase/quickstart/fcm/MainActivity.java, but I am trying to understand it. Thank you.

Answer

Dror picture Dror · Jul 17, 2018

Build.VERSION.SDK_INT:

The SDK version of the software currently running on this hardware device. 

in other words - this is the Android version of the device running the app.

Build.VERSION_CODES.O - is a reference to API level 26 (Android Oreo which is Android 8) https://developer.android.com/reference/android/os/Build.VERSION_CODES

if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) is TRUE - means the device running the app has Android SDK 26 or up - and the Block of code inside you "if" statement will be executed.

otherwise- the SDK version is lower than 26. (SDK 25 or lower)

What is the purpose of using the condition

this was answered by @CommonsWare