We use essential cookies for the website to function, as well as analytics cookies for analyzing and creating statistics of the website performance. To agree to the use of analytics cookies, click "Accept All". You can manage your preferences at any time by clicking "Cookie Settings" on the footer. More Information.

Only Essential Cookies
Accept All

Documents from this version have been archived, and will not continue to be maintained. Please use the latest version.

HMS Core GuidesLocation KitApp Development for React NativeClient Development

Development Guide

1 Location Service Development Procedure

1.1 Assigning App Permissions

The Android OS provides two location permissions: ACCESS_COARSE_LOCATION (approximate location permission) and ACCESS_FINE_LOCATION (precise location permission). You need to apply for the permissions in the Manifest file.

Collapse
Word wrap
Dark theme
Copy code
  1. <!--Fused Location-->
  2. <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
  3. <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

In Android Q, if your app needs to continuously locate the device location when it runs in the background, you need to apply for the ACCESS_BACKGROUND_LOCATION permission in the Manifest file.

Collapse
Word wrap
Dark theme
Copy code
  1. <!--Fused Location-->
  2. <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"/>

1.2 Using the Location Service Class

The name of the java class defined for Location Module is RNFusedLocationModule, and its exported name to React Native is "FusedLocation".

Collapse
Word wrap
Dark theme
Copy code
  1. import HMSLocation from 'react-native-hms-location';
  2. const FusedLocation = {
  3.    Native: HMSFusedLocation,
  4.    Data: LocationData,
  5.    Request: LocationRequest,
  6.    SettingsRequest: LocationSettingsRequest,
  7.    PriorityConstants: HMSFusedLocation.PriorityConstants,
  8.    Events: {
  9.        addFusedLocationEventListener,
  10.        removeFusedLocationEventListener,
  11.    },
  12. };

1.3 Checking the Device Location Settings

Device location settings will affect the location result of HUAWEI Location Kit. For example, if the location function is disabled on a device, the device location cannot be obtained. Therefore, you are advised to check whether the device settings meet the location requirements before continuously obtaining location information. HUAWEI Location Kit provides the capability of checking device location settings.

If the location settings do not meet the location requirements, your app can prompt users to enable related permissions. (The location permission must be enabled for HMS Core. In Android Q, Location must be set to Always for HMS Core.)

You can get the location settings with following method: checkLocationSettings( locationSettingsRequest )

The locationSettingsRequest object, which is sent as an argument, has three properties: locationRequest, alwaysShow & needBle

A locationRequest object can be created like below:

Collapse
Word wrap
Dark theme
Copy code
  1. const locationRequest = HMSLocation.FusedLocation.Request.configure({
  2.     id: 'e0048e' + Math.random() * 10000,
  3.     priority: HMSLocation.FusedLocation.PriorityConstants.PRIORITY_HIGH_ACCURACY,
  4.     interval: 3,
  5.     numUpdates: 10,
  6.     fastestInterval: 1000.0,
  7.     expirationTime: 200000.0,
  8.     expirationTimeDuration: 200000.0,
  9.     smallestDisplacement: 0.0,
  10.     maxWaitTime: 2000000.0,
  11.     needAddress: true,
  12.     language: 'en',
  13.     countryCode: 'en',
  14. }).build();

Afterwards, a locationSettingsRequest object can be crated like below:

Collapse
Word wrap
Dark theme
Copy code
  1. const locationSettingsRequest =
  2.    HMSLocation.FusedLocation.SettingsRequest.configure({
  3.        locationRequests: [locationRequest],
  4.        alwaysShow: false,
  5.        needBle: false,
  6.    }).build();

needBle property indicates whether BLE scanning needs to be enabled. The options are true (yes) and false (no).

alwaysShow property indicates whether a location is required for the app to continue. The options are true (yes) and false (no).

Finally, a call to the checkLocationSettings() method is made to retrieve the location settings. The method returns a promise which should be resolved.

