Overview

Location Kit combines the GNSS, Wi-Fi, and base station location functionalities into your app to build up global positioning capabilities, allowing you to provide flexible location-based services for global users. In this codelab, you will learn how to call capabilities of Location Kit to create a HarmonyOS app (codelab app).
The following figure shows the basic architecture of the app. The codelab app will use the integrated Location SDK for HarmonyOS to call the location service in HMS Core (APK).

What You Will Create

In this codelab, you will create an app for obtaining device location information.

What You Will Learn

Hardware Requirements

Software Requirements

To integrate Location Kit, you must complete the following preparations:

You need to open your project in DevEco Studio.

  1. Open the project-level build.gradle file of your DevEco Studio project.
  2. Go to allprojects > repositories and configure the Maven repository address for the HMS Core SDK.
    allprojects { repositories { maven {url 'https://repo.huaweicloud.com/repository/maven/'} // Configure the Maven repository address for the HMS Core SDK. maven { url 'https://developer.huawei.com/repo/' } jcenter() } }
  3. Go to buildscript > repositories and configure the Maven repository address and AppGallery Connect service dependency for the HMS Core SDK.
    buildscript { repositories { maven {url 'https://repo.huaweicloud.com/repository/maven/'} // Configure the Maven repository address for the HMS Core SDK. maven { url 'https://developer.huawei.com/repo/' } jcenter() } dependencies { classpath 'com.huawei.ohos:hap:2.4.4.2' // Add the AppGallery Connect service dependencies. classpath 'com.huawei.agconnect:agcp-harmony:1.1.0.300' classpath 'com.huawei.ohos:decctest:1.2.4.0' } }
  4. Open the app-level build.gradle file of your project.
  5. Add a build dependency on the SDK.
    dependencies { implementation 'com.huawei.hms:location-harmony:6.3.0.300' }
  6. Add the AppGallery Connect plugin configuration.
    Add the following configuration under the declaration in the file header:

    apply plugin: 'com.huawei.agconnect'
  7. Add a build dependency on AppGallery Connect in the dependencies block.
    dependencies { // Add a build dependency on AppGallery Connect. implementation 'com.huawei.agconnect:agconnect-core-harmony:1.1.0.300' }

Before building the app, configure the obfuscation configuration file to prevent the HMS Core SDK from being obfuscated.

  1. Open the obfuscation configuration file proguard-rules.pro of your HarmonyOS project.
  2. Add the following configuration to exclude the HMS Core SDK from obfuscation:
    -ignorewarnings -repackageclasses -keepattributes *Annotation* -keepattributes Exceptions -keepattributes InnerClasses -keepattributes Signature -keep public class com.huawei.hms.location.harmony.* { *;} -keep public class com.huawei.hms.location.harmony.base.* { *;} -keep class com.huawei.hmf.tasks.* {*;}

You can click here to download the demo source code and obtain the xxx.java file used during the demo development.

  1. Declare location permissions.
    a) Declare the following permissions in reqPermissions in the config.json file:
    HarmonyOS provides two types of location permissions: ohos.permission.LOCATION (location permission) and ohos.permission.LOCATION_IN_BACKGROUND (background location permission).
    <!--Allow the app to obtain the network status.--> ohos.permission.GET_NETWORK_INFO <!-- Allow the app to obtain the coarse longitude-latitude coordinates of a user device based on the Wi-Fi network or base station, and allow the app to obtain the location information when it runs in the foreground. --> ohos.permission.LOCATION <!-- Allow the app to obtain location information when it runs in the background. --> ohos.permission.LOCATION_IN_BACKGROUND

    The sample code is as follows:

    { "module": { "reqPermissions": [ { "name": "ohos.permission.GET_NETWORK_INFO", "reason": "Allows programs to obtain network information status." }, { "name": "ohos.permission.LOCATION", "reason": "Allows applications to obtain location information when running in the foreground." }, { "name": "ohos.permission.LOCATION_IN_BACKGROUND", "reason": "Allows applications to obtain location information when running in the background." } ] } }
    b) Dynamically apply for required permissions in the BaseAbilitySlice.java file.
    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!"); } if (verifySelfPermission("ohos.permission.LOCATION_IN_BACKGROUND") != IBundleManager.PERMISSION_GRANTED) { printLog(HiLog.INFO, TAG, "Self: LOCATION_IN_BACKGROUND permission not granted!"); if (canRequestPermission("ohos.permission.LOCATION_IN_BACKGROUND")) { printLog(HiLog.INFO, TAG, "Self: can request permission here"); requestPermissionsFromUser( new String[]{"ohos.permission.LOCATION_IN_BACKGROUND"}, REQUEST_CODE); } else { printLog(HiLog.WARN, TAG, "Self: enter settings to set permission"); } } else { printLog(HiLog.INFO, TAG, "Self: LOCATION_IN_BACKGROUND permission granted!"); }
  2. Create a location provider client.
    Create a FusedLocationClient instance in the onStart() method in the BaseAbilitySlice file, and use the instance to call location-related APIs.
    public FusedLocationClient fusedLocationClient; @Override protected void onStart(Intent intent) { super.onStart(intent); fusedLocationClient = new FusedLocationClient(this); }
  3. Create the location request body.
    LocationRequest locationRequest = new LocationRequest(); locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY); locationRequest.setInterval(5000); locationRequest.setNeedAddress(true); locationRequest.setLanguage("zh");
  4. Create a location result callback.
    LocationCallback locationCallback = new LocationCallback() { @Override public void onLocationResult(LocationResult locationResult) { if (locationResult != null) { List<Location> locations = locationResult.getLocations(); if (!locations.isEmpty()) { printLog(HiLog.INFO, TAG, "onLocationResult location is not empty"); List<HWLocation> hwLocationList = locationResult.getHWLocationList(); if (!hwLocationList.isEmpty()) printLog(HiLog.INFO, TAG, "onLocationResult hwLocationList is not empty"); for (HWLocation hwLocation : hwLocationList) { String result = "[new]onLocationResult location[Longitude,Latitude,Accuracy," + "CountryName,State,City,County,FeatureName,Provider]:" + hwLocation.getLongitude() + "," + hwLocation.getLatitude() + "," + hwLocation.getAccuracy() + "," + hwLocation.getCountryName() + "," + hwLocation.getState() + "," + hwLocation.getCity() + "," + hwLocation.getCounty() + "," + hwLocation.getFeatureName() + "," + hwLocation.getProvider(); printLog(HiLog.INFO, TAG, result); showLocation.setText(result); } } } } @Override public void onLocationAvailability(LocationAvailability locationAvailability) { super.onLocationAvailability(locationAvailability); if (locationAvailability != null) { printLog(HiLog.INFO, TAG, "onLocationAvailability isLocationAvailable:" + locationAvailability.isLocationAvailable()); } } };
  5. Request location updates.
    private void requestLocationUpdates() { LocationRequest locationRequest = buildLocationRequest(); fusedLocationClient .requestLocationUpdates(locationRequest, locationCallback) .addOnSuccessListener(var -> { printLog(HiLog.INFO, TAG, "requestLocationUpdatesWithCallback onSuccess"); }) .addOnFailureListener(e -> { printLog(HiLog.INFO, TAG, "requestLocationUpdatesWithCallback onFailure:" + e.getMessage()); }); }
  6. Stop requesting location updates.
    private void removeLocationUpdates() { fusedLocationClient .removeLocationUpdates(locationCallback) .addOnSuccessListener(var -> { printLog(HiLog.INFO, TAG, "removeLocationUpdatesWithCallback onSuccess"); }) .addOnFailureListener(e -> { printLog(HiLog.INFO, TAG, "removeLocationUpdatesWithCallback onFailure:" + e.getMessage()); }); }

Tap RequestLocationWithCallback in the demo app. The obtained location information will be displayed on the app screen.

Well done. You have successfully completed this codelab and learned how to:

For more information about Location Kit, please visit our official website. If you encounter any problems during the development, please refer to FAQs.

For more information, please read related documents.
You can click here to download the source code.

Code copied