Calling native Android APIs

Calling into the Android OS to utilize an API can be done in one of two ways. If you simply need to call an API that does not directly involve any parts of the Xojo framework, you can make a direct API call. If instead your API call will be interacting with a Xojo framework object, then it's best to create the declare as part of an extension method for the Xojo framework class with which you intend to use it.

Direct API Call

Calling an Android OS API directly via a declare is no different than it would be for other operating systems.

For example, if to get the version number of Android upon which the app is running, the Android Developer documentation for the Build object indicates that it is located in the android.os library. The Release property holds the user-visible string and is accessed via the Alias section. Because Release is a string, the return value must be defined in the declare as a CString.

Declare Function AndroidVersion Lib "android.os.Build.VERSION" Alias "RELEASE" As CString

An example project that uses this declare is available at Platform > Android > Declare > Declare project.

Using Xojo Framework Classes

For Android, Xojo supports a special new declare format that allows making calls directly against certain objects and controls. This is useful when creating a Declare to change the property of a control. As an example, let's set the background color of a MobileButton.

The typical way to use this new type of Object Declare is by adding an Extends method to a Xojo Module in your project. To extend the MobileButton class with the ability to change its color, add a method called SetBackgroundColor with the following parameters: Extends ctrl As MobileButton, c As Color to a Xojo Module in your project.

In the Android developer documentation you will see that a Button is considered a View and thus has a setBackgroundColor method.

An Alias is not needed in this case since the extension method is what will be called in Xojo code. What you will do instead is make the Declare like this:

Declare Sub setBackgroundColor Lib "Object:ctrl:MobileButton" (myColor As Integer)

Breaking this down, it is calling the setBackgroundColor function. The Lib denotes this new type of Object declare: an Object, separated by a colon, the Xojo name of the object (in this case, the ctrl parameter from the extension method signature), followed by another colon, followed by the parameter's Xojo framework class name.

The next and final line of the extension method will call the declared function:

setBackgroundColor(c.ToInteger)

You can see this declare and its helper method in action from the Examples section of Xojo in the Platforms > Android > Declare > ButtonBackgroundColor project.