Hongmeng watch positioning function demo experience, suitable for children, the elderly and travel safety markets

Time:2022-7-22

For children and the elderly, wearable smart watches are of great use. There are many similar products in the market, which support functions such as receiving and making calls, scanning payment codes, positioning, etc., and are emerging business opportunities. Relying on Huawei brand, Hongmeng watch is also committed to creating a high-quality, wearable and intelligent experience for users. In this regard,HMS core location services(location Kit) can provide three main capabilities, including fusion positioning, activity recognition and geographic fencing. Next, Xiaobian invites developers to experience the positioning function developed by positioning service on Hongmeng watch through simple and fast steps.

I Advantages and limitations of location-based services

  1. Positioning low power consumption: using chip to realize geographical fence, lower power consumption.

  2. High positioning accuracy: optimize the positioning accuracy of both sides of the road under the urban canyon, with high accuracy. Based on RTK (real – time kinematic) technology, it realizes sub meter high-precision positioning capability in open land.

  3. The latest version of SDK requires users to install HMS core (APK) version 6.0.0 or above on their mobile phones. If HMS core (APK) of other versions is not installed, the function can be used normally, but automatic version upgrade is not supported.

  4. Harmonyos controls applications through digital certificates and profile files. Only the signed harmonyos capability package (hereinafter referred to as “HAP”) can be installed on the device and run.

II Demo introduction

In order to let developers better understand the implementation of the positioning function of Hongmeng watch, here is a simple integration case, and we invite you to run the demo with simple code.Code capabilities include requesting callback location function, obtaining cache location information, querying whether location information is available and checking setting permissions

III Development practice

The following is how to run this demo according to the source code for developers to understand the implementation details.

Development preparation

one Tool preparation

Huawei smart watches with test equipment harmonyos 2.0 and above

Development tool deveco studio 2.1.0.201 and above

two Preparation before development

  1. registerBecome a Huawei developer, create an app

reference resourcesPositioning service development preparationCreate your application in the Huawei application market.

  1. Generate digital certificates and profile files

Detailed steps includeApply for application debugging certificateRegister debugging equipmentandApply for debugging profile, configure signature information.

  1. Generate signature certificate thumbprint, configure the signature certificate thumbprint.

  2. Integrated HMS core SDK

• Connect AGC’s agconnect services The JSON file is downloaded locally and placed in the application level root directory “entry\src\main\resources\rawfile”.

• Add the following configuration apply plugin to the next line of the file header declaration:’com huawei. agconnect’. Project level “build.gradle” file, add Maven warehouse address and agconnect service dependency.

buildscript {
    repositories {
        maven {url 'https://repo.huaweicloud.com/repository/maven/'}
        //Configure Maven warehouse address of HMS core SDK
        maven {url 'https://developer.huawei.com/repo/'}
        jcenter()
    }
    dependencies {
        classpath 'com.huawei.ohos:hap:2.4.4.2'
        //Add agconnect service dependency
        classpath 'com.huawei.agconnect:agcp-harmony:1.1.0.300'
        classpath 'com.huawei.ohos:decctest:1.2.4.0'
    }
}

allprojects {
    repositories {
        maven {url 'https://repo.huaweicloud.com/repository/maven/'}
        //Configure Maven warehouse address of HMS core SDK
        maven {url 'https://developer.huawei.com/repo/'}
        jcenter()
    }
}

• Application level build Add dependencies to the gradle file (actually set the version number as needed) or put it in the har package of the location kit in the local “LIBS” directory.

dependencies {
implementation 'com.huawei.hms:location-ohos:6.0.0.300'
//Agconnect dependent components
implementation 'com.huawei.agconnect:agconnect-core-harmony:1.1.0.300'
}

• If you need obfuscation code, open the obfuscation configuration file “proguard-rules.pro” under the application level root directory, and add the obfuscation configuration that excludes the HMS core SDK.

Running example application effect display

one Declare system permissions add the following permissions to the “reqpermissions” field in the “config.json” file

Harmonyos provides two location permissions: ohos permission. Location and ohos permission. LOCATION_ IN_ Background (background location permission). Note that network permissions are also required.