Collapse
Word wrap
Dark theme
Copy code
  1. HMSLocation.FusedLocation.Native.checkLocationSettings(locationSettingsRequest)
  2.    .then(res => setLocationSettings(res))
  3.    .catch(ex => console.log("Error while getting location settings. " + ex))

1.4 Obtaining the Last Known Location

An app can use the HUAWEI Location Kit service API to obtain the last known location of a device. In most cases, the last known location is the current location of the device. The following is the sample code for calling the getLastLocation() method to obtain the last known location:

The method takes no arguments and returns a promise containing the location data, which should be resolved.

Collapse
Word wrap
Dark theme
Copy code
  1. import HMSLocation from 'react-native-hms-location';
  2. const getLocation = useCallback(() => {
  3.    HMSLocation.FusedLocation.Native.getLastLocation()
  4.         .then(pos => setPosition(pos))
  5.         .catch(err => console.log('Failed to get last location', err));
  6.    }, []);
  7. return (
  8.     <View style={styles.spaceBetweenRow}>
  9.         <Text style={styles.sectionTitle}>Location Info</Text>
  10.         <Button title="Get last location" onPress={getLocation} />
  11.     </View>
  12. );

1.5 Continuously Obtaining the Location Information

To enable your app to continuously obtain the device location, you can use the requestLocationUpdatesWithCallback(), addFusedLocationEventListener () provided by the HUAWEI Location Kit.

First, a locationRequest object should be created as in the Location Settings example. Then a call to the requestLocationUpdatesWithCallback() should be made.

This method is used to request location updates using the callback on the specified Looper thread, then returns the id for the location request made, if the request was successful.

Collapse
Word wrap
Dark theme
Copy code
  1. import HMSLocation from 'react-native-hms-location';
  2. const requestLocationUpdate = useCallback(() => {
  3.    const LocationRequest = HMSLocation.FusedLocation.Request.configure({
  4.        id: 'e0048e' + Math.random() * 10000,
  5.     /**
  6.     * other such properties
  7.     */
  8.    }).build();
  9. HMSLocation.FusedLocation.Native
  10.    .requestLocationUpdatesWithCallback(LocationRequest)
  11.        .then(({ id }) => setLocationUpdateId(id))
  12.        .catch(ex => console.log("Exception while requestLocationUpdatesWithCallback " + ex))
  13.    }, []);

Then, an event listener should be added for the periodic location updates, with a defined handler method that handles the update events.

Collapse
Word wrap
Dark theme
Copy code
  1. const handleLocationUpdate = useCallback(location => {
  2.    console.log(location);
  3.    setPosition(location);
  4. }, []);
  5. const addFusedLocationEventListener = useCallback(() => {
  6.    requestLocationUpdate();
  7.    HMSLocation.FusedLocation.Events.addFusedLocationEventListener(
  8.        handleLocationUpdate,
  9.    );
  10.    setAutoUpdateEnabled(true);
  11. }, []);
  12. const removeFusedLocationEventListener = useCallback(() => {
  13.     HMSLocation.FusedLocation.Events.removeFusedLocationEventListener(
  14.         locationUpdateId,
  15.         handleLocationUpdate,
  16.     );
  17.     setAutoUpdateEnabled(false);
  18. }, [locationUpdateId]);

1.6 Using the Mock Location

To use the mock location function, go to Settings > System & updates > Developer options > Select mock location app and select the app for using the mock location function. (If Developer options is unavailable, go to Settings > About phone and tap Build number for seven consecutive times. Then, Developer options will be displayed on System & updates.) The sample code is as follows:

Mock location feature can be enabled or disabled with the following method: setMockMode( boolean ).

This takes a boolean as argument, which indicates whether mock mode should be enabled or disabled.

The method returns a promise with the result, which should be resolved.

