Huawei Location Kit Flutter Plugin

Table of Contents

Introduction

This plugin enables communication between Huawei Location SDK and Flutter platform. Huawei Location Kit combines the GPS, Wi-Fi, and base station locations to help you quickly obtain precise user locations, build up global positioning capabilities, and reach a wide range of users around the globe.Currently, it provides the four main capabilities: fused location, location semantics, activity identification, and geofence. You can call relevant capabilities as needed.

Huawei Location Kit provides the following core capabilities:

  • Fused location: Provides a set of simple and easy-to-use APIs for you to quickly obtain the device location based on the GPS, Wi-Fi, and base station location data.
  • Activity identification: Identifies user motion status through the acceleration sensor, cellular network information, and magnetometer, helping you adjust your app based on user behavior.
  • Geofence: Allows you to set an interested area through an API so that your app can receive a notification when a specified action (such as leaving, entering, or lingering in the area) occurs.

Installation Guide

  • Before you get started, you must register as a HUAWEI developer and complete identity verification on the HUAWEI Developer website. For details, please refer to Register a HUAWEI ID.

  • Create an app by referring to Creating an AppGallery Connect Project and Adding an App to the Project.

  • A signing certificate fingerprint is used to verify the authenticity of an app when it attempts to access an HMS Core (APK) through the HMS SDK. Before using the HMS Core (APK), you must locally generate a signing certificate fingerprint and configure it in AppGallery Connect. For details, please refer to Generating a Signing Certificate.

  • Sign in to AppGallery Connect and select My apps. Then, on the Project Setting page, set SHA-256 certificate fingerprint to the SHA-256 fingerprint from Configuring the Signing Certificate Fingerprint.

  • In AppGallery Connect, on My apps page, find your app from the list and click the app name. Go to Development > Overview > App Information. Click agconnect-service.json to download configuration file.

  • Copy the agconnect-service.json file to the android/app directory of your project.

  • Open the build.gradle file in the android directory of your project.

    • Go to buildscript then configure the Maven repository address and agconnect plugin for the HMS SDK.

        buildscript {
            repositories {
                google()
                jcenter()
                maven { url 'https://developer.huawei.com/repo/' }
            }
      
            dependencies {
                /* 
                 * <Other dependencies>
                 */
                classpath 'com.huawei.agconnect:agcp:1.3.1.300'
            }
        }
      
    • Go to allprojects then configure the Maven repository address for the HMS SDK.

        allprojects {
            repositories {
                google()
                jcenter()
                maven { url 'https://developer.huawei.com/repo/' }
            }
        }
      
  • Open the build.gradle file in the android/app directory.

    • Add apply plugin: 'com.huawei.agconnect' line after the apply plugin: 'com.android.application' line.

        apply plugin: 'com.android.application'
        apply plugin: 'com.huawei.agconnect'
        apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
      
    • Set your package name in defaultConfig > applicationId and set minSdkVersion to 19 or higher. Package name must match with the package_name entry in agconnect-services.json file.

        defaultConfig {
                applicationId "<package_name>"
                minSdkVersion 19
                /*
                 * <Other configurations>
                 */
            }
      
    • Copy the signature file that generated in Generating a Signing Certificate to android/app directory.

    • Configure the signature in android according to the signature file information.

        android {
            /*
             * <Other configurations>
             */
      
            signingConfigs {
                config {
                    storeFile file('<keystore_file>.jks')
                    storePassword '<keystore_password>'
                    keyAlias '<key_alias>'
                    keyPassword '<key_password>'
                }
            }
      
            buildTypes {
                debug {
                    signingConfig signingConfigs.config
                }
                release {
                    signingConfig signingConfigs.config
                    minifyEnabled true
                    shrinkResources true
                    proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
                }
            }
        }
      
  • On your Flutter project directory find and open your pubspec.yaml file and add library to dependencies. For more details please refer the Using packages document.

      dependencies:
          huawei_location:
              # Replace {library path} with actual library path of Huawei Location Kit Flutter Plugin.
              path: {library path}
    
  • Run following command to update package info.

      [project_path]> flutter pub get
    
  • Run following command to start the app.

      [project_path]> flutter run
    