"reqPermissions": [
   {
    "reason": "get Local Location",
    "name": "ohos.permission.LOCATION",
    "usedScene": {
      "ability": [
        "com.huawei.codelab.MainAbility",
      ],
      "when": "always"
    }
  },
  {
    "name": "ohos.permission.GET_NETWORK_INFO"
  },
  {
    "name": "ohos.permission. LOCATION_IN_BACKGROUND"
  }
  1. Dynamically apply for “ohos.permission.location” and “ohos.permission.location_in_background” permissions in the code
//Take location permission as an example
if (verifySelfPermission("ohos.permission.LOCATION") != IBundleManager.PERMISSION_GRANTED) {
    printLog(HiLog.INFO, TAG, "Self: LOCATION permission not granted!");
    if (canRequestPermission("ohos.permission.LOCATION")) {
        printLog(HiLog.INFO, TAG, "Self: can request permission here");
        requestPermissionsFromUser(
                new String[]{"ohos.permission.LOCATION"}, REQUEST_CODE);
    } else {
        printLog(HiLog.WARN, TAG, "Self: enter settings to set permission");
    }
} else {
    printLog(HiLog.INFO, TAG, "Self: LOCATION permission granted!");
}

Key code description

one Create location service client

Create a fusedlocationproviderclient instance in the OnStart () method of the base class baseabilityslice, and call and locate the relevant interface through this instance.

public FusedLocationProviderClient fusedLocProviderClient;
@Override
protected void onStart(Intent intent) {
    super.onStart(intent);
    fusedLocProviderClient = new FusedLocationClient(this);
}

two Check device positioning settings

Call locationrequest to set the location request parameters (including setting the interval of location update (MS: Unit), weight, language of return address information, etc.), and call the location service to check the location related settings before the request callback.

private void checkLocationSettings() {
    LocationRequest locationRequest = new LocationRequest();
    locationRequest.setPriority(100);
    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
    LocationSettingsRequest request =
            builder.addLocationRequest(locationRequest).setAlwaysShow(false).setNeedBle(false).build();
    settingsClient.checkLocationSettings(request)
            .addOnSuccessListener(response -> {
                //Set successful positioning conditions
            })
            .addOnFailureListener(exp -> {
                //Setting does not meet the positioning conditions
            });
}

three Implementation steps related to positioning function

Call requestlocationupdates() to continuously locate.

fusedLocProviderClient.requestLocationUpdates(locationRequest, locationCallback)
        .addOnSuccessListener(var -> {
            //Successful processing of interface call
        })
        .addOnFailureListener(e -> {
            //Handling of interface call failure           
        });

Call removelocationupdates() to stop the location update.

//Note: when stopping location update, mlocationcallback and the locationcallback parameter in requestlocationupdates() are the same object.
fusedLocProviderClient.removeLocationUpdates(locationCallback)
        .addOnSuccessListener(var -> {
            //Successful processing of interface call
        })
        .addOnFailureListener(e -> {
            //Handling of interface call failure        
        });

Define the location update callback.

LocationCallback locationCallback = new LocationCallback() {
    @Override
    public void onLocationResult(LocationResult locationResult) {
        if (locationResult != null) {
            //Processing location callback results
        }
    }
    @Override
    public void onLocationAvailability(LocationAvailability locationAvailability) {
        super.onLocationAvailability(locationAvailability);
        if (locationAvailability != null) {
            //Processing location status
        }
    }
};

Description of relevant parameters

one Set the positioning type. If the GNSS position is requested, the value is 100; If the network location is requested, the value is 102 or 104; If you do not need to actively request the position, but only need to passively receive the position, the value is 105.

two Locate the language of the setting. Currently, only en and CN are supported.

three Setnumupdates the callback times of the request location. If the value is 3, it will only callback 3 times, and the result will be sent to the client. If you want to continue callback all the time, try to use the default value.

For more details about HMS core location services, please refer to:
https://developer.huawei.com/consumer/cn/doc/development/HMSCore-Guides/introduction-0000001050706106?ha_source=hms1
Official website of Huawei developer Alliance:
https://developer.huawei.com/consumer/cn/doc/development/HMSCore-Guides/harmonyos-introduction-0000001121618904?ha_source=hms1
Download the demo and sample code at GitHub:
https://github.com/HMS-Core/hms-location-demo-harmonyos
To solve the integration problem, please go to stack overflow:
https://stackoverflow.com/questions/tagged/huawei-mobile-services?tab=Newest

Learn more > >

visitOfficial website of Huawei developer Alliance
obtainDevelopment guidance document
Huawei mobile service open source warehouse address:GitHubGitee

Follow us and learn the latest technical information of HMS core at the first time~