Collapse
Word wrap
Dark theme
Copy code
  1. import HMSLocation from 'react-native-hms-location';
  2. const [lat, setLat] = useState("41.3");
  3. const [long, setLong] = useState("29.1");
  4. const enableMockLocation = () => {  
  5.    HMSLocation.FusedLocation.Native.setMockMode(true)
  6.           .then(res => console.log('Mock mode ', res))
  7.           .catch(err => console.log(err));
  8. };
  9. return (
  10.    <View style={styles.sectionContainer}>
  11.        <Button
  12.            title="Enable"
  13.            onPress={enableMockLocation}
  14.        />
  15.    </View>
  16. );

Coordinates of the mock location can be set with the following method: setMockLocation({ latitude, longitude })

The method takes a single object as an argument, which contains the properties latitude and longitude. Then the method returns the result with a promise, which should be resolved.

Collapse
Word wrap
Dark theme
Copy code
  1. const setMockLocation = () => {
  2.    HMSLocation.FusedLocation.Native.setMockLocation(
  3.    {
  4.        latitude: parseFloat(lat),
  5.        longitude: parseFloat(long)
  6.    }
  7.    )
  8.     .then(res => { console.log('MOCK SET', res); })
  9.     .catch(err => { console.log(err); });
  10. };
  11. return (
  12.     <View style={styles.sectionContainer}>
  13.         <Button
  14.             title="Set"
  15.             onPress={setMockLocation}
  16.         />
  17.     </View>
  18. );

Once the mock location property is enabled and set, your phone should return the specified location data when trying to get last location information.

2 Activity Identification Service Development Procedure

2.1 Assigning App Permissions

To use the activity identification service in versions earlier than Android Q, you need to configure the following permissions in the Manifest file.

Collapse
Word wrap
Dark theme
Copy code
  1. <!--Activity Identification-->
  2. <uses-permission android:name="com.huawei.hms.permission.ACTIVITY_RECOGNITION" />

To use the activity identification service in Android Q and later versions, you need to configure the following permissions in the Manifest file:

Collapse
Word wrap
Dark theme
Copy code
  1. <!--Activity Identification-->
  2. <uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" />

2.2 Using the Activity Identification Class

The name of the java class defined for Location Module is RNActivityIdentificationModule, and its exported name to React Native is ActivityIdentification.

Collapse
Word wrap
Dark theme
Copy code
  1. import HMSLocation from 'react-native-hms-location';
  2. const ActivityIdentification = {
  3.    Native: HMSActivityIdentification,
  4.    ConversionInfo: ActivityConversionInfo,
  5.    ConversionData: ActivityConversionData,
  6.    ConversionRequest: ActivityConversionRequest,
  7.    ConversionResponse: ActivityConversionResponse,
  8.    IdData: ActivityIdentificationData,
  9.    IdResponse: ActivityIdentificationResponse,
  10.    Activities: HMSActivityIdentification.Activities,
  11.    ActivityConversions: HMSActivityIdentification.ActivityConversions,
  12.    Events: {
  13.        addActivityIdentificationEventListener,
  14.        removeActivityIdentificationEventListener,
  15.        addActivityConversionEventListener,
  16.        removeActivityConversionEventListener
  17.    }
  18. }

2.3 Registering Receiving of Activity Identification Updates

To use the activity identification service, you need to register receiving of activity identification updates to check the current user status, such as walking, bicycling, and motionless.

  • You can create activity identification updates with the following method: createActivityIdentificationUpdates(duration).

The method takes a single argument that indicates the interval of the updates, and returns an id created for the sent request as a promise, which then should be resolved.

