1

Wearable smartwatches are very useful for children and the elderly. There are also many similar products in the market, which support functions such as making calls, scanning QR codes for payment, and positioning, which are emerging business opportunities. Relying on the Huawei brand, Hongmeng Watch is also committed to creating a high-quality, high-quality, wearable smart experience for users. In this regard, the HMS Core location service (Location Kit) can provide three main capabilities, including fusion positioning, activity recognition and geofencing. Next, the editor invites developers to experience the positioning function developed by the positioning service on the Hongmeng watch through a few simple and quick steps.

1. Advantages and Limitations of Location Services

  1. positioning low power consumption : using the chip to realize the geo-fencing, the power consumption is lower.
  2. High-precision positioning : Optimize the positioning accuracy on both sides of the road under the urban canyon, with high accuracy. Based on RTK (Real-time kinematic) technology, it can achieve sub-meter-level high-precision positioning capabilities in open areas.
  3. The latest version of the SDK requires HMS Core (APK) 6.0.0 or later to be installed on the user's mobile phone. If it is not installed, or other versions of HMS Core (APK) are installed, the function can be used normally, but automatic version upgrade is not supported.
  4. HarmonyOS manages applications through digital certificates and Profile files, and only the signed HarmonyOS Ability Package (hereinafter referred to as "HAP") is allowed to be installed and run on the device.

2. Demo introduction

In order to let developers better understand the realization of the positioning function of Hongmeng watch, here is a simple integration case, inviting everyone to run the Demo with simple code. Code capabilities include requesting callback positioning functions, obtaining cache positioning information, querying whether positioning information is available, and checking setting permissions.

3. Development practice

The following describes how to run this Demo based on the source code for developers to understand the implementation details.

development preparation

1. Tool Preparation

Test device HarmonyOS 2.0 and above Huawei smart watch

Development Tools DevEco Studio 2.1.0.201 and above

2. Preparation before development

1) Register as Huawei Developer and create an app

Refer to Location Services Development Preparation to create an app in Huawei AppGallery.

2) Generate digital certificate and Profile file

The detailed steps include applying for the application debugging certificate , registering the debugging device and applying for the debugging Profile , and configuring the signature information.

3) generates the signature certificate fingerprint , and configures the signature certificate fingerprint.

4) Integrate HMS Core SDK

• Download the agconnect-services.json file of AGC to the local and put it under the path of "entry\src\main\resources\rawfile" in the application-level root directory.

• Add the following configuration apply plugin in the next line of the file header statement: 'com.huawei.agconnect'. In the project-level "build.gradle" file, add the Maven warehouse address and agconnect service dependencies.

buildscript {
    repositories {
        maven {url 'https://repo.huaweicloud.com/repository/maven/'}
        // 配置HMS Core SDK的Maven仓地址
        maven {url 'https://developer.huawei.com/repo/'}
        jcenter()
    }
    dependencies {
        classpath 'com.huawei.ohos:hap:2.4.4.2'
        // 添加agconnect服务依赖
        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/'}
        // 配置HMS Core SDK的Maven仓地址
        maven {url 'https://developer.huawei.com/repo/'}
        jcenter()
    }
}

• Add dependencies to the application-level build.gradle file (in fact, set the version number as needed) or place the har package of Location Kit in the local "libs" directory.

dependencies {
implementation 'com.huawei.hms:location-ohos:6.0.0.300'
// agconnect依赖组件
implementation 'com.huawei.agconnect:agconnect-core-harmony:1.1.0.300'
}

• To obfuscate the code, open the obfuscation configuration file "proguard-rules.pro" in the application-level root directory, and add the obfuscation configuration that excludes the HMS Core SDK.

Running the sample application effect display

1. Declare system permissions Add the following permissions in the "reqPermissions" field in the "config.json" file

HarmonyOS provides two location permissions: ohos.permission.LOCATION (location permission) 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 code

    //以location权限为例
    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

1. Create a location services client

Create a FusedLocationProviderClient instance in the onStart() method of the base class BaseAbilitySlice, and call the location-related interface through this instance.

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

2. Check the device location settings

Call LocationRequest to set location request parameters (including setting location update interval (milliseconds: unit), weight, language for returning address information, etc.), and call location service to check location-related settings before requesting 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 -> {
                // 设置成功定位条件
            })
            .addOnFailureListener(exp -> {
                // 设置不满足定位条件
            });
}

3. Implementation steps related to positioning function

Call requestLocationUpdates() for continuous positioning.

fusedLocProviderClient.requestLocationUpdates(locationRequest, locationCallback)
        .addOnSuccessListener(var -> {
            // 接口调用成功的处理
        })
        .addOnFailureListener(e -> {
            // 接口调用失败的处理           
        });

Call removeLocationUpdates() to stop location updates.

//注意:停止位置更新时,mLocationCallback与requestLocationUpdates()中的LocationCallback参数为同一对象。
fusedLocProviderClient.removeLocationUpdates(locationCallback)
        .addOnSuccessListener(var -> {
            // 接口调用成功的处理
        })
        .addOnFailureListener(e -> {
            // 接口调用失败的处理        
        });

Defines the location update callback.

LocationCallback locationCallback = new LocationCallback() {
    @Override
    public void onLocationResult(LocationResult locationResult) {
        if (locationResult != null) {
            // 处理位置回调结果
        }
    }
    @Override
    public void onLocationAvailability(LocationAvailability locationAvailability) {
        super.onLocationAvailability(locationAvailability);
        if (locationAvailability != null) {
            // 处理位置状态
        }
    }
};

Description of related parameters

1. Set the positioning type. If the GNSS position is requested, the value is 100; if the network position is requested, the value is 102 or 104;

2. The language of the location setting. Currently only EN and CN are supported.

3. SetNumUpdates is the number of callbacks for the requested location. If the value is 3, only 3 results will be called back to the client. If you want to keep calling back, try to use the default value.

For more details on HMS Core Location Services, please refer to:
https://developer.huawei.com/consumer/cn/doc/development/HMSCore-Guides/introduction-0000001050706106?ha_source=hms1
Huawei Developer Alliance official website:
https://developer.huawei.com/consumer/cn/doc/development/HMSCore-Guides/harmonyos-introduction-0000001121618904?ha_source=hms1
To download the demo and sample code, please go to Github:
https://github.com/HMS-Core/hms-location-demo-harmonyos
To solve integration problems go to Stack Overflow:
https://stackoverflow.com/questions/tagged/huawei-mobile-services?tab=Newest

more details>>

Visit Huawei Developer Alliance official website
Get development guidance document
Huawei Mobile Services open source warehouse address: GitHub , Gitee

us and know the latest technical information of HMS Core for the first time~


HarmonyOS_SDK
596 声望11.7k 粉丝

HarmonyOS SDK通过将HarmonyOS系统级能力对外开放,支撑开发者高效打造更纯净、更智能、更精致、更易用的鸿蒙原生应用,和开发者共同成长。