[Kotlin] Using SDK_INT or targetSDK as the if-condition ?

kokchai
1 min readMay 9, 2020

Look at build.gradle:

android {
defaultConfig {
minSdkVersion 21
targetSdkVersion 29
}
}

There are few constants we can use:

Build.VERSION.SDK_INT
The Android version of the device
Context.packageManager.getApplicationInfo(Context.packageName, 0).targetSdkVersion
The target of Android version

What should we concern here ?

Let’s look at the code below:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
// We do something here if the Android version of the device is equals to or greater than Android Q
// We are not sure what's the behaviour of R,S,T,....

}
val targetVersion = packageManager.getApplicationInfo(packageName, 0).targetSdkVersionif (Build.VERSION.SDK_INT <= targetVersion) {
// We Only do something here we tested even if the Android version of the device is greater than the target version
}

One more point,

val IS_GREATER_OR_EQUALS_TO_ANDROID_Q: Boolean by lazy {
// return a Boolean to determine whether the current version of the device is equals to or greater than Android Q
}

Using lazy to ensure this logic is executed for once.

Used in:

--

--