Collapse
Word wrap
Dark theme
Copy code
  1. import HMSLocation from 'react-native-hms-location';
  2. const [idReqCode, setIdReqCode] = useState();
  3. const createActivityIdentification = useCallback(() => {
  4. HMSLocation.ActivityIdentification.Native
  5.    .createActivityIdentificationUpdates(2000)
  6.    .then(res => {
  7.         console.log(res);
  8.         setIdReqCode(res.requestCode);
  9.     })
  10.     .catch(err => console.log('ERROR: Activity identification failed', err));
  11. }, []);
  12. //This id later used to remove the created updates.
  13. const removeActivityIdentification = useCallback(idReqCode => {
  14.    HMSLocation.ActivityIdentification.Native
  15.        .deleteActivityIdentificationUpdates(idReqCode)
  16.        .then(res => {
  17.           console.log(res);
  18.           setIdReqCode(null);
  19.         })
  20.         .catch(err =>
  21.         console.log('ERROR: Activity identification deletion failed', err));
  22. }, []);

  • You can use the following method to listen to and receive data from activity identification events: addActivityIdentificationEventListener (handlerMethod).

The method takes a single argument, which is a handler method that is called when an activity identification event is sent.

Collapse
Word wrap
Dark theme
Copy code
  1. const [identificationSubscribed,
  2.   setIdentificationSubscribed] = useState(false);
  3. const handleActivityIdentification = useCallback(act => {
  4.   console.log('ACTIVITY : ', act);
  5.   setIdentificationResponse(act);
  6. }, []);
  7. const addActivityIdentificationEventListener = useCallback(() => {
  8.    HMSLocation.ActivityIdentification.Events
  9.   .addActivityIdentificationEventListener(
  10.        handleActivityIdentification,
  11.    );
  12.    setIdentificationSubscribed(true);
  13. }, []);

You can remove the defined listener with the following method: removeActivityIdentificationEventListener (handlerMethod)

This method takes a single argument, which is the same as the above.

Collapse
Word wrap
Dark theme
Copy code
  1. const removeActivityIdentificationEventListener = useCallback(() => {
  2.     HMSLocation.ActivityIdentification.Events
  3.     .removeActivityIdentificationEventListener(
  4.         handleActivityIdentification,
  5.     );
  6.     setIdentificationSubscribed(false);
  7. }, []);
  8. return (
  9.    <View style={styles.centralizeContent}>
  10.        <Button
  11.            title={identificationSubscribed ? "Unsubscribe" : "Subscribe"}
  12.            onPress={() => {
  13.                if (identificationSubscribed) {
  14.                    removeActivityIdentificationEventListener()
  15.                } else {
  16.                    addActivityIdentificationEventListener()
  17.                }
  18.         }} />
  19. );

2.4 Registering Receiving of Activity Conversion Updates

The function of detecting activity conversions (activity entering and exit) is provided. For example, to detect user status change from standing still to walking.

  • You can create activity conversion updates with the following method: createActivityConversionUpdates(conversionRequest)

The method takes a single argument, which is an object that indicates which type of activity and which type of conversions should be detected. You can see an example of this object below:

Collapse
Word wrap
Dark theme
Copy code
  1. const conversionRequest =
  2. HMSLocation.ActivityIdentification.ConversionRequest.configure([
  3. // STILL
  4. {
  5.    conversionType:
  6.        HMSLocation.ActivityIdentification
  7.            .ActivityConversions.ENTER_ACTIVITY_CONVERSION,
  8.        activityType:
  9.             HMSLocation.ActivityIdentification.Activities.STILL
  10. },
  11. // ON FOOT
  12. {
  13. conversionType:
  14.     HMSLocation.ActivityIdentification
  15.          .ActivityConversions.ENTER_ACTIVITY_CONVERSION,
  16.     activityType:
  17.          HMSLocation.ActivityIdentification.Activities.FOOT
  18. }
  19. ]).build();

The createActivityConversionUpdates method returns an id created for the sent request as a promise, which then should be resolved.

Collapse
Word wrap
Dark theme
Copy code
  1. const createConversionUpdates = useCallback(conversionRequest => {
  2. HMSLocation.ActivityIdentification
  3.    .Native.createActivityConversionUpdates(conversionRequest)
  4.    .then(res => {
  5.         console.log(res);
  6.         setConvReqCode(res.requestCode);
  7.    })
  8.    .catch(err =>
  9.     console.log('ERROR: Activity Conversion creation failed', err));
  10. }, []);

