Intelligent Assistant
Chat with our virtual assistant to get answers promptly.
Documents from this version have been archived, and will not continue to be maintained. Please use the latest version.
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.
- <!--Fused Location-->
- <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
- <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.
- <!--Fused Location-->
- <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"/>
The name of the java class defined for Location Module is RNFusedLocationModule, and its exported name to React Native is "FusedLocation".
- import HMSLocation from 'react-native-hms-location';
- const FusedLocation = {
- Native: HMSFusedLocation,
- Data: LocationData,
- Request: LocationRequest,
- SettingsRequest: LocationSettingsRequest,
- PriorityConstants: HMSFusedLocation.PriorityConstants,
- Events: {
- addFusedLocationEventListener,
- removeFusedLocationEventListener,
- },
- };
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:
- const locationRequest = HMSLocation.FusedLocation.Request.configure({
- id: 'e0048e' + Math.random() * 10000,
- priority: HMSLocation.FusedLocation.PriorityConstants.PRIORITY_HIGH_ACCURACY,
- interval: 3,
- numUpdates: 10,
- fastestInterval: 1000.0,
- expirationTime: 200000.0,
- expirationTimeDuration: 200000.0,
- smallestDisplacement: 0.0,
- maxWaitTime: 2000000.0,
- needAddress: true,
- language: 'en',
- countryCode: 'en',
- }).build();
Afterwards, a locationSettingsRequest object can be crated like below:
- const locationSettingsRequest =
- HMSLocation.FusedLocation.SettingsRequest.configure({
- locationRequests: [locationRequest],
- alwaysShow: false,
- needBle: false,
- }).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.
- HMSLocation.FusedLocation.Native.checkLocationSettings(locationSettingsRequest)
- .then(res => setLocationSettings(res))
- .catch(ex => console.log("Error while getting location settings. " + ex))
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.
- import HMSLocation from 'react-native-hms-location';
- const getLocation = useCallback(() => {
- HMSLocation.FusedLocation.Native.getLastLocation()
- .then(pos => setPosition(pos))
- .catch(err => console.log('Failed to get last location', err));
- }, []);
- return (
- <View style={styles.spaceBetweenRow}>
- <Text style={styles.sectionTitle}>Location Info</Text>
- <Button title="Get last location" onPress={getLocation} />
- </View>
- );
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.
- import HMSLocation from 'react-native-hms-location';
- const requestLocationUpdate = useCallback(() => {
- const LocationRequest = HMSLocation.FusedLocation.Request.configure({
- id: 'e0048e' + Math.random() * 10000,
- /**
- * other such properties
- */
- }).build();
- HMSLocation.FusedLocation.Native
- .requestLocationUpdatesWithCallback(LocationRequest)
- .then(({ id }) => setLocationUpdateId(id))
- .catch(ex => console.log("Exception while requestLocationUpdatesWithCallback " + ex))
- }, []);
Then, an event listener should be added for the periodic location updates, with a defined handler method that handles the update events.
- const handleLocationUpdate = useCallback(location => {
- console.log(location);
- setPosition(location);
- }, []);
- const addFusedLocationEventListener = useCallback(() => {
- requestLocationUpdate();
- HMSLocation.FusedLocation.Events.addFusedLocationEventListener(
- handleLocationUpdate,
- );
- setAutoUpdateEnabled(true);
- }, []);
- const removeFusedLocationEventListener = useCallback(() => {
- HMSLocation.FusedLocation.Events.removeFusedLocationEventListener(
- locationUpdateId,
- handleLocationUpdate,
- );
- setAutoUpdateEnabled(false);
- }, [locationUpdateId]);
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.
- import HMSLocation from 'react-native-hms-location';
- const [lat, setLat] = useState("41.3");
- const [long, setLong] = useState("29.1");
- const enableMockLocation = () => {
- HMSLocation.FusedLocation.Native.setMockMode(true)
- .then(res => console.log('Mock mode ', res))
- .catch(err => console.log(err));
- };
- return (
- <View style={styles.sectionContainer}>
- <Button
- title="Enable"
- onPress={enableMockLocation}
- />
- </View>
- );
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.
- const setMockLocation = () => {
- HMSLocation.FusedLocation.Native.setMockLocation(
- {
- latitude: parseFloat(lat),
- longitude: parseFloat(long)
- }
- )
- .then(res => { console.log('MOCK SET', res); })
- .catch(err => { console.log(err); });
- };
- return (
- <View style={styles.sectionContainer}>
- <Button
- title="Set"
- onPress={setMockLocation}
- />
- </View>
- );
Once the mock location property is enabled and set, your phone should return the specified location data when trying to get last location information.
To use the activity identification service in versions earlier than Android Q, you need to configure the following permissions in the Manifest file.
- <!--Activity Identification-->
- <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:
- <!--Activity Identification-->
- <uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" />
The name of the java class defined for Location Module is RNActivityIdentificationModule, and its exported name to React Native is ActivityIdentification.
- import HMSLocation from 'react-native-hms-location';
- const ActivityIdentification = {
- Native: HMSActivityIdentification,
- ConversionInfo: ActivityConversionInfo,
- ConversionData: ActivityConversionData,
- ConversionRequest: ActivityConversionRequest,
- ConversionResponse: ActivityConversionResponse,
- IdData: ActivityIdentificationData,
- IdResponse: ActivityIdentificationResponse,
- Activities: HMSActivityIdentification.Activities,
- ActivityConversions: HMSActivityIdentification.ActivityConversions,
- Events: {
- addActivityIdentificationEventListener,
- removeActivityIdentificationEventListener,
- addActivityConversionEventListener,
- removeActivityConversionEventListener
- }
- }
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.
- import HMSLocation from 'react-native-hms-location';
- const [idReqCode, setIdReqCode] = useState();
- const createActivityIdentification = useCallback(() => {
- HMSLocation.ActivityIdentification.Native
- .createActivityIdentificationUpdates(2000)
- .then(res => {
- console.log(res);
- setIdReqCode(res.requestCode);
- })
- .catch(err => console.log('ERROR: Activity identification failed', err));
- }, []);
- //This id later used to remove the created updates.
- const removeActivityIdentification = useCallback(idReqCode => {
- HMSLocation.ActivityIdentification.Native
- .deleteActivityIdentificationUpdates(idReqCode)
- .then(res => {
- console.log(res);
- setIdReqCode(null);
- })
- .catch(err =>
- console.log('ERROR: Activity identification deletion failed', err));
- }, []);
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.
- const [identificationSubscribed,
- setIdentificationSubscribed] = useState(false);
- const handleActivityIdentification = useCallback(act => {
- console.log('ACTIVITY : ', act);
- setIdentificationResponse(act);
- }, []);
- const addActivityIdentificationEventListener = useCallback(() => {
- HMSLocation.ActivityIdentification.Events
- .addActivityIdentificationEventListener(
- handleActivityIdentification,
- );
- setIdentificationSubscribed(true);
- }, []);
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.
- const removeActivityIdentificationEventListener = useCallback(() => {
- HMSLocation.ActivityIdentification.Events
- .removeActivityIdentificationEventListener(
- handleActivityIdentification,
- );
- setIdentificationSubscribed(false);
- }, []);
- return (
- <View style={styles.centralizeContent}>
- <Button
- title={identificationSubscribed ? "Unsubscribe" : "Subscribe"}
- onPress={() => {
- if (identificationSubscribed) {
- removeActivityIdentificationEventListener()
- } else {
- addActivityIdentificationEventListener()
- }
- }} />
- );
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:
- const conversionRequest =
- HMSLocation.ActivityIdentification.ConversionRequest.configure([
- // STILL
- {
- conversionType:
- HMSLocation.ActivityIdentification
- .ActivityConversions.ENTER_ACTIVITY_CONVERSION,
- activityType:
- HMSLocation.ActivityIdentification.Activities.STILL
- },
- // ON FOOT
- {
- conversionType:
- HMSLocation.ActivityIdentification
- .ActivityConversions.ENTER_ACTIVITY_CONVERSION,
- activityType:
- HMSLocation.ActivityIdentification.Activities.FOOT
- }
- ]).build();
The createActivityConversionUpdates method returns an id created for the sent request as a promise, which then should be resolved.
- const createConversionUpdates = useCallback(conversionRequest => {
- HMSLocation.ActivityIdentification
- .Native.createActivityConversionUpdates(conversionRequest)
- .then(res => {
- console.log(res);
- setConvReqCode(res.requestCode);
- })
- .catch(err =>
- console.log('ERROR: Activity Conversion creation failed', err));
- }, []);
This id later used to remove the created conversion updates.
- const deleteConversionUpdates = useCallback(convReqCode => {
- HMSLocation.ActivityIdentification
- .Native.deleteActivityConversionUpdates(convReqCode)
- .then(res => {
- console.log(res);
- setConvReqCode(null);
- })
- .catch(err =>
- console.log('ERROR: Activity Conversion deletion failed', err));
- }, []);
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.
- const [conversionSubscribed,
- setConversionSubscribed] = useState(false);
- const handleActivityIdentification = useCallback(act => {
- console.log('ACTIVITY : ', act);
- setIdentificationResponse(act);
- }, []);
- const addActivityConversionEventListener = useCallback(() => {
- HMSLocation.ActivityIdentification
- .Events.addActivityConversionEventListener(
- handleActivityConversion,
- );
- setConversionSubscribed(true);
- }, []);
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.
- const removeActivityConversionEventListener = useCallback(() => {
- HMSLocation.ActivityIdentification
- .Events.removeActivityConversionEventListener(
- handleActivityConversion,
- );
- setConversionSubscribed(false);
- }, []);
- return (
- <View style={styles.centralizeContent}>
- <Button
- title={identificationSubscribed ? "Unsubscribe" : "Subscribe"}
- onPress={() => {
- if (identificationSubscribed) {
- addActivityConversionEventListener()
- } else {
- addActivityIdentificationEventListener()
- }
- }} />
- </View>
- );
To use the geofence service API of HUAWEI Location Kit, you need to apply for the ACCESS_FINE_LOCATION permission in the Manifest file.
- <!--Geofence-->
- <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.
- <!--Geofence-->
- <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"/>
The name of the java class defined for Location Module is RNGeofenceModule, and its exported name to React Native is Geofence.
- import HMSLocation from 'react-native-hms-location';
- const Geofence = {
- Native: HMSGeofence,
- Builder: GeofenceBuilder,
- Data: GeofenceData,
- Request: GeofenceRequest,
- GeofenceRequestConstants: HMSGeofence.GeofenceRequestConstants,
- GeofenceConstants: HMSGeofence.GeofenceConstants,
- ErrorCodes: HMSGeofence.ErrorCodes,
- Events: {
- addGeofenceEventListener,
- removeGeofenceEventListener
- }
- };
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:
- const geofence1 = HMSLocation.Geofence.Builder.configure({
- longitude: 42.0,
- latitude: 29.0,
- radius: 20.0,
- uniqueId: 'e00322',
- conversions: 1,
- validContinueTime: 10000.0,
- dwellDelayTime: 10,
- notificationInterval: 1,
- }).build();
Then create a geofenceRequest object through the provided builder, as shown below:
- const geofenceRequest = HMSLocation.Geofence.Request.configure({
- geofences: [geofence1, geofence2],
- conversions: 1,
- coordinate: 1,
- }).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.
- const createGeofenceList = useCallback(() => {
- HMSLocation.Geofence.Native.createGeofenceList(
- geofenceRequest.geofences,
- geofenceRequest.conversions,
- geofenceRequest.coordinate,
- )
- .then(res => {
- console.log(res);
- setReqCode(parseInt(res.requestCode));
- })
- .catch(err => {
- console.log(err);
- });
- })
This id later used to remove the created conversion updates.
- const deleteGeofenceList = useCallback(reqCode => {
- HMSLocation.Geofence.Native.deleteGeofenceList(reqCode)
- .then(res => {
- console.log(res);
- setReqCode(null);
- })
- .catch(err => console.log('ERROR: GeofenceList deletion failed', err))
- }, []);
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.
- import HMSLocation from 'react-native-hms-location';
- const [geoSubscribed, setGeoSubscribed] = useState(false);
- const handleGeofenceEvent = useCallback(geo => {
- console.log('GEOFENCE : ', geo);
- setGeofenceResponse(geo);
- });
- const addGeofenceEventListener = useCallback(() => {
- HMSLocation.Geofence.Events.addGeofenceEventListener(
- handleGeofenceEvent,
- );
- setGeoSubscribed(true);
- }, []);
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.
- const removeGeofenceEventListener = useCallback(() => {
- HMSLocation.Geofence.Events.removeGeofenceEventListener(
- handleGeofenceEvent,
- )
- setGeoSubscribed(false);
- })
- return (
- <View style={styles.centralizeContent}>
- <Button
- title={geoSubscribed ? "Unsubscribe" : "Subscribe"}
- onPress={() => {
- if (geoSubscribed) {
- removeGeofenceEventListener()
- } else {
- addGeofenceEventListener()
- }
- }} />
- </View>
- );