Introduction
Hello everyone. This article is second part is Huawei Game Service blog series. In the first part, I’ve give some detail about Game Service and I will give information about achievements, and events.Also I've explain how to use it in the your mobile game app with the MVVM structure.
You can find first part of the Game Service blog series on the below.
How to Use Game Service with MVVM / Part 1 — Login
{
"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"
}
What Is Achievement?
Achievements are a great way to increase player engagement within your game and to give players greater incentives to continue playing the game. An achievement can represent a player’s accomplishments (for example, number of defeated players or completed missions) or the skills the player has acquired. You can periodically add achievements to keep the game fresh and encourage players to continue to participate.
Achievement information must have been configured in AppGallery Connect. For details, please refer to Configuring Achievements.
Before calling achievement APIs, ensure that the player has signed in.
The device must run EMUI 10.0 or later, and have HUAWEI AppAssistant 10.1 or later installed, in order to support achievements display.
To use the achievement feature, users need to enable Game Services on HUAWEI AppGallery (10.3 or later). If a user who has not enabled Game Services triggers achievement API calling, the HMS Core SDK redirects the user to the Game Services switch page on HUAWEI AppGallery and instructs the user to enable Game Services. If the user does not enable Game Services, result code 7218 is returned. Your game needs to actively instruct users to go to Me > Settings > Game Services on AppGallery and enable Game Services, so the achievement feature will be available.
How To Create An Achievement?
Achievements are created on the console. For this, firstly log-in Huawei AGC Console.
Select “My Apps” -> Your App Name -> “Operate” -> “Achievements”
In this page, you can see your achievements and you can create a new achievement by clicking “Create” button.
After clicked “Create” button, you will see detail page. In this page you should give some information for your achievement. So, an achievement can contain the following basic attributes:
ID: A unique string generated by AppGallery Connect to identify an achievement.
Name: A short name for the achievement that you define during achievement configuration (maximum of 100 characters).
Description: A concise description of the achievement. Usually, this instructs the player how to earn the achievement (maximum of 500 characters).
Icon: Displayed after an achievement is earned. The icon must be 512 x 512 px, and in PNG or JPG format, and must not contain any words in a specific language. The HMS Core SDK will automatically generate a grayscale version icon based on this icon and use it for unlocked achievements.
Steps: Achievements can be designated as standard or incremental. An incremental achievement involves a player completing a number of steps to unlock the achievement. The predefined number of steps is known as the number of achievement steps.
List order: The order in which the current achievement appears among all of the achievements. It is designated during achievement configuration.
State: An achievement can be in one of three different states in a game.
Hidden: A hidden achievement means that details about the achievement are hidden from the player. Such achievements are equipped with a generic placeholder description and icon while in a hidden state. If an achievement contains a spoiler about your game that you would like not to reveal, you may configure the achievement as hidden and reveal it to the payer after the game reaches a certain stage.
Revealed: A revealed achievement means that the player knows about the achievement, but has not yet earned it. If you wish to show the achievement to the player at the start of the game, you can configure it to this state.
Unlocked: An unlocked achievement means that the player has successfully earned the achievement. This state is unconfigurable and must be earned by the player. After the player achieves this state, a pop-up will be displayed at the top of the game page. The HMS Core SDK allows for an achievement to be unlocked offline. When a game comes back online, it synchronizes with Huawei game server to update the achievement’s unlocked state.
After type all of the necessary information, click the “Save” button and save. After saving, you will be see again Achievement list. And you have to click “Release” button for start to using your achievements. Also, you can edit and see details of achievements in this page. But you must wait 1–2 days for the achievements to be approved. You can login the game with your developer account and test it until it is approved. But it must wait for approval before other users can view the achievements.
Listing Achievements
1.Create Achievement List Page
Firstly, create a Xml file, and add recyclerView to list all of the achievements. You can find my design in the below.
XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="70dp"
android:id="@+id/relativeLay"
android:layout_marginBottom="50dp">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Achievements"
android:textSize="25dp"
android:textAllCaps="false"
android:gravity="center"
android:textColor="#9A9A9B"
android:fontFamily="@font/muli_regular"
android:layout_gravity="center"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="10dp"/>
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/rvFavorite"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="30dp"/>
</RelativeLayout>
2. Create AchievementsViewModel class
AchievementsViewModel class will receive data from View class, processes data and send again to View class.
Firstly create a LiveData list and ArrayList to set achievemets and send to View class. Create getLiveData() and setLiveData() methods.
Finally, create a client for achievements. And create a method to get all Achievements. Add all of the achievements into arrayList. After than, set this array to LiveData list.
Yo can see AchievementsViewModel class in the below.
Code:
class AchievementsViewModel(private val context: Context): ViewModel() {
var achievementLiveData: MutableLiveData<ArrayList<Achievement>>? = null
var achievementList: ArrayList<Achievement> = ArrayList<Achievement>()
fun init() {
achievementLiveData = MutableLiveData()
setLiveData();
achievementLiveData!!.setValue(achievementList);
}
fun getLiveData(): MutableLiveData<ArrayList<Achievement>>? {
return achievementLiveData
}
fun setLiveData() {
getAllAchievements()
}
fun getAllAchievements(){
var client: AchievementsClient = Games.getAchievementsClient(context as Activity)
var task: Task<List<Achievement>> = client.getAchievementList(true)
task.addOnSuccessListener { turnedList ->
turnedList?.let {
for(achievement in it){
Log.i(Constants.ACHIEVEMENT_VIEWMODEL_TAG, "turned Value : " + "${achievement.displayName}")
achievementList.add(achievement!!)
}
achievementLiveData!!.setValue(achievementList)
}
}.addOnFailureListener {
if(it is ApiException){
Log.i(Constants.ACHIEVEMENT_VIEWMODEL_TAG, "${(it as ApiException).statusCode}")
}
}
}
}
3. Create AchievementsViewModelFactory Class
Create a viewmodel factory class and set context as parameter. This class should be return ViewModel class.
Code:
class AchievementsViewModelFactory(private val context: Context): ViewModelProvider.NewInstanceFactory() {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
return AchievementsViewModel(context) as T
}
}
4. Create Adapter Class
To list the achievements, you must create an adapter class and a custom AchievementItem design. Here, you can make a design that suits your needs and create an adapter class.
5. Create AchievementsFragment
Firstly, ViewModel dependencies should be added on Xml file. We will use it as binding object. For this, open again your Xml file and add variable name as “viewmodel” and add type as your ViewModel class directory like that.
XML:
<data>
<variable
name="viewmodel"
type="com.xxx.xxx.viewmodel.AchievementsViewModel" />
</data>
Turn back AchievemetsFragment and add factory class, viewmodel class and binding.
Code:
private lateinit var binding: FragmentAchievementsBinding
private lateinit var viewModel: AchievementsViewModel
private lateinit var viewModelFactory: AchievementsViewModelFactory
Real full article
Tips & Tricks
Remember that each success and event has a different ID. So, you must set the ID value of the event or achievement you want to use.
You must wait until the approval process is complete before all users can use the achievements and events.
Conclusion
Thanks to this article, you can create event and achievement on the console. Also, thanks to this article, you can grow and list your events.
In the next article, I will explain Leaderboard, Saved Games and give an example. Please follow fourth article for develop your game app with clean architecture.
References
HMS Game Service
Read full article here
Related
Hello everyone, in this article I am going to talk about Crash services which one of the AppGallery Connect services.
{
"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"
}
What is the crash service ?
The crash service of AppGallery Connect reports crashes automatically and allows crash analysis after integrating the crash service, your app will automatically report crashes to AppGallery Connect for it to generate crash reports in real time. The abundant information provided in reports will help you locate and resolve crashes.
Why do we need the crash service ?
Although apps have gone through rounds the tests before release considering the large user base diverse device models and complex network environment. it’s inevitable for apps to crash occasionally. Crashes compromise user experience, Users may even uninstall you app due to crashes and your app is not going to get good reviews.
You can’t get sufficient crash information from reviews to locate crashes, Therefore you can’t resolve them shortly. This will severely harm your business. That’s why we need to use the crash services in our apps to be more efficient.
How can we integrate Crash service ?
It’s piece of cake ! , you only need to integrate the Crash SDK to your app. Then the SDK can implement related functions without any coding. I’m going to tell you how to implement the SDK in progressive section.
Getting Started on Crash Service
There are some procedures that you need to apply it into your own app.Here is the following steps ,go for it;
1-Integrating the AppGallery Connect SDK
You will find out whole necessary information about how to integrate the SDK on AppGallery Connect.
2-Enabling HUAWEI Analytics Kit
The Crash service uses capabilities of HUAWEI Analytics Kit when reporting crash events. Therefore, you must enable HUAWEI Analytics Kit before integrating the Crash SDK. For details, please refer to Service Enabling.
3-Integrating HUAWEI Analytics Kit
Before using HUAWEI Analytics Kit, you must integrate it by adding the following code to the app-level build.gradle file (usually in the app directory):
Java:
implementation 'com.huawei.hms:hianalytics:5.0.3.300'
4-Integrating the Crash SDK
Add the following code to the app-level build.gradle file (usually in the app directory) to integrate the Crash SDK:
Java:
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation "com.huawei.agconnect:agconnect-crash:1.4.1.300"
}
After applying these steps, don’t forget to click on “Sync Now” button on the right top to rebuild with updated version of your project.
AndroidManifest Permission
Also,you need to add these below permission commands into your Androidmanifest.xml.
Java:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.agccrash.huawei">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="com.huawei.permission.SECURITY_DIAGNOSE"/>
</manifest>
Code Development Part
You can see piece by piece code blocks in MainActivity.java
Add the code for calling the AGConnectCrash.testIt method to trigger a crash when the makeCrash button is tapped.
Java:
Button btn_crash = findViewById(R.id.btn_crash);
btn_crash.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AGConnectCrash.getInstance().testIt();
}
});
Add the code for calling the AGConnectCrash.enableCrashCollection method to enable crash data reporting when the CrashCollectionON button is tapped.
Java:
findViewById(R.id.enable_crash_on).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AGConnectCrash.getInstance().enableCrashCollection(true);
}
});
Add the code for disabling crash data reporting when the CrashCollectionOFF button is tapped.
Java:
findViewById(R.id.enable_crash_off).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AGConnectCrash.getInstance().enableCrashCollection(false);
}
});
Add the code for calling AGConnectCrash.setUserId to define a custom user ID, calling AGConnectCrash.log to record custom logs, and calling AGConnectCrash.setCustomKey to define a custom key-value pair when the CustomReport button is tapped.
Java:
findViewById(R.id.CustomReport).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AGConnectCrash.getInstance().setUserId("testuser");
AGConnectCrash.getInstance().log(Log.DEBUG,"set debug log.");
AGConnectCrash.getInstance().log(Log.INFO,"set info log.");
AGConnectCrash.getInstance().log(Log.WARN,"set warning log.");
AGConnectCrash.getInstance().log(Log.ERROR,"set error log.");
AGConnectCrash.getInstance().setCustomKey("stringKey", "Hello world");
AGConnectCrash.getInstance().setCustomKey("booleanKey", false);
AGConnectCrash.getInstance().setCustomKey("doubleKey", 1.1);
AGConnectCrash.getInstance().setCustomKey("floatKey", 1.1f);
AGConnectCrash.getInstance().setCustomKey("intKey", 0);
AGConnectCrash.getInstance().setCustomKey("longKey", 11L);
}
});
Here is the all MainActivity.xml layout, it creates application interface.
Java:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<LinearLayout
android:layout_width="300dp"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical">
<Button
android:id="@+id/btn_crash"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAllCaps="false"
android:text="makeCrash" />
<Button
android:id="@+id/enable_crash_off"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAllCaps="false"
android:text="CrashCollectionOFF" />
<Button
android:id="@+id/enable_crash_on"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAllCaps="false"
android:text="CrashCollectionON" />
<Button
android:id="@+id/CustomReport"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAllCaps="false"
android:text="CustomReport" />
</LinearLayout>
</LinearLayout>
The app interface you will see after applying xml to your own project is as follows.
So, we completed code development part, the next step is tracking and analysing results at AppGallery Connect ,after executing your project.
Enabling Crash Service On AppGallery Connect
After signing AppGallery Connect ,you need to follow these steps to enable crash service, if you are going to use it first time.
My project →Project Settings → Quality → Enable Now
How can we resolve the existing crashes ?
With signing in to AppGallery Connect ,you can check crash indicators including number of crashes, number of affected users and crash rate. You can filter date by time ,OS, app version, device type and other criteria to find the crash you want to resolve. In addition, you can check the details of the crash, locate the crash accordingly or directly go to the code where the crash occurs based on the crash stack and resolve the crash.
What is crash notification ?
The crash service will monitor your app in real time for crashes, When a critical crash occurs, if you have enabled the notification function, you will receive email notifications , so you can resolve them promptly.
How to Enable Crash Notifications ?
Please follow the below steps to enable crash notifications.
1. Sign in to AppGallery Connect and select Users and permissions.
2. Go to User > Personal information.
3. In the Notification area, select the check boxes under Email and SMS message for Crash notification (Notify me of a major crash) and click Save.
Monitoring & Analyzing Crash Service Test Result
After completing configuration process, you can see the results for your crash services.
In “Statistics ” tab, you will find out some outputs about crash. Such as;
How much times your app crashed,
Crash Rate,
Affected Users,
In time type
Additionally, you can select “Add Filter” on left top and check out the result as;
Operating System
App version,
Device
However, you can customize the threshold with clicking on “Set crash notification”.
You can also download report by clicking on “Download Report” to verify in .csv format the all crash results.
In ”Problems ” tab, you can view main problem of crash’ occuring reaason.Additively, can check out ;
Event Type,
Event,
Affected User,
Last occurence time.
After clicking on the name of the problem which is “java.lang.NullPointerException” here, you will get a chance to examine in detail.
In below table, you will have information to check such as;
Stack,
Logs,
Status,
Information.
Now we are going to explain above matters ,after that jump into “Search by User” tab.
In “Logs” tab , you can go through logs by filtering according to ;
All
Debug,
Info,
Warning
Error
Also you can get search with using the box named as “Enter a keyword”.
In “Status” tab , To obtain the app status in which a crash occurs, you can add a custom “key-value” pair to record the status. Actually here, you will have examine your own custom values that you created to occur crash.
In “Information” tab, you take a look at information about your ;
App
Operating System
Device
In “Search by user” tab, you will find out some outputs about crash’s ;
Occuring time,
User ID,
Event type,
Problems
Customizing a Crash Report
if you want , you can create your own crash report by customizing these red marked area parameters.So that your analyz will be more efficient and understandable.
FAQ’s
Q:Can I get export the all crash reports from AppGallery Connect ?
A:Yes sure, you can download as report .csv format in your own AGC crash page.
Q:Can I see through AGC that my application has been crashed for whatever reason?
A:Yes you can , clicking on through Problems tab, you will see 4 different tab named as Stack, Logs, Status and Information, each tab will give you different solution about what you are looking for
Q:Why can’t ı see the crash report immediately in AGC ,when I run the test in my app ? Is there any duration to see and how long data is stored ?
A:The reflection of the test report to you is at least 1 minute on average, and this data provides you with the results of hourly, 24-hour and 7-day, 30-day and 90-day data.
We have come to the end of my article, I hope what I mentioned will be useful to you, see you in my next article, I wish you all have a nice day…
References
https://developer.huawei.com/consum...Gallery-connect-Guides/agc-crash-introduction
Very useful.
Can we track activity names , where exactly crash happens and is it possible to track runtime exceptions?
Introduction
This article is based on Multiple HMS services application. I have created Hotel Booking application using HMS Kits. We need mobile app for reservation hotels when we are traveling from one place to another place.
In this article I have implemented Account kit and Ads Kit. User can login through Huawei Id.
{
"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"
}
Flutter setup
Refer this URL to setup Flutter.
Software Requirements
1. Android Studio 3.X
2. JDK 1.8 and later
3. SDK Platform 19 and later
4. Gradle 4.6 and later
Steps to integrate service
1. We need to register as a developer account in AppGallery Connect
2. Create an app by referring to Creating a Project and Creating an App in the Project
3. Set the data storage location based on current location.
4. Enabling Required Services: Account and Ads Kit.
5. Generating a Signing Certificate Fingerprint.
6. Configuring the Signing Certificate Fingerprint.
7. Get your agconnect-services.json file to the app root directory.
Development Process
Create Application in Android Studio.
1. Create Flutter project.
2. App level gradle dependencies. Choose inside project Android > app > build.gradle.
Code:
apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect'
Root level gradle dependencies
Code:
maven {url 'https://developer.huawei.com/repo/'}
classpath 'com.huawei.agconnect:agcp:1.4.1.300'
Add the below permissions in Android Manifest file.
Code:
<manifest xlmns:android...>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
</manifest>
3. Refer below URL for cross-platform plugins.
https://developer.huawei.com/consum...y-V1/flutter-sdk-download-0000001051088628-V1
4. On your Flutter project directory find and open your pubspec.yaml file and add library to dependencies to download the package from pub.dev. Or if you downloaded the package from the HUAWEI Developer website, specify the library path on your local device. For both ways, after running pub get command, the plugin will be ready to use.
Code:
name: hotelbooking
description: A new Flutter application.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
version: 1.0.0+1
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
shared_preferences: ^0.5.12+4
bottom_navy_bar: ^5.6.0
cupertino_icons: ^1.0.0
provider: ^4.3.3
huawei_ads:
path: ../huawei_ads/
huawei_account:
path: ../huawei_account/
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
assets:
- assets/images/
5. We can check the plugins under External Libraries directory.
6. Open main.dart file to create UI and business logics.
Account kit
Account kit allows users to login their applications conveniently, quickly and simple login functionalities to the 3rd party applications.
If you examine Account Kit’s Official Huawei resources on internet, it also appears that they imply the simplicity, fastness and security. We can make use of following observation to understand where this fastness and simplicity is originated.
Service Features
Quick and standard
Huawei Account Kit allows you to connect to the Huawei ecosystem using your HUAWEI ID from a range of devices. This range of devices is not limited with mobile phones, you can also easily access applications on tablets, wearables, and smart displays using Huawei ID.
Massive user base and global services
Huawei Account Kit serves 190+ countries and regions worldwide. Users can also use HUAWEI ID to quickly sign in to apps. For details about supported regions/countries, please refer here from official documentation.
Secure, reliable, and compliant with international standards
Complies with international standards and protocols (such as OAuth2.0 and OpenID Connect), and supports two-factor authentication to ensure high security.
Integration
Signing-In
To allow users securely signing-in with Huawei ID, you should use signIn method of HMSAccount module. When this method called for the first time for a user, a Huawei ID authorization interface will be shown Once signIn successful, it will return AuthHuaweiID object.
Code:
void _signInHuawei() async {
final helper = new HmsAuthParamHelper();
helper
..setAccessToken()
..setIdToken()
..setProfile()
..setEmail()
..setAuthorizationCode();
try {
HmsAuthHuaweiId authHuaweiId =
await HmsAuthService.signIn(authParamHelper: helper);
StorageUtil.putString("Token", authHuaweiId.accessToken);
Navigator.push(context,MaterialPageRoute(builder: (context) => HomePageScreen()),
);
} on Exception catch (e) {}
}
Signing-Out
signOut method is used to allow user signing-out from app, it does not clear user information permanently.
Code:
void signOut() async {
try {
final bool response = await HmsAuthService.signOut();
} on Exception catch (e) {
print(e.toString());
}
}
ADs kit
Nowadays, traditional marketing has left its place on digital marketing. Advertisers prefer to place their ads via mobile media rather than printed publications or large billboards, this way they can reach their target audience more easily and they can measure their efficiency by analyzing many parameters such as ad display and the number of clicks.
HMS Ads Kit is a mobile service that helps us to create high quality and personalized ads in our application. It provides many useful ad formats such as native ads, banner ads and rewarded ads to more than 570 million Huawei device users worldwide.
Advantages
1. Provides high income for developers.
2. Rich ad format options.
3. Provides versatile support.
1. Banner Ads are rectangular ad images located at the top, middle or bottom of an application’s layout. Banner ads are automatically refreshed at intervals. When a user taps a banner ad, in most cases the user is taken to the advertiser’s page.
2. Rewarded Ads are generally preferred in gaming applications. They are the ads that in full-screen video format that users choose to view in exchange for in-app rewards or benefits.
3. Native Ads are ads that take place in the application’s interface in accordance with the application flow. At first glance they look like a part of the application, not like an advertisement.
4. Interstitial Ads are full screen ads that cover the application’s interface. Such that ads are displayed without disturbing the user’s experience when the user launches, pauses or quits the application.
5. Splash Ads are ads that are displayed right after the application is launched, before the main screen of the application comes.
Huawei Ads SDK integration Let’s call HwAds.init() in the initState()
Code:
@override
void initState() {
super.initState();
HwAds.init();
}
Load Banner Ads
void loadAds() {
BannerAd _bannerAd;
_bannerAd = createAd()
..loadAd()
..show();
}
BannerAd createAd() {
return BannerAd(
adSlotId: "testw6vs28auh3",
size: BannerAdSize.s320x50,
adParam: new AdParam());
}
Load Native Ads
Code:
NativeAdConfiguration configuration = NativeAdConfiguration();
configuration.choicesPosition = NativeAdChoicesPosition.bottomRight;
Container(
height: 100,
margin: EdgeInsets.only(bottom: 10.0),
child: NativeAd(
adSlotId: "testu7m3hc4gvm",
controller: NativeAdController(
adConfiguration: configuration,
listener: (AdEvent event, {int errorCode}) {
print("Native Ad event : $event");
}),
type: NativeAdType.small,
),
),
Result
Tips & Tricks
1. Download latest HMS Flutter plugin.
2. The lengths of access_token and refresh_token are related to the information encoded in the tokens. Currently, access_token and refresh_token contains a maximum of 1024 characters.
3. This API can be called by an app up to 10,000 times within one hour. If the app exceeds the limit, it will fail to obtain the access token.
4. Whenever you updated plugins, click on pug get.
Conclusion
We implemented simple hotel booking application using Account kit and Ads kit in this article.
Thank you for reading and if you have enjoyed this article, I would suggest you to implement this and provide your experience.
Reference
Account Kit URL
Ads Kit URL
Read full article
Garrygb said:
Hi! Thank you for share this information. I tried to build apps for my business using HMS kits but unfortunately have some problems with the main code and I can't find where this code error. Perhaps, I will try to ask for help from professional apps developers.
Click to expand...
Click to collapse
Hi can you please explain which kit you integrated in your application ,can you explain detail so that i can able to help you out to fix your problems
I deleted all projects and start new.
With the unveiling of so many new functions and pages on HUAWEI AppGallery, it’s required a wide range of new redirection solutions on the platform.
However, the types of links, functions, apps, and scenarios that they are used, can vary great. It can be quite confusing sorting this all out, so I’ve outlined some common redirection scenarios for your reference.
Feel free to correct me, if you think that I’ve got something wrong, or am missing something.
1. Redirecting to the AppGallery Home Page
Usage case: You want to redirect the user from an app to the AppGallery home page, so that the user can search for related apps or activities quickly.
Method: Use the action method from Intent to implement the function.
action: com.huawei.appmarket.intent.action.MainActivity
Example:
Java:
public void launchAGHomePage() {
Intent intent = new Intent("com.huawei.appmarket.intent.action.MainActivity");
startActivity(intent);
}
2. Redirecting to an App’s Details Page on AppGallery
2.1 Intent-based Redirection from an In-App Page
Usage case: You want to redirect the user from an in-app page to the app’s details page, so the user can rate or comment on the app.
Methods: Use the action method from Intent to implement the function.
1. Method 1: by app ID
action:com.huawei.appmarket.appmarket.intent.action.AppDetail. withid
setPackage("com.huawei.appmarket");
name: "appId", value: "C100170981"
2. Method 2: by package name
action: com.huawei.appmarket.intent.action.AppDetail
setPackage("com.huawei.appmarket");
name: "APP_PACKAGENAME", value: "com.huawei.browser"
Note: Compared with method 2, method 1 includes additional appmarket and withid parameters from the action method.
Parameters involved:
{
"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"
}
Examples:
Method 1:by app ID
Java:
public void launchAppDetilPage1() {
Intent intent = new Intent("com.huawei.appmarket.appmarket.intent.action.AppDetail.withid");
intent.setPackage("com.huawei.appmarket");
intent.putExtra("appId", "C100170981");
startActivity(intent);
}
Method 2:by package name
Java:
public void launchAppDetilPage2() {
Intent intent = new Intent("com.huawei.appmarket.intent.action.AppDetail");
intent.setPackage("com.huawei.appmarket");
intent.putExtra("APP_PACKAGENAME", "com.huawei.browser");
startActivity(intent);
}
2.2 URL-based Redirection
Usage case: You want to redirect a user who clicks on a shared URL to an app’s details page.
Method: Create a URL with the following format:
hiapplink://com.huawei.appmarket?appId=yourAppID&channelId=yourChannelId&referrer=yourReferrer
Note: You’ll need to change the strings in either italic or bold only.
Parameters involved:
Example:
By app id
Java:
public void launchAppDetilWithURL1() {
String text1 = "hiapplink://com.huawei.appmarket?appId=C100170981&channelId=HwBrowserSearch&referrer=Keywords";
Uri uri = Uri.parse(text1);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
3. Launching All App Stores Installed on a Device to Redirect Users to an App’s Details Page in an App Store via MARKET
Usage case: You want to launch all app stores installed on the user’s device by passing a package name or app ID, so that the user can choose to go to the app’s details page in a desired app store.
Methods: Pass the link whose scheme is market://. Android supports the standard MARKET protocol, to ensure that all app stores can be launched on Android devices. The methods are as follows:
Method 1: market://details?id=pkgName // for all stores
Method 2: appmarket://details?id=pkgName // only for AppGallery
Method 3: market://com.huawei.appmarket.applink?appId=App ID" // only for AppGallery
Note: Method 1 is a standard method for Android devices, and is applicable to all app stores, such as Google Play and Tecent Appstore.
Parameters involved:
Examples:
// Method 1
Java:
public void launchAppDetilOnMarket1() {
String text1 = "market://details?id=com.huawei.browser";
Uri uri = Uri.parse(text1);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
// Method 2
Java:
public void launchAppDetilOnMarket2() {
String text1 = "appmarket://details?id=com.huawei.browser";
Uri uri = Uri.parse(text1);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
// Method 3
Java:
public void launchAppDetilOnMarket3() {
String text1 = "market://com.huawei.appmarket.applink?appId=C100170981";
Uri uri = Uri.parse(text1);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
4. Redirecting from a Web Link to an App’s Detail Page on the Web Version of AppGallery
Usage case: You want to redirect the user to an app’s details page on the web version of AppGallery, when the user clicks on a web link from the app’s official website, or a promotional web page.
Methods:
Method 1:https://appgallery.huawei.com/#/app/YOUR_APPID
Method 2::https://appgallery.cloud.huawei.com/appDetail?pkgName=pkgName
Method 3:https://appgallery.huawei.com/#/app/YOUR_APPID?pkgName=pkgName
Method 4:https://appgallery.cloud.huawei.com/marketshare/app/ YOUR_APPID?locale=LOCALE&shareTo=WAP&shareFrom=channeID
Parameters involved:
Examples:
// Method 1: by app ID
https://appgallery.huawei.com/#/app/C100170981
// Method 2: by package name
https://appgallery.cloud.huawei.com/appDetail?pkgName=com.huawei.browser
// Method 3: by app ID and package name
https://appgallery.huawei.com/#/app/C100170981?pkgName=com.huawei.browser
// Method 4: by complete link with optional parameters (not commonly used, and generally used for badge-based promotions).
HUAWEI Browser
Huawei AppGallery
appgallery.cloud.huawei.com
5. Redirecting from a Badge Link to the App Detail Page on AppGallery
When a badge link of AppGallery appears as an image of AppGallery, by clicking this link, the user will be redirected to an app’s details page on AppGallery. If you hope to market your app, you can use this badge directly. In essence, it still functions as a link, no different than any other web link.
Use cases: If you have developed and released an app, and want to divert traffic from your website or another source to AppGallery, a badge can be ideal.
How to make a badge: The method for creating a badge is rather simple. You only need to sign in to AppGallery Connect, and click AppGallery Download. Then you proceed to make the badge as prompted.
Restrictions: You can only make a badge for apps that have been released, with a maximum of one badge for each app. Once a badge has been created, you can query for it on the Search badge tab page.
Badge use instructions:
You can find a created badge on the Search badge tab page, and download the badge or copy its link. I’ll walk you through some common operations:
Badge download: You will obtain a PNG image, which can be displayed on your website, or on a marketing HTML5 page.
Link creation: You can create a link for a specific channel, for example, Facebook or Baidu.
Link copying: You can download a link for a specific channel.
Usage example:
// 1. Typical link
https://appgallery.huawei.com/#/app...EDCCBCD90A86F29A8DA2400AA4163&detailType=0&v=
// 2. Typical badge with a link, which can be clicked
6. App Linking, with Cross-Platform Link Support
App Linking is a new service provided by AppGallery Connect. Since it’s new, I’ll give you a brief overview of what it is.
The service provides links that can work on a diverse range of platforms, such as Android, iOS, and PC browsers, making it similar in this way to Dynamic Links of Firebase, enabling you to quickly build cross-platform links, which can be easily shared.
In what scenarios can I use App Linking? I’ll give you an example to help illustrate how the service can be used. It’s an app that’s available on both Android and iOS devices, and thus requires a promotional activity that reaches users on both platforms. To engage users, we’ll need to send them an activity invitation link that works on Android and iOS alike. Also, some users may be opening the link in a PC browser, and in this case, that link should also support an HTML5 page for the activity.
What benefits does App Linking offer? Here, two scenarios should be considered:
The user’s device has already installed the app: App Linking will automatically open the app, and show the user the target page.
The user’s device has not installed the app: The link will prompt the user to open the app’s details page on AppGallery, or any other app store (configurable), and download the app. Then, when the user opens the downloaded app, the target page will appear.
How does App Linking work? Links of App Linking can be created in any of the following ways:
Creation on the console: All operations are performed in AppGallery Connect. You’ll need to click My projects, click your project, and go to Grow > App Linking. To create a link of App Linking, create a URL prefix first.This mode is recommended if you’re not familiar with coding. A step will require you to provide a deep link, which will need to be obtained from your R&D personnel.
Creation in your iOS app: This mode is similar to the previous one.
The only difference is that these links are for iOS users.
What if the user’s device is not a Huawei device?
Since App Linking supports both Android and iOS, many of you may be wondering how this service works on non-Huawei Android devices.
1. Can App Linking work for non-Huawei devices? You can be rest assured App Linking is not dependent on HMS Core, and thus is supported on all Android devices, regardless of whether they are running GMS or HMS.
2. What if the user has not installed the app and AppGallery? For Android devices that don’t have AppGallery installed, you can choose to open the link in the local app store that is installed. As long as your package name on that app store is the same as that on AppGallery, the user will be able to open your app’s details page on that app store.
Usage example:
// 1. Typical URL prefix
https://photoplaza.drcn.agconnect.link // In the prefix, photoplaza is unique to the app, and drcn.agconnect.link is a fixed.
// 2. Typical link of App Linking
https://photoplaza.drcn.agconnect.link/vm3Y
// 3. Code for creating a typical link of App Linking for Android
Java:
private static final String DOMAIN_URI_PREFIX = "https://photoplaza.drcn.agconnect.link";private static final String DEEP_LINK = "https://developer.huawei.com";public void createAppLinking() {
AppLinking.Builder builder = new AppLinking.Builder()
.setUriPrefix(DOMAIN_URI_PREFIX)
.setDeepLink(Uri.parse(DEEP_LINK))
.setAndroidLinkInfo(new AppLinking.AndroidLinkInfo.Builder().build());
String LongAppLinking = builder.buildAppLinking().getUri().toString();
}
// 4. Typical link of App Linking for iOS
Objective-C:
- (IBAction)CreatLink:(id)sender {
AGCAppLinkingComponents *component = [[AGCAppLinkingComponents alloc] init];
component.uriPrefix = @"https://photoplaza.drcn.agconnect.link";
component.deepLink = @"https://www.developer.huawei.com";
component.iosBundleId = @"com.lucky.agc.demo";
component.iosDeepLink = @"agckit://ios/detail"; self.longlink.text = component.buildLongLink.absoluteString;
}
7. For Reference
Badge link document: https://developer.huawei.com/consum...ct-Guides/appgallery-agd-introduction-stamped
App Linking document: https://developer.huawei.com/consum.../agc-applinking-introduction-0000001054143215
Guide for adding a referrer: https://developer.huawei.com/consum...connect-Guides/appgallery-referrer-createlink
Guide for querying attribution information: https://developer.huawei.com/consum...ry-connect-Guides/appgallery-referrer-develop
{
"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"
}
Introduction
Hello everyone, this article is third part of the Huawei Game Service blog series. In the third part, I’ve give some detail about Game Service and I’ve give information about leaderboards and saved games. Also I've explain how to use it in the your mobile game app with the MVVM structure. You can find second part of the Game Service blog series on the below.
How to Use Game Service with MVVM / Part 2— Achievements & Events
What Is Leaderboards?
Leaderboards are an effective way to drive competition among game players by displaying players’ rankings. You can create up to 70 leaderboards in AppGallery Connect. Your game can report the score of a player to one or more leaderboards you have created at specified moments (for example, when a player reaches a level or a round ends). Huawei game server automatically processes the scores of players and ranks them. Then you can call rankings APIs to display the leaderboards to your game players.
The basic functions of a leaderboard are as follows:
Huawei game server automatically checks whether a reported score of a player is better than the best score ever recorded for this player. If so, Huawei game server will update all involved leaderboards with the new score.
A game can have up to 70 leaderboards, and a leaderboard can have up to 5000 records.
Huawei game server automatically creates the daily, weekly, and all-time versions for a leaderboard. For example, the server can generate the daily, weekly, and all-time versions for a round-finishing time leaderboard of a racing game. You do not need to create a leaderboard for each time frame.
Leaderboards reset data based on the local time of the corresponding game server. For example, the China site adopts UTC+08:00. The daily leaderboard is reset at 00:00 every day, and the weekly leaderboard is reset at 24:00 on Saturday for the Europe site and at 24:00 on Sunday for other sites. A leaderboard displays only rankings of players from the same site.
If entries on your leaderboards are ranked by currency amount, you need to perform exchange rate conversion on your own. Huawei game server only ranks reported values without units.
How To Create A Leaderboard?
Leaderboards are created on the console. For this, firstly log-in Huawei AGC Console.
Select “My Apps” -> Your App Name -> “Operate” -> “Leaderboards”
In this page, you can see your leaderboards and you can create a new leaderboard by clicking “Create” button.
After clicked “Create” button, you will see leaderboard detail page. In this page you should give some information for your leaderboard. So, an leaderboard should contain the following basic attributes:
Leaderboard ID: A unique string generated by AppGallery Connect to identify a leaderboard.
Leaderboard Name: Name of a leaderboard. How to name a leaderboard is up to you.
Score: Score of a player on a leaderboard. Scores can only be uploaded by Game Service APIs upon score changes, but cannot be directly defined during leaderboard creation.
Custom Unit: For a numeric leaderboard, you can customize a unit for numbers, for example, meter or kilometer.
Icon: Icon associated with a leaderboard. The icon must be of the resolution 512 x 512 px, and in PNG or JPG format. Avoid using any texts that need to be localized in the icon.
Ordering Mode: Ordering mode of leaderboard entries. You can define whether a larger or smaller score is better. Once a leaderboard is released, the mode cannot be modified.
Limits: Lower and upper limits of scores allowed by a leaderboard. The setting can help discard scores that are clearly fraudulent. Once a leaderboard is released, the limits cannot be modified.
List Order: Order of a leaderboard among all leaderboards. You need to set this attribute when creating a leaderboard.
Multi-Language: Multi-language information of a leaderboard. You can define what languages your game supports when creating a leaderboard. You need to define the leaderboard name and custom unit (if defined) in each supported language.
Score Format: You can define the score format as any of the following when creating a leaderboard:
Currency: Displays scores in a currency format. A score value represents a currency amount.
Time: Displays scores in a time format.
Numeric: Displays scores as numbers. You can customize a unit for them.
After type all of the necessary information, click the “Save” button and save. After saving, you will be see again Leaderboards list. And you have to click “Release” button for start to using your leaderboard. Also, you can edit and see details of leaderboards in this page. But you must wait 1–2 days for the leaderboards to be approved. You can login the game with your developer account and test it until it is approved. But it must wait for approval before other users can view the leaderboards.
Displaying Scores
1. Create Score List (Leaderboard) Page
Firstly, create a Xml file, and add recyclerView to list all of the leaders. You can find my design in the below.
XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="70dp"
android:id="@+id/relativeLay">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Leadership"
android:textSize="25dp"
android:textAllCaps="false"
android:gravity="center"
android:textColor="#9A9A9B"
android:fontFamily="@font/muli_regular"
android:layout_gravity="center"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="10dp"/>
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/rvFavorite"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="25dp"/>
</RelativeLayout>
Read full article.
Tips & Tricks
Remember that each leaderboard has a different ID. So, you must set the ID value of the leaderboard you want to use.
You can create diffirent leaderboards for diffirent game types.
Before calling archive APIs, ensure that the player has signed in.
Conclusion
Thanks to this article, you can create a Leaderboard on the console. Also, you can submit a score and list your leaders on your game app. Also, you can create a Saved Games, you can update and list your saved game details on your game app. You can see saved game detail logs on the below.
References
HMS Game Service
Read full article.
HUAWEI Location Kit provides you with the tools to build ultra-precise location services into your apps, by utilizing GNSS, Wi-Fi, base stations, and a range of cutting-edge hybrid positioning technologies. Location Kit-supported solutions give your apps a leg up in a ruthlessly competitive marketplace, making it easier than ever for you to serve a vast, global user base.
Location Kit currently offers three main functions: fused location, geofence, and activity identification. When used in conjunction with the Map SDK, which is supported in 200+ countries and regions and 100+ languages, you'll be able to bolster your apps with premium mapping services that enjoy a truly global reach.
Fused location provides easy-to-use APIs that are capable of obtaining the user's location with meticulous accuracy, and doing so while consuming a minimal amount of power. HW NLP, Huawei's exclusive network location service, makes use of crowdsourced data to achieve heightened accuracy. Such high-precision, cost-effective positioning has enormous implications for a broad array of mobile services, including ride hailing navigation, food delivery, travel, and lifestyle services, providing customers and service providers alike with the high-value, real time information that they need.
To avoid boring you with the technical details, we've provided some specific examples of how positioning systems, geofence, activity identification, map display and route planning services can be applied in the real world.
For instance, you can use Location kit to obtain the user's current location and create a 500-meter geofence radius around it, which can be used to determine the user's activity status when the geofence is triggered, then automatically plan a route based on this activity status (for example, plan a walking route when the activity is identified as walking), and have it shown on the map.
This article addresses the following functions:
Fused location: Incorporates GNSS, Wi-Fi, and base station data via easy-to-use APIs, making it easy for your app to obtain device location information.
Activity identification: Identifies the user's motion status, using the acceleration sensor, network information, and magnetometer, so that you can tailor your app to account for the user's behavior.
Geofence: Allows you to set virtual geographic boundaries via APIs, to send out timely notifications when users enter, exit, or remain with the boundaries.
Map display: Includes the map display, interactive features, map drawing, custom map styles, and a range of other features.
Route planning: Provides HTTP/HTTPS APIs for you to initiate requests using HTTP/HTTPS, and obtain the returned data in JSON format.
Usage scenarios:
Using high-precision positioning technology to obtain real time location and tracking data for delivery or logistics personnel, for optimally efficient services. In the event of accidents or emergencies, the location of personnel could also be obtained with ease, to ensure their quick rescue.
Creating a geofence in the system, which can be used to monitor an important or dangerous area at all times. If someone enters such an area without authorization, the system could send out a proactive alert. This solution can also be linked with onsite video surveillance equipment. When an alert is triggered, the video surveillance camera could pop up to provide continual monitoring, free of any blind spots.
Tracking patients with special needs in hospitals and elderly residents in nursing homes, in order to provide them with the best possible care. Positioning services could be linked with wearable devices, for attentive 24/7 care in real time.
Using the map to directly find destinations, and perform automatic route planning.
I. Advantages of Location Kit and Map Kit
Low-power consumption (Location Kit): Implements geofence using the chipset, for optimized power efficiency
High precision (Location Kit): Optimizes positioning accuracy in urban canyons, correctly identifying the roadside of the user. Sub-meter positioning accuracy in open areas, with RTK (Real-time kinematic) technology support. Personal information, activity identification, and other data are not uploaded to the server while location services are performed. As the data processor, Location Kit only uses data, and does not store it.
Personalized map displays (Map Kit): Offers enriching map elements and a wide range of interactive methods for building your map.
Broad-ranging place searches (Map Kit): Covers 130+ million POIs and 150+ million addresses, and supports place input prompts.
Global coverage: Supports 200+ countries/regions, and 40+ languages.
For more information and development guides, please visit: https://developer.huawei.com/consumer/en/hms/huawei-MapKit
II. Demo App Introduction
In order to illustrate how to integrate Location Kit and Map Kit both easily and efficiently, we've provided a case study here, which shows the simplest coding method for running the demo.
This app is used to create a geofence on the map based on the location when the user opens the app. The user can drag on the red mark to set a destination. After being confirmed, when the user triggers the geofence condition, the app will automatically detect their activity status and plan a route for the user, such as planning a walking route if the activity status is walking, or cycling route if the activity status is cycling. You can also implement real-time voice navigation for the planned route.
III. Development Practice
You need to set the priority (which is 100 by default) before requesting locations. To request the precise GPS location, set the priority to 100. To request the network location, set the priority to 102 or 104. If you only need to passively receive locations, set the priority to 105.
Parameters related to activity identification include VEHICLE (100), BIKE (101), FOOT (102), and STILL (103).
Geofence-related parameters include ENTER_GEOFENCE_CONVERSION (1), EXIT_GEOFENCE_CONVERSION (2), and DWELL_GEOFENCE_CONVERSION (4).
The following describes how to run the demo using source code, helping you understand the implementation details.
Preparations
Preparing Tools
Huawei phones (It is recommended that multiple devices be tested)
Android Studio
2.Registering as a Developer
Register as a Huawei developer.
Create an app in AppGallery Connect.
Create an app in AppGallery Connect by referring to Location Kit development preparations or Map Kit development preparations.
Enable Location Kit and Map Kit for the app on the Manage APIs page.
Add the SHA-256 certificate fingerprint.
Download the agconnect-services.json file and add it to the app directory of the project.
Create an Android demo project.
Learn about the function restrictions.
To use the route planning function of Map Kit, refer to Supported Countries/Regions (Route Planning).
To use other services of Map Kit, refer to Supported Countries/Regions.
Device TypeFeatureOS VersionHMS Core (APK) VersionHuawei phonesFused locationEMUI 5.0 or later4.0.0 or laterGeofenceEMUI 8.0 or later4.0.4 or laterActivity identificationEMUI 9.1.1 or later3.0.2 or laterNon-Huawei Android phonesFused locationAndroid 8.0 or later (API level 26 or higher)4.0.1 or laterGeofenceAndroid 5.0 or later (API level 21 or higher)4.0.4 or laterActivity identificationNot supportedNot supported
Running the Demo App
Install the app on the test device after debugging the project in Android Studio successfully
Replace the project package name and JSON file with those of your own.
Tap related button in the demo app to create a geofence which has a radius of 200 and is centered on the current location automatically pinpointed by the demo app.
Drag the mark point on the map to select a destination.
View the route that is automatically planned based on the current activity status when the geofence is triggered.
The following figure shows the demo effect:
{
"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"
}
Key Steps
Add the Huawei Maven repository to the project-level build.gradle file.
Add the following Maven repository address to the project-level build.gradle file of your Android Studio project:
Code:
buildscript {
repositories {
maven { url 'http://developer.huawei.com/repo/'}
}
dependencies {
...
// Add the AppGallery Connect plugin configuration.
classpath 'com.huawei.agconnect:agcp:1.4.2.300'
}
}allprojects {
repositories {
maven { url 'http://developer.huawei.com/repo/'}
}
}
Add dependencies on the SDKs in the app-level build.gradle file.
Code:
dependencies {
implementation 'com.huawei.hms:location:5.1.0.300'
implementation 'com.huawei.hms:maps:5.2.0.302' }
3. Add the following configuration to the next line under apply plugin: 'com.android.application' in the file header:
apply plugin: 'com.huawei.agconnect'
Note:
You must configure apply plugin: 'com.huawei.agconnect' under apply plugin: 'com.android.application'.
The minimum Android API level (minSdkVersion) required for the HMS Core Map SDK is 19.
4. Declare system permissions in the AndroidManifest.xml file.
Location Kit uses GNSS, Wi-Fi, and base station data for fused location, enabling your app to quickly and accurately obtain users' location information. Therefore, Location Kit requires permissions to access Internet, obtain the fine location, and obtain the coarse location. If your app needs to continuously obtain the location information when it runs in the background, you also need to declare the ACCESS_BACKGROUND_LOCATION permission in the AndroidManifest.xml file:
Code:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="com.huawei.hms.permission.ACTIVITY_RECOGNITION" />
<uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" />
Note: Because the ACCESS_FINE_LOCATION, WRITE_EXTERNAL_STORAGE, READ_EXTERNAL_STORAGE, and ACTIVITY_RECOGNITION permissions are dangerous system permissions, you need to dynamically apply for these permissions. If you do not have the permissions, Location Kit will reject to provide services for your app.
Key Code
I. Map Display
Currently, the Map SDK supports two map containers: SupportMapFragment and MapView. This document uses the SupportMapFragment container.
Add a Fragment object in the layout file (for example: activity_main.xml), and set map attributes in the file.
Code:
<fragment
android:id="@+id/mapfragment_routeplanningdemo"
android:name="com.huawei.hms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
To use a map in your app, implement the OnMapReadyCallback API.
RoutePlanningActivity extends AppCompatActivity implements OnMapReadyCallback
Load SupportMapView in the onCreate method, call getMapAsync to register the callback.
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.mapfragment_routeplanningdemo);
if (fragment instanceof SupportMapFragment) {
SupportMapFragment mSupportMapFragment = (SupportMapFragment) fragment;
mSupportMapFragment.getMapAsync(this);
}
Call the onMapReady callback to obtain the HuaweiMap object.
Code:
@Override
public void onMapReady(HuaweiMap huaweiMap) {
hMap = huaweiMap;
hMap.setMyLocationEnabled(true);
hMap.getUiSettings().setMyLocationButtonEnabled(true);
}
II. Function Implementation
Check the permissions.
Code:
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) {
if (ActivityCompat.checkSelfPermission(context,
"com.huawei.hms.permission.ACTIVITY_RECOGNITION") != PackageManager.PERMISSION_GRANTED) {
String[] permissions = {"com.huawei.hms.permission.ACTIVITY_RECOGNITION"};
ActivityCompat.requestPermissions((Activity) context, permissions, 1);
Log.i(TAG, "requestActivityTransitionButtonHandler: apply permission");
}
} else {
if (ActivityCompat.checkSelfPermission(context,
"android.permission.ACTIVITY_RECOGNITION") != PackageManager.PERMISSION_GRANTED) {
String[] permissions = {"android.permission.ACTIVITY_RECOGNITION"};
ActivityCompat.requestPermissions((Activity) context, permissions, 2);
Log.i(TAG, "requestActivityTransitionButtonHandler: apply permission");
}
}
Check whether the location permissions have been granted. If no, the location cannot be obtained.
Code:
settingsClient.checkLocationSettings(locationSettingsRequest)
.addOnSuccessListener(locationSettingsResponse -> {
fusedLocationProviderClient
.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.getMainLooper())
.addOnSuccessListener(aVoid -> {
//Processing when the API call is successful.
});
})
.addOnFailureListener(e -> {});
if (null == mLocationCallbacks) {
mLocationCallbacks = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult != null) {
List<HWLocation> locations = locationResult.getHWLocationList();
if (!locations.isEmpty()) {
for (HWLocation location : locations) {
hMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 14));
latLngOrigin = new LatLng(location.getLatitude(), location.getLongitude());
if (null != mMarkerOrigin) {
mMarkerOrigin.remove();
}
MarkerOptions options = new MarkerOptions()
.position(latLngOrigin)
.title("Hello Huawei Map")
.snippet("This is a snippet!");
mMarkerOrigin = hMap.addMarker(options);
removeLocationUpdatesWith();
}
}
}
}
@Override
public void onLocationAvailability(LocationAvailability locationAvailability) {
if (locationAvailability != null) {
boolean flag = locationAvailability.isLocationAvailable();
Log.i(TAG, "onLocationAvailability isLocationAvailable:" + flag);
}
}
};
}
III. Geofence and Ground Overlay Creation
Create a geofence based on the current location and add a round ground overlay on the map.
Code:
GeofenceRequest.Builder geofenceRequest = new
GeofenceRequest.Builder geofenceRequest = new GeofenceRequest.Builder();
geofenceRequest.createGeofenceList(GeoFenceData.returnList());
geofenceRequest.setInitConversions(7);
try {
geofenceService.createGeofenceList(geofenceRequest.build(), pendingIntent)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(Task<Void> task) {
if (task.isSuccessful()) {
Log.i(TAG, "add geofence success!");
if (null == hMap) {
return; }
if (null != mCircle) {
mCircle.remove();
mCircle = null;
}
mCircle = hMap.addCircle(new CircleOptions()
.center(latLngOrigin)
.radius(500)
.strokeWidth(1)
.fillColor(Color.TRANSPARENT));
} else {Log.w(TAG, "add geofence failed : " + task.getException().getMessage());}
}
});
} catch (Exception e) {
Log.i(TAG, "add geofence error:" + e.getMessage());
}
// Geofence service
Code:
<receiver
android:name=".GeoFenceBroadcastReceiver"
android:exported="true">
<intent-filter>
<action android:name=".GeoFenceBroadcastReceiver.ACTION_PROCESS_LOCATION" />
</intent-filter>
</receiver>
if (intent != null) {
final String action = intent.getAction();
if (ACTION_PROCESS_LOCATION.equals(action)) {
GeofenceData geofenceData = GeofenceData.getDataFromIntent(intent);
if (geofenceData != null && isListenGeofence) {
int conversion = geofenceData.getConversion();
MainActivity.setGeofenceData(conversion);
}
}
}
Mark the selected point on the map to obtain the destination information, check the current activity status, and plan routes based on the detected activity status.
Code:
hMap.setOnMapClickListener(latLng -> {
latLngDestination = new LatLng(latLng.latitude, latLng.longitude);
if (null != mMarkerDestination) {
mMarkerDestination.remove();
}
MarkerOptions options = new MarkerOptions()
.position(latLngDestination)
.title("Hello Huawei Map");
mMarkerDestination = hMap.addMarker(options);
if (identification.getText().equals("To exit the fence,Your activity is about to be detected.")) {
requestActivityUpdates(5000);
}
});
// Activity identification API
activityIdentificationService.createActivityIdentificationUpdates(detectionIntervalMillis, pendingIntent)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Log.i(TAG, "createActivityIdentificationUpdates onSuccess");
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
Log.e(TAG, "createActivityIdentificationUpdates onFailure:" + e.getMessage());
}
});
// URL of the route planning API (cycling route is used as an example): https://mapapi.cloud.huawei.com/mapApi/v1/routeService/bicycling?key=API KEY
NetworkRequestManager.getBicyclingRoutePlanningResult(latLngOrigin, latLngDestination,
new NetworkRequestManager.OnNetworkListener() {
@Override
public void requestSuccess(String result) {
generateRoute(result);
}
@Override
public void requestFail(String errorMsg) {
Message msg = Message.obtain();
Bundle bundle = new Bundle();
bundle.putString("errorMsg", errorMsg);
msg.what = 1;
msg.setData(bundle);
mHandler.sendMessage(msg);
}
});
Note:
The route planning function provides a set of HTTPS-based APIs used to plan routes for walking, cycling, and driving and calculate route distances. The APIs return route data in JSON format and provide the route planning capabilities.
The route planning function can plan walking, cycling, and driving routes.
You can try to plan a route from one point to another point and then draw the route on the map, achieving the navigation effects.
Related Parameters
In indoor environments, the navigation satellite signals are usually weak. Therefore, HMS Core (APK) will use the network location mode, which is relatively slow compared with the GNSS location. It is recommended that the test be performed outdoors.
In Android 9.0 or later, you are advised to test the geofence outdoors. In versions earlier than Android 9.0, you can test the geofence indoors.
Map Kit is unavailable in the Chinese mainland. Therefore, the Android SDK, JavaScript API, Static Map API, and Directions API are unavailable in the Chinese mainland. For details, please refer to Supported Countries/Regions.
In the Map SDK for Android 5.0.0.300 and later versions, you must set the API key before initializing a map. Otherwise, no map data will be displayed.
Currently, the driving route planning is unavailable in some countries and regions outside China. For details about the supported countries and regions, please refer to the Huawei official website.
Before building the APK, configure the obfuscation configuration file to prevent the HMS Core SDK from being obfuscated.
Open the obfuscation configuration file proguard-rules.pro in the app's root directory of your project and add configurations to exclude the HMS Core SDK from obfuscation.
If you are using AndResGuard, add its trustlist to the obfuscation configuration file.
For details, please visit the following link: https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/android-sdk-config-obfuscation-scripts-0000001061882229
To learn more, visit the following links:
Documentation on the HUAWEI Developers website:
https://developer.huawei.com/consumer/en/hms/huawei-locationkit
https://developer.huawei.com/consumer/en/hms/huawei-MapKit
To download the demo and sample code, please visit GitHub.
To solve integration problems, please go to Stack Overflow at the following link:
https://stackoverflow.com/questions/tagged/huawei-mobile-services?tab=Newest
To learn more, please visit:
HUAWEI Developers official website
Development Guide
Reddit to join developer discussions
GitHub or Gitee to download the demo and sample code
Stack Overflow to solve integration problems
Follow our official account for the latest HMS Core-related news and updates.
Original Source
Can we get the location offline?