This id later used to remove the created conversion updates.

Collapse
Word wrap
Dark theme
Copy code
  1. const deleteConversionUpdates = useCallback(convReqCode => {
  2.    HMSLocation.ActivityIdentification
  3.       .Native.deleteActivityConversionUpdates(convReqCode)
  4.       .then(res => {
  5.            console.log(res);
  6.            setConvReqCode(null);
  7.       })
  8.   .catch(err =>
  9.    console.log('ERROR: Activity Conversion deletion failed', err));
  10. }, []);
  • You can use the following method to listen to and receive data from activity identification events: addActivityConversionEventListener (handlerMethod)

The method takes a single argument, which is a handler method that is called when an activity identification event is sent.

Collapse
Word wrap
Dark theme
Copy code
  1. const [conversionSubscribed,
  2.   setConversionSubscribed] = useState(false);
  3. const handleActivityIdentification = useCallback(act => {
  4.   console.log('ACTIVITY : ', act);
  5.   setIdentificationResponse(act);
  6. }, []);
  7. const addActivityConversionEventListener = useCallback(() => {
  8.   HMSLocation.ActivityIdentification
  9.        .Events.addActivityConversionEventListener(
  10.        handleActivityConversion,
  11.   );
  12.   setConversionSubscribed(true);
  13. }, []);

You can remove the defined listener with the following method: removeActivityConversionEventListener (handlerMethod)

This method takes a single argument, which is the same as the above.

Collapse
Word wrap
Dark theme
Copy code
  1. const removeActivityConversionEventListener = useCallback(() => {
  2.    HMSLocation.ActivityIdentification
  3.    .Events.removeActivityConversionEventListener(
  4.     handleActivityConversion,
  5.     );
  6.    setConversionSubscribed(false);
  7. }, []);
  8. return (
  9.    <View style={styles.centralizeContent}>
  10.        <Button
  11.             title={identificationSubscribed ? "Unsubscribe" : "Subscribe"}
  12.             onPress={() => {
  13.                  if (identificationSubscribed) {
  14.                      addActivityConversionEventListener()
  15.                  } else {
  16.                      addActivityIdentificationEventListener()
  17.                   }
  18.          }} />
  19.     </View>
  20. );

3 Developing the Geofence Service

3.1 Assigning App Permissions

To use the geofence service API of HUAWEI Location Kit, you need to apply for the ACCESS_FINE_LOCATION permission in the Manifest file.

Collapse
Word wrap
Dark theme
Copy code
  1. <!--Geofence-->
  2. <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

In Android Q, you need to apply for the ACCESS_BACKGROUND_LOCATION permission in the Manifest file.

Collapse
Word wrap
Dark theme
Copy code
  1. <!--Geofence-->
  2. <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"/>

3.2 Using the Geofence Service Class

The name of the java class defined for Location Module is RNGeofenceModule, and its exported name to React Native is Geofence.

Collapse
Word wrap
Dark theme
Copy code
  1. import HMSLocation from 'react-native-hms-location';
  2. const Geofence = {
  3.    Native: HMSGeofence,
  4.    Builder: GeofenceBuilder,
  5.    Data: GeofenceData,
  6.    Request: GeofenceRequest,
  7.    GeofenceRequestConstants: HMSGeofence.GeofenceRequestConstants,
  8.    GeofenceConstants: HMSGeofence.GeofenceConstants,
  9.    ErrorCodes: HMSGeofence.ErrorCodes,
  10.    Events: {
  11.        addGeofenceEventListener,
  12.        removeGeofenceEventListener
  13.    }
  14. };

3.3 Creating and Adding a Geofence

