Huawei Developers
Published in

Huawei Developers

Enable Mock Location with HMS Location Kit in Xamarin.Android

Part 1 of this series we have got the last location from the user, and in Part 2, we requested locations from users periodically. Also in that part, you can find the configuration settings we need to do before moving on the development. Required permissions are set in that part also.

In this part, we are going to see how to use a fake location with HMS Location Kit’s Mock Mode functionality.

Mock locations allow us to create specific mock data, instead of trying to approximate data by moving an actual device. HMS Location Kit provides us this functionality that we can easily use in our applications.

Before using the mock location function, we need to enable the mock location app in Settings > System & Updates > Developer options > Select mock location app.

Create a new activity named MockLocationActivity and enable mock mode with switch and setting mock location with the button.

First, we create FusedLocationProviderClient for using mock mode function and assign the switch’s CheckedChange and button’s Click events in OnCreate method.

In switch’s CheckedChange event we will try to enable mock mode.

fusedLocationProviderClient.SetMockMode(isSelected) returns Task, so we need to attach a SuccessListener called when Task completes successfully and a FailureListener called when Task fails.

If Task failed and mock mode cannot be enabled, we will display a suitable message to the user about the error and set switch state to false. We can set the message by checking the ErrorCode in the ex parameter.

This means that we need to set the mock location app in the developer options.

And if Task completed successfully and mock mode enabled, we can set the mock location now.

Now let’s complete the Set Mock Location button’s Click event:

Enter the Latitude and Longitude values in the fields and click Set Mock Location Button:

After re-launch the application we will see that the mock location we just set is returning in our application location requests:

You can download the source code from here. Also if you have any questions, ask away in Huawei Developer Forums.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store