Summary of Chapter 9. Platform-specific API calls
It is sometimes necessary to run some code that varies by platform. This chapter explores the techniques.
Preprocessing in the Shared Asset Project
A Xamarin.Forms Shared Asset Project can execute different code for each platform using the C# preprocessor directives
endif. This is demonstrated in PlatInfoSap1:
However, the resultant code can be ugly and difficult to read.
Parallel classes in the Shared Asset Project
A more structured approach to executing platform-specific code in the SAP is demonstrated in the PlatInfoSap2 sample. Each of the platform projects contains an identically named class and methods, but implemented for that particular platform. The SAP then simply instantiates the class and calls the method.
DependencyService and the Portable Class Library
A library cannot normally access classes in application projects. This restriction seems to prevent the technique shown in PlatInfoSap2 from being used in a PCL. However, Xamarin.Forms contains a class named
DependencyService that uses .NET reflection to access public classes in the application project from the PCL.
The PCL must define an
interface with the members it needs to use in each platform. Then, each of the platforms contains an implementation of that interface. The class that implements the interface must be identified with a DependencyAttribute on the assembly level.
The PCL then uses the generic
Get method of
DependencyService to obtain an instance of the platform class that implements the interface.
This is demonstrated in the DisplayPlatformInfo sample.
Platform-specific sound generation
The MonkeyTapWithSound sample adds beeps to the MonkeyTap program by accessing sound-generation facilities in each platform.