API Reference

Fused Location Provider Client

Methods

Return TypeMethodDescription
Future<LocationSettingsStates>checkLocationSettings(LocationSettingsRequest locationSettingsRequest)This API is used to check location settings of the device.
Future<Location>getLastLocation()This API is used to obtain the last requested available location. This API does not proactively request the location. Instead, it uses the location cached for the last request.
Future<HWLocation>getLastLocationWithAddress(LocationRequest locationRequest)This API is used to obtain the available location of the last request, including the detailed address information.
Future<LocationAvailability>getLocationAvailability()This API is used to check whether the location data is available.
Future<void>setMockMode(bool mockMode)This API is used to specify whether the location provider uses the location mock mode. If yes, the GPS or network location is not used and the location set through setMockLocation (Location) is directly returned.
Future<void>setMockLocation(Location location)This API is used to set the specific mock location. You must call the setMockMode(boolean) method and set the flag to true before calling this method.
Future<int>requestLocationUpdates(LocationRequest locationRequest)This API is used to continuously request location updates.
Future<int>requestLocationUpdatesCb(LocationRequest locationRequest, LocationCallback locationCallback)This API is used to request location updates using the callback.
Future<int>requestLocationUpdatesExCb(LocationRequest locationRequest, LocationCallback locationCallback)This API is an extended location information service API. It supports high-precision location and is compatible with common location APIs. If the device does not support high-precision location or the app does not request the high-precision location permission, this API returns common location information similar to that returned by the requestLocationUpdates API.
Future<void>removeLocationUpdates(int requestCode)This API is used to remove location updates from the specified requestCode.
Future<void>removeLocationUpdatesCb(int callbackId)This API is used to remove location updates of the specified callbackId.
Stream<Location>onLocationDataThis API is used to listen location updates that comes from requestLocationUpdates API method.

Data Types

