Viewing Location Using HMS Core Site Kit Place Detail Search — “My Diary” Study Case (Part 3)

Hanna Nadia Savira
8 min readJul 22, 2021

--

Team Name: The Clowns

Team Member: William Chrisandy, Hanna Nadia Savira, Halimkenneth

This is a case study that explains how to implement HMS Core in our application that can be downloaded at the following link:

My Diary

About The Apps

My Diary is an app to keep your memory that works like a physical diary. You can write multiple diaries and tag them with a date to keep you reminded of the events. You can also add some locations to each diary to keep you reminded where the event happened.

My Diary also provides you an alert dialog to prevent you from accidentally pressing back and lost all your changes. This application will also you many appropriate warn and completion statuses.

My Diary is made for you to ease up your life. You can find five or more locations at one time. You can click on the info window above the marker to select the location you wanted to add to the diary. To be able to use this feature, you have to grant access to the location permission. You can also view your location and explore the map in this feature. However, you can still run all the diary functionality, excluding the location feature without giving the location permission.

Here are some screenshots from the application:

Disclaimers

The following steps can also be found in the Huawei Developer documentation. This is just a step-by-step tutorial to use the HMS Core for your application.

Preparation

Before you get started, you must register as a Huawei developer and complete identity verification on HUAWEI Developers. For details, please refer to Registration and Verification.

We can follow instructions in Creating a Project to create a project. The signing certificate fingerprint is used to verify the authenticity of an app. Before releasing an app, you must generate a signing certificate fingerprint locally based on the signing certificate and configure it in AppGallery Connect. You can configure the Signing Certificate Fingerprint with the following steps:

  1. Sign in to AppGallery Connect and click My projects.
  2. Find your app project, and click the desired app name.
  3. Go to Project settings > General information. In the App information area, click the add icon next to SHA-256 certificate fingerprint, and enter the obtained SHA-256 certificate fingerprint.
  4. After completing the configuration, click on the check icon.

Add an app to your project. For details, please refer to Creating an App. Set relevant parameters as follows:

  • Platform: Android
  • Device: Mobile phone
  • App category: App or Game

The application use Recycler View to display the data and SQLite Database to save the data. For more information about this, you can refer to the link that can be accessed in the references section.

To use Site Kit, you need to enable it in AppGallery Connect. For details, please refer to Enabling a Service.

We can configure the Maven Repository Address for the HMS Core SDK with the following steps:

  1. Open the build.gradle file in the root directory of your Android Studio project.
  2. Add the AppGallery Connect plugin and the Maven repository.
  • Go to buildscript > repositories and configure the Maven repository address for the HMS Core SDK.
  • Go to allprojects > repositories and configure the Maven repository address for the HMS Core SDK.
  • If the agconnect-services.json file has been added to the app, go to buildscript > dependencies and add the AppGallery Connect plugin configuration.
buildscript {
repositories {
google()
jcenter()
// Configure the Maven repository address for the HMS Core SDK.
maven {url 'https://developer.huawei.com/repo/'}
}
dependencies {
...
// Add the AppGallery Connect plugin configuration.
classpath 'com.huawei.agconnect:agcp:1.4.2.300'
}
}allprojects {
repositories {
google()
jcenter()
// Configure the Maven repository address for the HMS Core SDK.
maven {url 'https://developer.huawei.com/repo/'}
}
}

We can add Build Dependencies with the following steps:

  • Open the app-level build.gradle file.
  • Add a build dependency in the dependencies block.
dependencies {
implementation 'com.huawei.hms:site:{version}'
}
  • Add the following information under apply plugin: ‘com.android.application’ in the file header:
apply plugin: ‘com.huawei.agconnect’
  • Copy the signing certificate generated in Generating a Signing Certificate to the app directory of your project, and configure the signing certificate in android in the build.gradle file.
android {
signingConfigs {
release {
// Signing certificate.
storeFile file("**.**")
// KeyStore password.
storePassword "******"
// Alias.
keyAlias "******"
// Key password.
keyPassword "******"
v2SigningEnabled true
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
signingConfig signingConfigs.release
}
debug {
signingConfig signingConfigs.release
}
}
}

After completing the preceding configuration, click the synchronization icon on the toolbar to synchronize the Gradle files.

Add the following code to the application element in the AndroidManifest.xml file, prompting users to download HMS Core (APK):

<application ...>
<meta-data
android:name="com.huawei.hms.client.channel.androidMarket"
android:value="false" />
...
</application>

After HMS Core (APK) is downloaded, the HMS Core SDK will automatically install or update HMS Core (APK).

In Android 11, the way for an app to query other apps on the user device and interact with them has been changed. If targetSdkVersion is 30 or later for your app, add the <queries> element in the manifest element in AndroidManifest.xml to allow your app to access HMS Core (APK).

<manifest ...>
...
<queries>
<intent>
<action android:name="com.huawei.hms.core.aidlservice" />
</intent>
</queries>
...
</manifest>

To call capabilities of Site Kit, you must apply for the following permissions for your app in the AndroidManifest.xml file:

<!-- Allow the app to access Internet.-->
<uses-permission android:name="android.permission.INTERNET"/>
<!--Allow the app to query the network status.-->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<!-- Allow the app to read common data. -->
<uses-permission android:name="com.huawei.appmarket.service.commondata.permission.GET_COMMON_DATA"/>
<!-- Allow the app to change the WLAN status. -->
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>

To obtain the current device location, you need to add the following permissions to the AndroidManifest.xml file. In Android 6.0 and later, you need to apply for these permissions dynamically.

<!-- Allow the app to obtain the coarse longitude and latitude of a user through the Wi-Fi network or base station. -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<!-- Allow the app to receive location information from satellites through the GPS chip. -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

After declaring permissions in the AndroidManifest.xml file, apply for the permissions dynamically in the code (according to requirements for dangerous permissions in Android 6.0).

if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P)
{
if (ActivityCompat.checkSelfPermission(this, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
String[] strings = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
ActivityCompat.requestPermissions(this, strings, 1);
}
}
else
{
if (ActivityCompat.checkSelfPermission(this, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this, "android.permission.ACCESS_BACKGROUND_LOCATION") != PackageManager.PERMISSION_GRANTED)
{
String[] strings =
{
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_BACKGROUND_LOCATION
};
ActivityCompat.requestPermissions(this, strings, 2);
}
}

Implementation

With this function, you can search for details about a place (such as the name, detailed address, and longitude-latitude coordinates of the place) based on the unique ID (siteId) of the place. One or no record is returned. To obtain place details, perform the following steps:

  • Declare a SearchService object and use SearchServiceFactory to instantiate the object. NOTE: To create a SearchService instance, you need to pass the Context parameter and API key. It is recommended that the Context parameter is of the Activity type. Otherwise, no update wizard will be displayed when HMS Core (APK) needs to be updated. The API key is generated when you create an app on HUAWEI Developers. Note that you need to call the URLEncoder.encode(“Your apiKey”, “UTF-8”) method to encode the API key using encodeURI.
  • Create a DetailSearchRequest object, which is used as the request body for place details search. Related parameters are as follows, among which siteId is mandatory and others are optional:
  • siteId: ID of a place.
  • language: language in which search results are displayed. If no language is specified, English will be used. If English is unavailable, the local language will be used.
  • politicalView: political view. The value is a two-letter country/region code complying with ISO 3166–1 alpha-2. This parameter has been deprecated.
  • children: indicates whether to return information about child nodes. The default value is false. If this parameter is set to true, full information about child nodes will be returned.
  • Create a SearchResultListener object to listen for the search result.
  • Use the created SearchService object to call the detailSearch() API and pass the created DetailSearchRequest and SearchResultListener objects to the API.
  • Obtain the DetailSearchResponse object using the created SearchResultListener object. You can obtain a Site object from the DetailSearchResponse object and then parse it to obtain the search results.

The sample code is as follows:

// Declare a SearchService object.
private SearchService searchService;
// Instantiate the SearchService object.
searchService = SearchServiceFactory.create(this, "API key");
// Create a request body.
DetailSearchRequest request = new DetailSearchRequest();
request.setSiteId("C2B922CC4651907A1C463127836D3957");
request.setLanguage("fr");
request.setChildren(false);
// Create a search result listener.
SearchResultListener<DetailSearchResponse> resultListener = new SearchResultListener<DetailSearchResponse>() {
// Return search results upon a successful search.
@Override
public void onSearchResult(DetailSearchResponse result) {
Site site;
if (result == null || (site = result.getSite()) == null) {
return;
}
Log.i("TAG", String.format("siteId: '%s', name: %s\r\n", site.getSiteId(), site.getName()));
}
// Return the result code and description upon a search exception.
@Override
public void onSearchError(SearchStatus status) {
Log.i("TAG", "Error : " + status.getErrorCode() + " " + status.getErrorMessage());
}
};
// Call the place detail search API.
searchService.detailSearch(request, resultListener);

In the My Diary application, we will get the site id from the database and then display a marker on the Map Kit. The marker’s coordinate itself is gotten from the Site Kit. For further information on how to use the map, you can check it in part 1 of this case study.

Other Parts

Check out other parts of this study case here:

Adding Map to Your Application Using HMS Core Map Kit — “My Diary” Study Case (Part 1)

Adding Location Using HMS Core Site Kit Query Autocomplete — “My Diary” Study Case (Part 2)

References

Google Developers Training Team. (2018). 4.5: RecyclerView. Retrieved July 22, 2021, from https://google-developer-training.github.io/android-developer-fundamentals-course-concepts-v2/unit-2-user-experience/lesson-4-user-interaction/4-5-c-recyclerview/4-5-c-recyclerview.html

Google Developers Training Team. (2018). 10.0: SQLite primer. Retrieved July 22, 2021, from https://google-developer-training.github.io/android-developer-fundamentals-course-concepts-v2/unit-4-saving-user-data/lesson-10-storing-data-with-room/10-0-c-sqlite-primer/10-0-c-sqlite-primer.html#sqlite

Huawei Developers. (2021). About The Service. Retrieved July 22, 2021, from https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/android-sdk-introduction-0000001061991291

Huawei Developers. (2021). About The Service. Retrieved July 22, 2021, from https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/android-sdk-about-the-service-0000001076188604

--

--