You can create a geofence instance and construct a request to add a geofence.

  • You can create a geofence list with the following method: createGeofenceList( geofences, conversions, coordinateType )

The method takes three arguments:

- Geofences: List of geofences to be added

- Conversions: Initial conversions

- Coordinate Type: Type of coordinate

You can create geofence instances through the provided builder, as shown below:

Collapse
Word wrap
Dark theme
Copy code
  1. const geofence1 = HMSLocation.Geofence.Builder.configure({
  2.    longitude: 42.0,
  3.    latitude: 29.0,
  4.    radius: 20.0,
  5.    uniqueId: 'e00322',
  6.    conversions: 1,
  7.    validContinueTime: 10000.0,
  8.    dwellDelayTime: 10,
  9.    notificationInterval: 1,
  10. }).build();

Then create a geofenceRequest object through the provided builder, as shown below:

Collapse
Word wrap
Dark theme
Copy code
  1. const geofenceRequest = HMSLocation.Geofence.Request.configure({
  2.    geofences: [geofence1, geofence2],
  3.    conversions: 1,
  4.    coordinate: 1,
  5. }).build();

Finally, a call to the createGeofenceList method is made with the created request object, the method returns an id created for the sent request as a promise, which then should be resolved.

Collapse
Word wrap
Dark theme
Copy code
  1. const createGeofenceList = useCallback(() => {
  2.    HMSLocation.Geofence.Native.createGeofenceList(
  3.        geofenceRequest.geofences,
  4.        geofenceRequest.conversions,
  5.        geofenceRequest.coordinate,
  6.    )
  7.    .then(res => {
  8.        console.log(res);
  9.        setReqCode(parseInt(res.requestCode));
  10.    })
  11.    .catch(err => {
  12.        console.log(err);
  13.    });
  14. })

This id later used to remove the created conversion updates.

Collapse
Word wrap
Dark theme
Copy code
  1. const deleteGeofenceList = useCallback(reqCode => {
  2. HMSLocation.Geofence.Native.deleteGeofenceList(reqCode)
  3.   .then(res => {
  4.     console.log(res);
  5.     setReqCode(null);
  6.   })
  7.   .catch(err => console.log('ERROR: GeofenceList deletion failed', err))
  8. }, []);
  • You can use the following method to listen to and receive data from activity geofence events: addGeofenceEventListener ( handlerMethod )

The method takes a single argument, which is a handler method that is called when a geofence event is sent.

Collapse
Word wrap
Dark theme
Copy code
  1. import HMSLocation from 'react-native-hms-location';
  2. const [geoSubscribed, setGeoSubscribed] = useState(false);
  3. const handleGeofenceEvent = useCallback(geo => {
  4.    console.log('GEOFENCE : ', geo);
  5.    setGeofenceResponse(geo);
  6. });
  7. const addGeofenceEventListener = useCallback(() => {
  8.    HMSLocation.Geofence.Events.addGeofenceEventListener(
  9.    handleGeofenceEvent,
  10.    );
  11.    setGeoSubscribed(true);
  12. }, []);

You can remove the defined listener with the following method: removeGeofenceEventListener ( handlerMethod )

This method takes a single argument, which is the same as the above example.

Collapse
Word wrap
Dark theme
Copy code
  1. const removeGeofenceEventListener = useCallback(() => {
  2.    HMSLocation.Geofence.Events.removeGeofenceEventListener(
  3.    handleGeofenceEvent,
  4.    )
  5.    setGeoSubscribed(false);
  6. })
  7. return (
  8.    <View style={styles.centralizeContent}>
  9.       <Button
  10.           title={geoSubscribed ? "Unsubscribe" : "Subscribe"}
  11.           onPress={() => {
  12.               if (geoSubscribed) {
  13.                   removeGeofenceEventListener()
  14.               } else {
  15.                   addGeofenceEventListener()
  16.               }
  17.       }} />
  18.    </View>
  19. );


This page may contain third-party content. For details, click here.