Location
PropertiesTypeDescription
providerStringLocation provider, such as network location, GPS, Wi-Fi, and Bluetooth.
latitudedoubleLatitude of a location. If no latitude is available, 0.0 is returned.
longitudedoubleLongitude of a location. If no longitude is available, 0.0 is returned.
altitudedoubleAltitude of a location. If no altitude is available, 0.0 is returned.
speeddoubleSpeed of a device at the current location, in meters per second. If no speed is available, 0.0 is returned.
bearingdoubleBearing of a device at the current location, in degrees. If no bearing is available, 0.0 is returned.
horizontalAccuracyMetersdoubleHorizontal error of a location, in meters. If no horizontal error is available, 0.0 is returned.
verticalAccuracyMetersdoubleVertical error of a location, in meters. If no vertical error is available, 0.0 is returned.
speedAccuracyMetersPerSeconddoubleSpeed error of a device at the current location, in meters per second. If no speed error is available, 0.0 is returned.
bearingAccuracyDegreesdoubleBearing error of the current location, in degrees. If no bearing error is available, 0.0 is returned.
timeintCurrent timestamp, in milliseconds.
elapsedRealtimeNanosintTime elapsed since the system was started, in nanoseconds
HWLocation
PropertiesTypeDescription
providerStringLocation provider, such as network location, GPS, Wi-Fi, and Bluetooth.
latitudedoubleLatitude of a location. If no latitude is available, 0.0 is returned.
longitudedoubleLongitude of a location. If no longitude is available, 0.0 is returned.
altitudedoubleAltitude of a location. If no altitude is available, 0.0 is returned.
speeddoubleSpeed of a device at the current location, in meters per second. If no speed is available, 0.0 is returned.
bearingdoubleBearing of a device at the current location, in degrees. If no bearing is available, 0.0 is returned.
horizontalAccuracyMetersdoubleHorizontal error of a location, in meters. If no horizontal error is available, 0.0 is returned.
verticalAccuracyMetersdoubleVertical error of a location, in meters. If no vertical error is available, 0.0 is returned.
speedAccuracyMetersPerSeconddoubleSpeed error of a device at the current location, in meters per second. If no speed error is available, 0.0 is returned.
bearingAccuracyDegreesdoubleBearing error of the current location, in degrees. If no bearing error is available, 0.0 is returned.
timeintCurrent timestamp, in milliseconds.
elapsedRealtimeNanosintTime elapsed since the system was started, in nanoseconds
countryCodeStringCountry code. The value is a two-letter code complying with the ISO 3166-1 standard.
countryNameStringCountry name.
stateStringAdministrative region.
cityStringCity of the current location.
countyStringCounty of the current location.
streetStringStreet of the current location.
featureNameStringLandmark building at the current location.
postalCodeStringPostal code of the current location.
phoneStringPhone number of the landmark building (such as a store or company) at the current location.
urlStringWebsite of the landmark building (such as a store or company) at the current location.
extraInfoMap<String, dynamic>Additional information, which is a key-value pair.
LocationRequest
PropertiesTypeDescription
priorityintRequest priority. The default value is 100.
intervalintRequest interval, in milliseconds. The default value is 3600000.
fastestIntervalintShortest request interval, in milliseconds. The default value is 600000. If another app initiates a location request, the location is also reported to the app at the interval specified in fastestInterval.
expirationTimeintRequest expiration time, in milliseconds.
numUpdatesintNumber of requested location updates.
smallestDisplacementdoubleMinimum displacement between location updates, in meters.
maxWaitTimeintMaximum waiting timeIndicates whether to return the address information. The default value is false.
needAddressboolIndicates whether to return the address information. The default value is false.
languageStringLanguage. The value consists of two letters and complies with the ISO 639-1 international standard. By default, the value is empty.
countryCodeStringCountry code. The value consists of two letters and complies with the ISO 3166-1 international standard. By default, the value is empty.
ConstantsTypeValueDescription
PRIORITY_HIGH_ACCURACYint100Used to request the most accurate location.
PRIORITY_BALANCED_POWER_ACCURACYint102Used to request the block-level location.
PRIORITY_LOW_POWERint104Used to request the city-level location.
PRIORITY_NO_POWERint105Used to request the location with the optimal accuracy without additional power consumption.
PRIORITY_HD_ACCURACYint200Used to request the high-precision location information. Currently, this parameter is available only for the requestLocationUpdatesExCb API.
MethodsReturn TypeDescription
isFastestIntervalExplicitlySetboolIndicates whether the fastest interval explicitly set or default value is being used.
LocationResult
PropertiesTypeDescription
locationsList<Location>Available locations, which are ordered from oldest to newest.
hwLocationsList<HWLocation>List of available locations sorted from oldest to newest, including the detailed address information.
lastLocationLocationAvailable location of the last request.
lastHWLocationHWLocationAvailable location of the last request, including the detailed address information.
LocationCallback
PropertiesTypeDescription
onLocationAvailabilityvoid Function(LocationAvailability locationAvailability)Callback function to listen location availability changes.
onLocationResultvoid Function(LocationResult locationResult)Callback function to listen location updates.
LocationAvailability
PropertiesTypeDescription
cellStatusintAvailability status code of cell location. Currently not provided. Value is always 0.
wifiStatusintAvailability status code of wifi location. Currently not provided. Value is always 0.
elapsedRealtimeNsintTime elapsed since the system was started, in nanoseconds. Currently not provided. Value is always 0.
locationStatusintLocation status code. If the value of smaller than 1000, then device location is available.
MethodsReturn TypeDescription
isLocationAvailableboolIndicates if the location is available or not.
LocationSettingsRequest
PropertiesTypeDescription
requestsList<LocationRequest>Collection of LocationRequest object.
alwaysShowboolIndicates whether BLE scanning needs to be enabled. The options are true (yes) and false (no).
needBleboolIndicates whether a location is required for the app to continue. The options are true (yes) and false (no).
LocationSettingsStates
PropertiesTypeDescription
blePresentboolIndicates whether the BLE exists on the device.
bleUsableboolIndicates whether the BLE is enabled and can be used by the app.
gpsPresentboolIndicates whether the GPS provider exists on the device.
gpsUsableboolIndicates whether the GPS provider is enabled and can be used by the app.
locationPresentboolIndicates whether the location provider exists on the device.
locationUsableboolIndicates whether the location provider is enabled and can be used by the app.
networkLocationPresentboolIndicates whether the network location provider exists on the device.
networkLocationUsableboolIndicates whether the network location provider is enabled and can be used by the app.

Activity Identification and Conversion

Methods

Return TypeMethodDescription
Future<int>createActivityIdentificationUpdates(int detectionIntervalMillis)This API is used to register for activity identification updates.
Future<int>createActivityConversionUpdates(List<ActivityConversionInfo> activityConversions)This API is used to activity conversions (entering and exit), for example, detecting user status change from walking to bicycling.The Conversion API supports the following activity parameters.
Future<void>deleteActivityIdentificationUpdates(int requestCode)This API is used to remove all activity identification updates from the specified requestCode.
Future<void>deleteActivityConversionUpdates(int requestCode)This API is used to remove all activity conversion updates from the specified requestCode.
Stream<ActivityIdentificationResponse>onActivityIdentificationThis API is used to listen activity identification updates that comes from createActivityIdentificationUpdates API method.
Stream<ActivityConversionResponse>onActivityConversionThis API is used to listen activity conversion updates that comes from createActivityConversionUpdates API method.

Data Types

ActivityIdentificationData
PropertiesTypeDescription
identificationActivityintType of the detected activity.
possibilityintThe confidence for the user to execute the activity. The confidence ranges from 0 to 100. A larger value indicates more reliable activity authenticity.
ConstantsTypeValueDescription
VEHICLEint100The device is in a vehicle, such as a car.
BIKEint101The device is on a bicycle.
FOOTint102The device user is walking or running.
STILLint103The device is still.
OTHERSint104The current activity cannot be detected.
TILTINGint105The device has an obvious tilt change.
WALKINGint107The user of the device is walking,it is a sub-activity of FOOT.
RUNNINGint108The user of the device is running,it is a sub-activity of FOOT.
MethodsReturn TypeDescription
static isValidType(int type)boolChecks that given activity type is one of the valid constants.
Activity Identification Service
PropertiesTypeDescription
timeintTime of this identification, which is in milliseconds since January 1, 1970.
elapsedTimeFromRebootintElapsed real time (in milliseconds) of this identification since boot.
activityIdentificationDatasList<ActivityIdentificationData>List of activitiy identification list. The activity identifications are sorted by most probable activity first.
MethodsReturn TypeDescription
mostActivityIdentificationActivityIdentificationDataThis API is used to obtain the most probable activity identification of the user.
getActivityPossibility(int activityType)intThis API is used to obtain the confidence of an activity type.
ActivityConversionData
PropertiesTypeDescription
activityTypeintActivity type of the conversion. The value is one of the activity types defined in ActivityIdentificationData.
conversionTypeintActivity conversion information. The options are ActivityConversionInfo.ENTER_ACTIVITY_CONVERSION and ActivityConversionInfo.EXIT_ACTIVITY_CONVERSION.
elapsedTimeFromRebootintElapsed real time (in milliseconds) of this conversion since boot.
ActivityConversionInfo
PropertiesTypeDescription
activityTypeintActivity type of the conversion. The value is one of the activity types defined in ActivityIdentificationData.
conversionTypeintActivity conversion information. The options are ActivityConversionInfo.ENTER_ACTIVITY_CONVERSION and ActivityConversionInfo.EXIT_ACTIVITY_CONVERSION.
ConstantsTypeValueDescription
ENTER_ACTIVITY_CONVERSIONint0A user enters the given activity.
EXIT_ACTIVITY_CONVERSIONint1A user exits the given activity.
ActivityConversionResponse
PropertiesTypeDescription
activityConversionDatasList<ActivityConversionData>All activity conversion events in the result. The obtained activity events are sorted by time in ascending order.

Geofence Service

Methods

Return TypeMethodDescription
Future<int>createGeofenceList(GeofenceRequest geofenceRequest)This API is used to add geofences. When a geofence is triggered, a notification can be listened through onGeofenceData API method.
Future<void>deleteGeofenceList(int requestCode)This API is used to remove geofences associated with a requestCode.
Future<void>deleteGeofenceListWithIds(List<String> geofenceIds)This API is used to remove geofences by their unique IDs.
Stream<GeofenceData>onGeofenceDataThis API is used to listen geofence updates that comes from createGeofenceList API method.

Data Types

Geofence
PropertiesTypeDescription
uniqueIdStringUnique ID. If the unique ID already exists, the new geofence will overwrite the old one.
conversionsintGeofence conversions. The bitwise-OR operation is supported.
validDurationintGeofence timeout interval, in milliseconds. The geofence will be automatically deleted after this amount of time.
latitudedoubleLatitude. The value range is -90,90.
longitudedoubleLongitude. The value range is -180,180.
radiusdoubleRadius, in meters.
notificationIntervalintNotification response capability. The default value is 0. Setting it to a larger value can reduce power consumption accordingly. However, reporting of geofence events may be delayed.
dwellDelayTimeintLingering duration for converting a geofence event, in milliseconds. A geofence event is converted when a user lingers in a geofence for this amount of time.
ConstantsTypeValueDescription
ENTER_GEOFENCE_CONVERSIONint1A user enters the geofence.
EXIT_GEOFENCE_CONVERSIONint2A user exits the geofence.
DWELL_GEOFENCE_CONVERSIONint4A user lingers in the geofence.
GEOFENCE_NEVER_EXPIREint-1No timeout interval is configured for the geofence.
GeofenceData
PropertiesTypeDescription
errorCodeintError code.
conversionintGeofence convert type.
convertingGeofenceIdListList<String>List of converted geofence unique IDs.
convertingLocationLocationThe location when a geofence is converted.
GeofenceRequest
PropertiesTypeDescription
geofenceListList<Geofence>List of geofences to be monitored.
initConversionsintInitial conversion type. This parameter is invalid if it is set to 0. The default value is GeofenceRequest.ENTER_INIT_CONVERSION | GeofenceRequest.DWELL_INIT_CONVERSION.
coordinateTypeintCoordinate type of geofences. Defaults to GeofenceRequest.COORDINATE_TYPE_WGS_84.
ConstantsTypeValueDescription
ENTER_INIT_CONVERSIONint1ENTER_INIT_CONVERSION is converted immediately when a request is initiated to add the geofence where a user device has already entered.
EXIT_INIT_CONVERSIONint2EXIT_INIT_CONVERSION is converted immediately when a request is initiated to add the geofence where a user device has already exit.
DWELL_INIT_CONVERSIONint4DWELL_INIT_CONVERSION is converted immediately when a request is initiated to add the geofence where a user device has already entered and stayed for the specified duration.
COORDINATE_TYPE_WGS_84int1WGS_84 coordinate system.
COORDINATE_TYPE_GCJ_02int0GCJ-02 coordinate system.

PermissionHandler

Methods

Return TypeMethodDescription
Future<bool>hasLocationPermission()This API is used to check location permission is available or not.
Future<bool>hasBackgroundLocationPermission()This API is used to check background location permission is available or not.
Future<bool>hasActivityRecognitionPermission()This API is used to check activity permission is available or not.
Future<bool>requestLocationPermission()This API is used to request location permission. Returns true if permission is granted, else returns false.
Future<bool>requestBackgroundLocationPermission()This API is used to request background location permission. Returns true if permission is granted, else returns false.
Future<bool>requestActivityRecognitionPermission()This API is used to request activity recognition permission. Returns true if permission is granted, else returns false.

Configuration Description

No.

Licensing and Terms

Huawei Location Kit Flutter Plugin uses the Apache 2.0 license.

Libraries

activity_conversion_data
activity_conversion_info
activity_conversion_response
activity_identification_data
activity_identification_response
activity_identification_service
fused_location_provider_client
geofence
geofence_data
geofence_request
geofence_service
hwlocation
location
location_availability
location_callback
location_request
location_result
location_settings_request
location_settings_states
permission_handler