{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Have you ever had the following experience: When you are walking on a road and searching for car information in a social networking app, an ad pops up to you suddenly, telling you about discounts at a nearby car dealership. Given the advantages of the short distance, demand matching, and discount, you are more likely to go to the place for some car details, and this ad succeeds to attract you to the activity.
Nowadays, advertising has been one of the most effective ways for app developers to monetize traffic and achieve business success. By adding sponsored links or displaying ads in various formats, such as splash ads and banner ads, in their apps, app developers will be able to attract targeting audiences to view and tap the ads, or even purchase items. So how do apps always push ads for the right users at the right moment? Audience targeting methods may be the right thing they are looking for.
In the car selling situation, you may wonder how the ad can know what you want.
This benefits from the location-based ad requesting technology. Thanks to the increasing sophistication of ad technology, apps are now able to request user location-based ads, when being authorized, and audience targeting also makes it possible.
So the most important thing for an ad is to reach its target customers. Therefore, app marketing personnel should be giving a lot of thought to how to target audience, place ads online to advertise their items, and maximize ad performance.
That's why it is critical for apps to track audience information. Mobile location data can indicate the user's patterns of consumption. Office workers tend to order a lot of takeout on busy weekdays, trendsetters may prefer more stylish and fashion activities, and homeowners in high-end villas are more likely to purchase luxury items, to cite just some examples. All these mean that user attributes can be extracted from location information for ad matching purposes, and ad targeting should be as precise and multi-faceted as possible.
As an app developer, I am always looking for new tools to help me match and request ads with greater precision. Some of these tools have disappointed me greatly. Fortunately, I stumbled upon Ads Kit in HMS Core, which is capable of requesting ads based on geographical locations. With this tool, I've been able to integrate ads in various formats into my app with greater ease, and provide targeted, audience specific marketing content, including native and roll ads for nearby restaurants, stores, courses, and more.
I've been able to achieve monetization success with improvement of user conversions and substantially boost my ad revenue as a result.
To display ads more efficiently and accurately, my app can carry users’ location information through the Ads SDK, when requesting ads, so long as my app has been authorized to obtain the users' location information.
The SDK is surprisingly easy to integrate. Here's how to do it:
Integration StepsFirst, request permissions for your app.
1. As the Android OS provides two location permissions: ACCESS_COARSE_LOCATION (approximate location permission) and ACCESS_FINE_LOCATION (precise location permission), configure the permissions in the AndroidManifest.xml file.
Code:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
2. (Optional) If your app needs to continuously locate the device of Android 10 or later when it runs in the background, configure the ACCESS_BACKGROUND_LOCATION permission in the AndroidManifest.xml file.
Code:
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
3. Dynamically apply for related location permissions (according to requirements for dangerous permissions in Android 6.0 or later).
Code:
// Dynamically apply for required permissions if the API level is 28 or lower.
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) {
Log.i(TAG, "android sdk <= 28 Q");
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.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 {
// Dynamically apply for required permissions if the API level is greater than 28. The android.permission.ACCESS_BACKGROUND_LOCATION permission is required.
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.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 = {android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.ACCESS_COARSE_LOCATION,
"android.permission.ACCESS_BACKGROUND_LOCATION"};
ActivityCompat.requestPermissions(this, strings, 2);
}
}
If your app requests and obtains the location permission from a user, the SDK will carry the location information by default. If you do not want to carry the location information in an ad request from the app, you can call the setRequestLocation() API and set requestLocation to false.
Code:
// Here, a banner ad is used as an example. The location information is not carried.
AdParam adParam = new AdParam.Builder()
// Indicates whether location information is carried in a request. The options are true (yes) and false (no). The default value is true.
.setRequestLocation(false)
.build();
bannerView.loadAd(adParam);
ConclusionAll app developers are deeply concerned with how to boost conversions and revenue, by targeting ad audiences. The key is gaining insight into what users care most about. Real time location is a key piece of this puzzle.
If your apps are permitted to do so, you can add personalized ads in apps for these users. Displaying ads through ad networks may be the most popular way to help you monetize traffic and other content. A good advertising mechanism can help you a lot, and in this way, location-based ad requesting is very important in this process. Through users' locations, you will be able to give what they are looking for and show ads perfectly matching user intent. All these implementations may be a complicated process, and I have been also searching for good ways for better results.
As you can see from the coding above, this SDK is easy to implement, with just a few lines of code, and is highly useful for you to request location-based ads. I hope that it serves you as well as it has served me.
ReferencesAds Kit
Development guide
Related
1) What is analytics? Why is it used?
How your app is used by users? which pages get more traffic?on which page customers leave the app?
If you want to understand that and direct your future developments accordingly
Analytics is just for you. Understanding user’s habits will help you to make your app better.
If your app is at a certain level or you want to move your app and business forward, you need to use analytics.
To date, there are many services that offer solutions for analytics. Huawei handled analytics as a priority on HMS.
So why would I prefer Huawei Analytics?
Easy to integrate and use
It is very easy to integrate and use the analytics dashboard after integrating Huawei Analytics.
Moreover, you can customize your tables on the dashboard as you wish and you can easily see the data you want to see, not imposed on you.
Reach Huawei users
As you know, google services are not used in the latest Huawei devices. When you integrate Huawei Analytics, you will reach all Huawei users and all other devices users. So Huawei Analytics a connective, not a divider.
Power of HMS Core
Analytics gets its power from HMS Core.
It is very easy to reach all the documents you need for integration or usage of dashboard.When there is a technical problem you can find technical support very easily.
Powerful Analysis Capabilities
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
2) How to Integrate Huawei Analytics?
For integrate Huawei Analytics kit to our application, first of all, it is necessary to register in the Huawei developer community
After adding your app to AppGallery Connect, we need to enable Analytics service to usage.
After completing the enabling process, we go to the manage API tab from the project settings, activate the analytics service and add the json file on the project settings page to our project and add HMS SDK Dependencies to your project(Note: The order of these processes is important. You should update your json file in case of any service change.).
Add build dependencies to dependencies.
Code:
implementation 'com.huawei.hms:hianalytics:4.0.0.303'
Then all you have to do is go to the class you want to collect and start collecting the data.
Code:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Enable SDK log recording
HiAnalyticsTools.enableLog();
HiAnalyticsInstance instance = HiAnalytics.getInstance(this);
//Or, use context initialization
//Context context = this.getApplicationContext();
//HiAnalyticsInstance instance = HiAnalytics.getInstance(context);
//instance.setUserProfile("userKey","value");
}
You can customize the data to be collected.
Code:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Enable SDK log recording
HiAnalyticsTools.enableLog();
HiAnalyticsInstance instance=HiAnalytics.getInstance(this);
//Or, use context initialization
//Context context = this.getApplicationContext();
//HiAnalyticsInstance instance = HiAnalytics.getInstance(context);
//instance.setUserProfile("userKey","value");
}
As you can see, we can write just a few lines of code and connect our project with Huawei Analytics. So where and how do we evaluate the data we collect, let’s look at it
3) Viewing Analytics Data
You have a 4 section in welcome page. Overview, Distirbution Analysis, Operation Analysis and Advance Analysis. By default, the Overview page of an app displays its KPIs in all channels (AppGallery and AppTouch), including App impressions, Details page views, New downloads, and In-app purchase amount.
The Distribution Analysis page displays the app usage and sales data. Use Downloads & installs to measure the installation and usage of your app. Use In-App Purchases and Paid application details to measure the sales of your app.
With Operation Analysis, you can view the financial reports of your application and set up your future strategies based on this.
Advanced Analysis is a platform where you can create personalized tables, filter your users and view them according to categories, and instantly track active users and all other data.
With Event Analysis Gains insight into user behaviour details. Activity analysis providing gains insight into user loyalty. Funnel analysis gains insight the phase in which user lost.
Huawei Analytics gives us uncountable opportunities to do. As you can see here, your limit is your imagination.
Thanks for reading!
Related Links
Thanks to Mehmet Batuhan Ulper
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
With the increasing popularity of the mobile Internet, mobile apps are now becoming an integral part of our daily lives and provide increasingly more diverse functions that bring many benefits to users. One such function is searching for Point of Interests (POIs) or places, such as banks and restaurants, in an app.
When a user searches for a POI in an app, besides general information about the POI, such as the name and location, they also expect to be shown other relevant details. For example, when searching for a POI in a taxi-hailing app, a user usually expects the app to display both the searched POI and other nearby POIs, so that the user can select the most convenient pick-up and drop-off point. When searching for a bank branch in a mobile banking app, a user usually wants the app to show both the searched bank branch and nearby POIs of a similar type and their details such as business hours, telephone numbers, and nearby roads.
However, showing POI details in an app is usually a challenge for developers of non-map-related apps, because it requires a large amount of detailed POI data that is generally hard to collect for most app developers. So, wouldn't it be great if there was a service which an app can use to provide users with information about POI (such as the business hours and ratings) when they search for different types of POIs (such as hotels, restaurants, and scenic spots) in the app?
Fortunately, HMS Core Site Kit provides a one-stop POI search service, which boasts more than 260 million POIs in over 200 countries and regions around the world. In addition, the service supports more than 70 languages, empowering users to search for places in their own native languages. The place detail search function in the kit allows an app to obtain information about a POI, such as the name, address, and longitude and latitude, based on the unique ID of the POI. For example, a user can search for nearby bank branches in a mobile banking app, and view information about each branch, such as their business hours and telephone numbers, or search for the location of a scenic spot and view information about nearby hotels and weather forecasts in a travel app, thanks to the place detail search function. The place detail search function can even be utilized by location-based games that can use the function to show in-game tasks and rankings of other players at a POI when a player searches for the POI in the game.
Th integration process for this kit is straightforward, which I'll demonstrate below.
Demo
Integration Procedure
PreparationsBefore getting started, you'll need to make some preparations, such as configuring your app information in AppGallery Connect, integrating the Site SDK, and configuring the obfuscation configuration file.
If you use Android Studio, you can integrate the SDK into your project via the Maven repository. The purpose of configuring the obfuscation configuration file is to prevent the SDK from being obfuscated.
You can follow instructions here to make relevant preparations. In this article, I won't be describing the preparation steps.
Developing Place Detail SearchAfter making relevant preparations, you will need to implement the place detail search function for obtaining POI details. The process is as follows:
1. Declare a SearchService object and use SearchServiceFactory to instantiate the object.
2. Create a DetailSearchRequest object and set relevant parameters.
The object will be used as the request body for searching for POI details. Relevant parameters are as follows:
siteId: ID of a POI. This parameter is mandatory.
language: language in which search results are displayed. English will be used if no language is specified, and if English is unavailable, the local language will be used.
children: indicates whether to return information about child nodes of the POI. The default value is false, indicating that child node information is not returned. If this parameter is set to true, all information about child nodes of the POI will be returned.
3. Create a SearchResultListener object to listen for the search result.
4. Use the created SearchService object to call the detailSearch() method and pass the created DetailSearchRequest and SearchResultListener objects to the method.
5. 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:
Code:
// Declare a SearchService object.
private SearchService searchService;
// Create a SearchService instance.
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 the search result when the search is successful.
@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 when a search exception occurs.
@Override
public void onSearchError(SearchStatus status) {
Log.i("TAG", "Error : " + status.getErrorCode() + " " + status.getErrorMessage());
}
};
// Call the place detail search API.
searchService.detailSearch(request, resultListener);
You have now completed the integration process and your app should be able to show users details about the POIs they search for.
Conclusion
Mobile apps are now an integral part of our daily life. To improve user experience and provide users with a more convenient experience, mobile apps are providing more and more functions such as POI search.
When searching for POIs in an app, besides general information such as the name and location of the POI, users usually expect to be shown other context-relevant information as well, such as business hours and similar POIs nearby. However, showing POI details in an app can be challenging for developers of non-map-related apps, because it requires a large amount of detailed POI data that is usually hard to collect for most app developers.
In this article, I demonstrated how I solved this challenge using the place detail search function, which allows my app to show POI details to users. The whole integration process is straightforward and cost-efficient, and is an effective way to show POI details to users.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Many health and fitness apps provide a data subscription feature, which allows users to receive notifications in real time within the app, once their fitness or health records are updated, such as the day's step count, heart rate, or running distance.
However, tracking health and fitness over the long haul is not so easy. Real time notifications are less useful here. This can be a common challenge for fitness and health tracking apps, as meeting specific goals is not conducive for thinking over a long term. I have encountered this issue in my own fitness app. Let us say that a user of my app is trying to make an exercise plan. They set a long-term goal of walking for 10,000 steps for three times a week. When the step goal is achieved for the current day, my app will send a message with the day's step count. However, my app is still unable to notify the user whether the goal has been achieved for the week. That means, the user will have to check manually to see whether they have completed their long-term goals, which can be quite a hassle.
I stumbled across the scenario-based event subscription capability provided by HMS Core Health Kit, and tried integrating it into my app. Instead of subscribing to a single data type, I can now subscribe to specific scenarios, which entail the combination of one or more data types. In the example mentioned above, the scenario will be walking for 10,000 steps for any of the three days of a week. At the end of a week, my app will push a notification to the user, telling them whether they have met their goal.
After integrating the kit's scenario-based event subscription capability, my users have found it more convenient to track their long-term health and fitness goals. As a result, the user experience is considerably improved, and the retention period has been extended. My app is now a truly smart and handy fitness and health assistant. Next I'll show you how I managed to do this.
Integration MethodRegistering as a SubscriberApply for the Health Kit service on HUAWEI Developers, select a product you have created, and select Registering the Subscription Notification Capability. You can select the HTTP subscription mode, enter the callback notification address, and test the connectivity of the address. Currently, the subscription capability is available to enterprise developers only. If you are an individual developer, you will not be able to use this capability for your app.
You can also select device-side notification and set the app package name and action if your app:
Uses the device-side subscription mode.
Subscribes to scenario-based goal events.
Relies on communications between APKs.
Registering Subscription RecordsSend an HTTP request as follows to add or update subscription records:
Code:
POST
https://health-api.cloud.huawei.com/healthkit/v1/subscriptions
Request example
Code:
POST
https://health-api.cloud.huawei.com/healthkit/v1/subscriptions
Request body
Code:
POST
https://health-api.cloud.huawei.com/healthkit/v1/subscriptions
Content-Type: application/json
Authorization: Bearer ***
x-client-id: ***
x-version: ***
x-caller-trace-id: ***
{
"subscriberId": "08666998-78f6-46b9-8620-faa06cdbac2b",
"eventTypes": [
{
"type": "SCENARIO_GOAL_EVENT",
"subType": "ACHIEVE",
"eventType": "SCENARIO_GOAL_EVENT$ACHIEVE",
"goalInfo": {
"createTime": 1654660859105,
"startDay": 20220608, // Set the goal start date, which must be later than the date on which the goal is created.
"recurrence": {
"unit": 1, // Set the period unit to day.
"count": 30, // Set the entire period to 30 days.
"expectedAchievedCount": 28
},
"goals": [
{
"goalType": 1,
"metricGoal": {
"value": 10000, // Set the goal to 10,000 steps.
"fieldName": "steps",
"dataType": "com.huawei.continuous.steps.total"
}
}
]
}
}
]
}
Receiving Notifications of Goal AchievementSend an HTTP request as follows to receive notifications of whether a goal is achieved:
Code:
POST
https://www.example.com/healthkit/notifications
Request example
Code:
POST
https://www.example.com/healthkit/notifications
Request body
Code:
POST
https://lfhealthdev.hwcloudtest.cn/test/healthkit/notifications
Content-Type: application/json
x-notification-signature: ***
[{
"appId": "101524371",
"subscriptionId": "3a82f885-97bf-47f8-84d1-21e558fe6e99",
"periodIndex": 0,
"periodStartDay": 20220608,
"periodEndDay": 20220608,
"goalAchieve": [{
"goalType": 1,
"metricGoal": {
"value": 10000.0,
"fieldName": "steps",
"dataType": "com.huawei.continuous.steps.total"
},
"achievedFlag": true // Goal achieved.
}
]
}
(Optional) Querying Goal Achievement ResultsSend an HTTP request as follows to query results of scenario-based events in a single period:
Code:
GET
https://health-api.cloud.huawei.com/healthkit/v1/subscriptions/3a82f885-97bf-47f8-84d1-21e558fe6e99/achievedRecord
Request example
Code:
GET
https://health-api.cloud.huawei.com/healthkit/v1/subscriptions/3a82f885-97bf-47f8-84d1-21e558fe6e99/achievedRecord
Response body
Code:
HTTP/1.1 200 OK
Content-type: application/json;charset=utf-8
[
{
"openId": "MDFAMTAxNTI0MzcxQGQ0Y2M3N2UxZTVmNjcxNWFkMWQ5Y2JjYjlmZDZiaNTY3QDVhNmNkY2FiaMTFhYzc4NDk4NDI0MzJiaNjg0MzViaYmUyMGEzZjZkNzUzYWVjM2Q5ZTgwYWM5NTgzNmY",
"appId": "101524371",
"subscriptionId": "3a82f885-97bf-47f8-84d1-21e558fe6e99",
"periodIndex": 0,
"periodStartDay": 20220608,
"periodEndDay": 20220608,
"goalAchieve": [{
"goalType": 1,
"metricGoal": {
"value": 10000.0, // Goal value
"fieldName": "steps",
"dataType": "com.huawei.continuous.steps.total"
},
"achievedResult": "20023", // Actual value
"achievedFlag": true // Flag indicating goal achieved
}]
},
{
"openId": "MDFAMTAxNTI0MzcxQGQ0Y2M3N2UxZTVmNjcxNWFkMWQ5Y2JjYjlmZDZiaNTY3QDVhNmNkY2FiaMTFhYzc4NDk4NDI0MzJiaNjg0MzViaYmUyMGEzZjZkNzUzYWVjM2Q5ZTgwYWM5NTgzNmY",
"appId": "101524371",
"subscriptionId": "3a82f885-97bf-47f8-84d1-21e558fe6e99",
"periodIndex": 1,
"periodStartDay": 20220609,
"periodEndDay": 20220609,
"goalAchieve": [{
"goalType": 1,
"metricGoal": {
"value": 10000.0, // Goal value
"fieldName": "steps",
"dataType": "com.huawei.continuous.steps.total"
},
"achievedResult": "9800", // Actual value
"achievedFlag": false // Flag indicating goal not achieved
}]
}
]
ConclusionIt is common to find apps that notify users of real-time fitness and health events, for example, for every kilometer that's run, or when the user's heart rate crosses a certain threshold, or when they have walked certain number of steps that current day.
However, health and fitness goals tend to be long-term, and can be broken down into small, periodic goals. This means that apps that only offer real time notifications are not as appealing as might otherwise be.
Users may set a long-term goal, like losing 10 kg in three months, or going to the gym and exercising three times per week for the upcoming year, and then break down the goal into one month or one week increments. They may expect apps to function as a reminder of their fitness or health goals over the long run.
Health Kit can help us do this easily, without requiring too much development workload.
This kit provides the scenario-based event subscription capability, empowering health and fitness apps to periodically notify users of whether or not they have met their set goals, in a timely manner.
With these notifications, app users will be able to keep better track of their goals, and be better motivated to meet them, or even use the app to share their goals with friends and loved ones.
ReferenceHMS Core Health Kit
Data Subscription Capability Development Guide
In the mobile Internet era, people are increasingly using mobile apps for a variety of different purposes, such as buying products online, hailing taxis, and much more. When using such an app, a user usually needs to manually enter their address for package delivery or search for an appropriate pick-up and drop-off location when they hail a taxi, which can be inconvenient.
To improve user experience, many apps nowadays allow users to select a point on the map and then use the selected point as the location, for example, for package delivery or getting on or off a taxi. Each location has a longitude-latitude coordinate that pinpoints its position precisely on the map. However, longitude-latitude coordinates are simply a string of numbers and provide little information to the average user. It would therefore be useful if there was a tool which an app can use to convert longitude-latitude coordinates into human-readable addresses.
Fortunately, the reverse geocoding function in HMS Core Location Kit can obtain the nearest address to a selected point on the map based on the longitude and latitude of the point. Reverse geocoding is the process of converting a location as described by geographic coordinates (longitude and latitude) to a human-readable address or place name, which is much more useful information for users. It permits the identification of nearby street addresses, places, and subdivisions such as neighborhoods, counties, states, and countries.
Generally, the reverse geocoding function can be used to obtain the nearest address to the current location of a device, show the address or place name when a user taps on the map, find the address of a geographic location, and more. For example, with reverse geocoding, an e-commerce app can show users the detailed address of a selected point on the map in the app; a ride-hailing or takeout delivery app can show the detailed address of a point that a user selects by dragging the map in the app or tapping the point on the map in the app, so that the user can select the address as the pick-up address or takeout delivery address; and an express delivery app can utilize reverse geocoding to show the locations of delivery vehicles based on the passed longitude-latitude coordinates, and intuitively display delivery points and delivery routes to users.
Bolstered by a powerful address parsing capability, the reverse geocoding function in this kit can display addresses of locations in accordance with local address formats with an accuracy as high as 90%. In addition, it supports 79 languages and boasts a parsing latency as low as 200 milliseconds.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
DemoThe file below is a demo of the reverse geocoding function in this kit.
Preparations
Before getting started with the development, you will need to make the following preparations:
Register as a Huawei developer and complete identity verification on the HUAWEI Developers website. You can click here to find out the detailed registration and identity verification procedure.
Create a project and then create an app in the project in AppGallery Connect. Before doing so, you must have a Huawei developer account and complete identity verification.
Generate a signing certificate fingerprint and configure it in AppGallery Connect. 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.
Integrate the Location SDK into your app. If you are using Android Studio, you can integrate the SDK via the Maven repository.
Here, I won't be describing how to generate and configure a signing certificate fingerprint and integrate the SDK. You can click here to learn about the detailed procedure.
Development Procedure
After making relevant preparations, you can perform the steps below to use the reverse geocoding service in your app. Before using the service, ensure that you have installed HMS Core (APK) on your device.
1. Create a geocoding service client.
In order to call geocoding APIs, you first need to create a GeocoderService instance in the onClick() method of GeocoderActivity in your project. The sample code is as follows:
Code:
Locale locale = new Locale("zh", "CN");
GeocoderService geocoderService = LocationServices.getGeocoderService(GeocoderActivity.this, locale);
2. Obtain the reverse geocoding information.
To empower your app to obtain the reverse geocoding information, you need to call the getFromLocation() method of the GeocoderService object in your app. This method will return a List<HWLocation> object containing the location information based on the set GetFromLocationRequest object.
a. Set reverse geocoding request parameters.
There are three request parameters in the GetFromLocationRequest object, which indicate the latitude, longitude, and maximum number of returned results respectively. The sample code is as follows:
Code:
// Parameter 1: latitude
// Parameter 2: longitude
// Parameter 3: maximum number of returned results
// Pass valid longitude-latitude coordinates. If the coordinates are invalid, no geographical information will be returned. Outside China, pass longitude-latitude coordinates located outside China and ensure that the coordinates are correct.
GetFromLocationRequest getFromLocationRequest = new GetFromLocationRequest(39.985071, 116.501717, 5);
b. Call the getFromLocation() method to obtain reverse geocoding information.
The obtained reverse geocoding information will be returned in a List<HWLocation> object. You can add listeners using the addOnSuccessListener() and addOnFailureListener() methods, and obtain the task execution result using the onSuccess() and onFailure() methods.
The sample code is as follows:
Code:
private void getReverseGeocoding() {
// Initialize the GeocoderService object.
if (geocoderService == null) {
geocoderService = new GeocoderService(this, new Locale("zh", "CN"));
}
geocoderService.getFromLocation(getFromLocationRequest)
.addOnSuccessListener(new OnSuccessListener<List<HWLocation>>() {
@Override
public void onSuccess(List<HWLocation> hwLocation) {
// TODO: Define callback for API call success.
if (null != hwLocation && hwLocation.size() > 0) {
Log.d(TAG, "hwLocation data set quantity: " + hwLocation.size());
Log.d(TAG, "CountryName: " + hwLocation.get(0).getCountryName());
Log.d(TAG, "City: " + hwLocation.get(0).getCity());
Log.d(TAG, "Street: " + hwLocation.get(0).getStreet());
}
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
// TODO: Define callback for API call failure.
}
});
}
Congratulations, your app is now able to use the reverse geocoding function to obtain the address of a location based on its longitude and latitude.
Conclusion
The quick development and popularization of the mobile Internet has caused many changes to our daily lives. One such change is that more and more people are using mobile apps on a daily basis, for example, to buy daily necessities or hail a taxi. These tasks traditionally require users to manually enter the delivery address or pick-up and drop-off location addresses. Manually entering such addresses is inconvenient and prone to mistakes.
To solve this issue, many apps allow users to select a point on the in-app map as the delivery address or the address for getting on or off a taxi. However, the point on the map is usually expressed as a set of longitude-latitude coordinates, which most users will find hard to understand.
As described in this post, my app resolves this issue using the reverse geocoding function, which is proven a very effective way for obtaining human-readable addresses based on longitude-latitude coordinates. If you are looking for a solution to such issues, have a try to find out if this is what your app needs.
Conventional pop-up ads and roll ads in apps not only frustrate users, but are a headache for advertisers. This is because on the one hand, advertising is expensive, but on the other hand, these ads do not necessarily reach their target audience. The emergence of personalized ads has proved a game changer.
To ensure ads are actually sent to their intended audience, publishers usually need to collect the personal data of users to determine their characteristics, hobbies, recent requirements, and more, and then push targeted ads in apps. Some users are unwilling to share privacy data to receive personalized ads. Therefore, if an app needs to collect, use, and share users' personal data for the purpose of personalized ads, valid consent from users must be obtained first.
HUAWEI Ads provides the capability of obtaining user consent. In countries/regions with strict privacy requirements, it is recommended that publishers access the personalized ad service through the HUAWEI Ads SDK and share personal data that has been collected and processed with HUAWEI Ads. HUAWEI Ads reserves the right to monitor the privacy and data compliance of publishers. By default, personalized ads are returned for ad requests to HUAWEI Ads, and the ads are filtered based on the user's previously collected data. HUAWEI Ads also supports ad request settings for non-personalized ads. For details, please refer to "Personalized Ads and Non-personalized Ads" in the HUAWEI Ads Privacy and Data Security Policies.
To obtain user consent, you can use the Consent SDK provided by HUAWEI Ads or the CMP that complies with IAB TCF v2.0. For details, see Integration with IAB TCF v2.0.
Let's see how the Consent SDK can be used to request user consent and how to request ads accordingly.
Development ProcedureTo begin with, you will need to integrate the HMS Core SDK and HUAWEI Ads SDK. For details, see the development guide.
Using the Consent SDK
1. Integrate the Consent SDK.
a. Configure the Maven repository address.
The code library configuration of Android Studio is different in versions earlier than Gradle 7.0, Gradle 7.0, and Gradle 7.1 and later versions. Select the corresponding configuration procedure based on your Gradle plugin version.
b. Add build dependencies to the app-level build.gradle file.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Replace {version} with the actual version number. For details about the version number, please refer to the version updates. The sample code is as follows:
Code:
dependencies {
implementation 'com.huawei.hms:ads-consent:3.4.54.300'
}
After completing all the preceding configurations, click
on the toolbar to synchronize the build.gradle file and download the dependencies.
2. Update the user consent status.
When using the Consent SDK, ensure that the Consent SDK obtains the latest information about the ad technology providers of HUAWEI Ads. If the list of ad technology providers changes after the user consent is obtained, the Consent SDK will automatically set the user consent status to UNKNOWN. This means that every time the app is launched, you should call the requestConsentUpdate() method to determine the user consent status. The sample code is as follows:
Code:
...
import com.huawei.hms.ads.consent.*;
...
public class ConsentActivity extends BaseActivity {
...
@Override
protected void onCreate(Bundle savedInstanceState) {
...
// Check the user consent status.
checkConsentStatus();
...
}
...
private void checkConsentStatus() {
...
Consent consentInfo = Consent.getInstance(this);
...
consentInfo.requestConsentUpdate(new ConsentUpdateListener() {
@Override
public void onSuccess(ConsentStatus consentStatus, boolean isNeedConsent, List<AdProvider> adProviders) {
// User consent status successfully updated.
...
}
@Override
public void onFail(String errorDescription) {
// Failed to update user consent status.
...
}
});
...
}
...
}
If the user consent status is successfully updated, the onSuccess() method of ConsentUpdateListener provides the updated ConsentStatus (specifies the consent status), isNeedConsent (specifies whether consent is required), and adProviders (specifies the list of ad technology providers).
3. Obtain user consent.
You need to obtain the consent (for example, in a dialog box) of a user and display a complete list of ad technology providers. The following example shows how to obtain user consent in a dialog box:
a. Collect consent in a dialog box.
The sample code is as follows:
Code:
...
import com.huawei.hms.ads.consent.*;
...
public class ConsentActivity extends BaseActivity {
...
@Override
protected void onCreate(Bundle savedInstanceState) {
...
// Check the user consent status.
checkConsentStatus();
...
}
...
private void checkConsentStatus() {
...
Consent consentInfo = Consent.getInstance(this);
...
consentInfo.requestConsentUpdate(new ConsentUpdateListener() {
@Override
public void onSuccess(ConsentStatus consentStatus, boolean isNeedConsent, List<AdProvider> adProviders) {
...
// The parameter indicating whether the consent is required is returned.
if (isNeedConsent) {
// If ConsentStatus is set to UNKNOWN, ask for user consent again.
if (consentStatus == ConsentStatus.UNKNOWN) {
...
showConsentDialog();
}
// If ConsentStatus is set to PERSONALIZED or NON_PERSONALIZED, no dialog box is displayed to ask for user consent.
else {
...
}
} else {
...
}
}
@Override
public void onFail(String errorDescription) {
...
}
});
...
}
...
private void showConsentDialog() {
// Start to process the consent dialog box.
ConsentDialog dialog = new ConsentDialog(this, mAdProviders);
dialog.setCallback(this);
dialog.setCanceledOnTouchOutside(false);
dialog.show();
}
}
Sample dialog box
Note: This image is for reference only. Design the UI based on the privacy page.
More information will be displayed if users tap here.
Note: This image is for reference only. Design the UI based on the privacy page.
b. Display the list of ad technology providers.
Display the names of ad technology providers to the user and allow the user to access the privacy policies of the ad technology providers.
After a user taps here on the information screen, the list of ad technology providers should appear in a dialog box, as shown in the following figure.
Note: This image is for reference only. Design the UI based on the privacy page.
c. Set consent status.
After obtaining the user's consent, use the setConsentStatus() method to set their content status. The sample code is as follows:
Code:
Consent.getInstance(getApplicationContext()).setConsentStatus(ConsentStatus.PERSONALIZED);
d. Set the tag indicating whether a user is under the age of consent.
If you want to request ads for users under the age of consent, call setUnderAgeOfPromise to set the tag for such users before calling requestConsentUpdate().
Code:
// Set the tag indicating whether a user is under the age of consent.
Consent.getInstance(getApplicationContext()).setUnderAgeOfPromise(true);
If setUnderAgeOfPromise is set to true, the onFail (String errorDescription) method is called back each time requestConsentUpdate() is called, and the errorDescription parameter is provided. In this case, do not display the dialog box for obtaining consent. The value false indicates that a user has reached the age of consent.
4. Load ads according to user consent.
By default, the setNonPersonalizedAd method is not called for requesting ads. In this case, personalized and non-personalized ads are requested, so if a user has not selected a consent option, only non-personalized ads can be requested.
The parameter of the setNonPersonalizedAd method can be set to the following values:
ALLOW_ALL: personalized and non-personalized ads.
ALLOW_NON_PERSONALIZED: non-personalized ads.
The sample code is as follows:
Code:
// Set the parameter in setNonPersonalizedAd to ALLOW_NON_PERSONALIZED to request only non-personalized ads.
RequestOptions requestOptions = HwAds.getRequestOptions();
requestOptions = requestOptions.toBuilder().setNonPersonalizedAd(ALLOW_NON_PERSONALIZED).build();
HwAds.setRequestOptions(requestOptions);
AdParam adParam = new AdParam.Builder().build();
adView.loadAd(adParam);
Testing the Consent SDK
To simplify app testing, the Consent SDK provides debug options that you can set.
1. Call getTestDeviceId() to obtain the ID of your device.
The sample code is as follows:
Code:
String testDeviceId = Consent.getInstance(getApplicationContext()).getTestDeviceId();
2. Use the obtained device ID to add your device as a test device to the trustlist.
The sample code is as follows:
Code:
Consent.getInstance(getApplicationContext()).addTestDeviceId(testDeviceId);
3. Call setDebugNeedConsent to set whether consent is required.
The sample code is as follows:
Code:
// Require consent for debugging. In this case, the value of isNeedConsent returned by the ConsentUpdateListener method is true.
Consent.getInstance(getApplicationContext()).setDebugNeedConsent(DebugNeedConsent.DEBUG_NEED_CONSENT);
// Not to require consent for debugging. In this case, the value of isNeedConsent returned by the ConsentUpdateListener method is false.
Consent.getInstance(getApplicationContext()).setDebugNeedConsent(DebugNeedConsent.DEBUG_NOT_NEED_CONSENT);
After these steps are complete, the value of isNeedConsent will be returned based on your debug status when calls are made to update the consent status.
For more information about the Consent SDK, please refer to the sample code.
References
Ads Kit
Development Guide of Ads Kit