Home » Android » c# – Detect API level incompatibilities in Xamarin Android App (Visual Studio 2015) at compile time instead of runtime

c# – Detect API level incompatibilities in Xamarin Android App (Visual Studio 2015) at compile time instead of runtime

Posted by: admin May 14, 2020 Leave a comment

Questions:

I am writing a Xamarin Android app using Visual Studio 2015 (Windows). I want to target the latest Android API, while maintaining backwards compatibility to API 16 (4.1 Jelly Bean).

I know how to ensure there is no run-time error thrown via an API level check:

if(Android.OS.Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
{
    //Call API supported by Lollipop and above, but not by lower API's
}
else
{
   //Alternative code for graceful backwards compatibility
}

Unfortunately, if I don’t have this check, Visual Studio still happily compiles and runs my code – and if the API is not supported, I get a run-time Java.Lang.NoSuchMethodError exception. I can manually reset the project to a lower level API to catch the errors compile-time, but this is a bit cumbersome – it would be great to catch these errors (even as warnings) at compile-time, without manually resetting to each lower API I’d like to support.

How can I detect an incompatible API call at compile time?

NOTE: I did find a similar question on StackOverflow, but it specifically addresses Xamarin Studio for Mac – which suggests this should be possible to do in Visual Studio 2015 for Windows (2017 solution ok too).

How to&Answers: