compileSdkVersion : compileSdkVersion defines which Android SDK version will be used by gradle to compile your app.
For example:
In Android 12, so in SDK version 31, new splash screen API was introduced, that allows us to easily implement a splash screen.
If you want to use that API in your app you have to update compileSdkVersion to 31 in your app.
Only then you can use this new splash screen API in your code otherwise you will get a compilation error.
That doesn’t of course mean that you can use only this new API and forget about users who have older Android versions where this API is not available.
You have to also provide an alternative way to display a splash screen for older devices by using version check condition.
*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
// New Splash screen API
} else {
// Old splash screen approach
}*
Similarly, some methods or properties could be deprecated in this Android SDK version, and some of them even removed.
That's why once you update the compiledSdkVersion in your app, you will often see some warnings and errors during compilation.
But changing the compileSdkVersion alone does not actually change the behaviour of the app when running on android device.
So how does the Android system know if it can use new functionalities with your app or not? That’s where targetSdkVersion comes into play.
targetSdkVersion : targetSdkVersion tells the system for which Android version the app was designed and tested on.
For example:
In Android 12 the appearance of custom notifications was changed.
If your targetSdkVersion is below 31 system will assume that you haven’t tested that feature
and will display notifications in the old way to minimize the risk that notification will not be displayed properly.
Only after you update the target SDK version to 31 the new notification appearance will be used.
Not all changes that are introduced in new Android versions are targeted and use these backwards-compatibility mechanisms.
For each Android version release, in documentation, you can see that changes are split into two groups:
-> behavioral changes for apps targeting specific Android versions
-> and changes for all apps, no matter which targetSdkVersion they define.
An example of the latter may be the introduction of one time permissions in Android 11.
When the device uses Android version 11 or higher and the app asks for location permission,
the user can grant temporary access to that data and the app has to handle that case properly no matter if it targets SDK version 30 or not.
Relationship between compile and target SDK versions:
-> targetSdkVersion cannot be higher than the compileSdkVersion simply because we cannot target things that we know nothing about during compilation.
-> Ideally, the compileSdkVersion and targetSdkVersion should be equal and both point to the latest SDK.