Introduction
In my last article, I have explained how to integrate an account kit finance application. Have a look into Pygmy collection application Part 1 (Account kit).
In this article, we will learn how to integrate Analytics kit kit in Pygmy collection finance application.
Adding Events with Huawei Analytics Kit
This guide walks you through the process of building application that uses Huawei Analytics Kit to trigger event and can find data on the console.
What You Will Build
You will build an application that triggers events, setting user properties, logging custom event etc.
What You Need
About 10 minutes
A favorite text editor or IDE(For me Android Studio)
JDK 1.8 or later
Gradle 4+
SDK platform 19
What is Mobile analytics?
Mobile analytics captures data from mobile app, website, and web app visitors to identify unique users, track their journeys, record their behaviour, and report on the app’s performance. Similar to traditional web analytics, mobile analytics are used to improve conversions, and are the key to crafting world-class mobile experiences.
How to complete this guide
When a person says that I know theoretical concept, only when he/she knows the answer for all WH questions. To complete this guide, lets understand all WH questions.
1. Who has to use analytics?
2. Which one to use?
3. What is Huawei Analytics kit?
4. When to use HMS Analytics kit?
5. Why to use analytics kit?
6. Where to use analytics Kit?
Once you get answer for all the above questions, then you will get theoretical knowledge. But to understand with result you should know answer for below question.
1. How to integrate Huawei analytics kit?
Who has to use the analytics kit?
The answer is very simple, the analytics kit will be used in the mobile/web application. So off course software developer has to use analytics kit.
Which one to use?
Since there are many analytics vendors in the market. But for mobile application I recommend Huawei analytics kit. Now definitely you will have question why? To answer this I’ll give some reasons.
Very easy to integrate.
Documentation is too good.
Community is too good. Response from community is so fast.
Moreover, it is very similar to other vendors, so no need to learn new things.
You can see events in real time.
What is Huawei Analytics kit?
Flutter Analytics plugin enables the communication between HMS Core analytics SDK and Flutter platform. This plugin exposed all the functionality which is provided by HMS core analytics SDK.
Huawei Analytics kit offers you a range of analytics models that helps you to analyse the users’ behaviour with predefined and custom events, you can gain a deeper insight into your users, products and content. It helps you to gain insight into that how users behave on different platforms based on the user behaviour events and user attributes reported through apps.
Huawei Analytics kit, our one-stop analytics platform provides developers with intelligent, convenient and powerful analytics capabilities, using this we can optimize apps performance and identify marketing channels.
Collect and report custom events.
Set a maximum of 25 user attributes.
Automate event collection and session calculation.
Preset event IDs and parameters.
When to use HMS Analytics kit?
Mobile app analytics are a developer’s best friend. It helps you gain understanding about that how users’ behaviour and app can be optimized to reach your goals. Without mobile app analytics, you would be trying out different things blindly without any data to back up your experiments.
That’s why it’s extremely important for developers to understand their mobile app analytics to track their progress while working towards achieving their goals.
Why to use analytics kit?
Mobile app analytics are essential to development process for many reasons. They give you insights into that how users are using your app, which parts of the app they interact with, and what actions they take within the app. You can use these insights to come up with an action plan to improve your product in future, like adding new features that the users seem to need, or improve existing ones in a way that would make the users lives easier, or removing features that the users don’t seem to use.
You’ll also gain insights into whether you’re achieving your goals for your mobile app, whether its revenue, awareness, or other KPIs, and then take the data you have to adjust your strategy and optimize your app to reach your further goals.
When it comes to why? Always everyone thinks about benefits.
Benefits of Analytics
App analytics helps you to drive ROI over every aspect of performance.
App analytics helps you to gather accurate data to better serve for customers.
App analytics allows you to drive personalized and customer-focused marketing.
App analytics allowss you to track individual and group achievements of marketing goals from campaigns.
App analytics offers data-driven insights into issues concerning churn and retention.
Where to use analytics Kit?
This is very important question, because you already know why to use the analytics kit. So wherever you want understand about user behaviour, which part of the application users are using regularly, which functionality of the application users are using more. In the scenario you can use analytics kit in either mobile/web application you can use the analytics kit.
Now start with practical
Till now you understood theoretical concept of the analytics kit. Now let’s start with the practical example, to understand about practical we should get answer for the below question.
How to integrate Huawei analytics kit in Android finance application?
To achieve this you need to follow couple of steps as follows.
1. Configure application on the AGC.
2. Client application development process.
Configure application on the AGC
Follow the steps.
Step 1: We need to register as a developer account in AppGallery Connect. If you are already developer ignore this step.
Step 2: Create an app by referring to Creating a Project and Creating an App in the Project
Step 3: Set the data storage location based on current location.
Step 4: Enabling Analytics Kit. Project setting > Manage API > Enable analytics kit toggle button.
Step 5: Generating a Signing Certificate Fingerprint.
Step 6: Configuring the Signing Certificate Fingerprint.
Step 7: Download your agconnect-services.json file, paste it into the app root directory.
Client application development process
Follow the steps.
Step 1: Create Android application in the Android studio (Any IDE which is your favorite)
Step 2: Add the App level gradle dependencies. Choose inside project Android > app > build.gradle.
How to integrate Ads Kit
1. Configure the application on the AGC.
2. Client application development process.
3. Testing a Splash Ad.
Client application development process
Follow the steps.
Step 1: Create an Android application in the Android studio (Any IDE which is your favorite).
Step 2: Add the App level Gradle dependencies. Choose inside project Android > app > build.gradle.
Code:
apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect'
dependencies {
implementation 'com.huawei.hms:hianalytics:5.1.0.300'
}
Root level gradle dependencies.
Code:
maven { url 'https://developer.huawei.com/repo/' }
classpath 'com.huawei.agconnect:agcp:1.4.1.300'
Step 3: To allow HTTP and HTTPS network requests on devices with targetSdkVersion 28 or later, configure the following information in the AndroidManifest.xml file:
XML:
<application
...
android:usesCleartextTraffic="true"
>
...
</application>
Step 4: Initialize Ads kit activity or application class.
Step 5: Build Application.
HuaweiUserProperty.java
Java:
public class HuaweiUserProperty {
public enum KeyName {
USER_CUSTOMER_ID("user_session_id"),
USER_PHONE_NUMBER("user_phone_number");
String textValue;
KeyName(String textValue) {
this.textValue = textValue;
}
public String textValue() {
return textValue;
}
}
}
HuaweiEvenParams.java
Java:
public enum HuaweiEventParams {
temp;
public enum EventName {
TAP("tap"),
OPEN("open");
String textValue;
EventName(String textValue) {
this.textValue = textValue;
}
public String textValue() {
return textValue;
}
}
public enum Key {
PREVIOUS_SCREEN_NAME("previous_screen_name"),
SCREEN_NAME("screen_name"),
UI_ELEMENT("ui_element_name"),
DESCRIPTION("description_key"),
PARENT_SCREEN_NAME("parent_screen_name"),
CUSTOMER_ID("customer_id"),
MODEL_NUMBER("model_number");
String textValue;
Key() {
}
Key(String textValue) {
this.textValue = textValue;
}
String textValue() {
return this.textValue;
}
}
public enum ScreenName {
PLATFORM_APP_LAUNCHER("platform_app_launcher"),
GRANT_PERMISSION_DIALOG_SCREEN("grant_permission_dialog_screen"),
CONFIGURATION_SCREEN("configuration_screen"),
MAIN_SPLASH("main_splash"),
LOGIN_SCREEN("login_screen"),
COLLECTION_SCREEN("collection_screen"),
PHONE_NUMBER_SCREEN("phone_number_screen"),
PHONE_CONF_POPUP("phone_number_confirmation_popup"),
OTP_SCREEN("otp_screen"),
PROFILE_POPUP("profile_popup"),
SOCIAL_MEDIA_LOGIN("social_media_login_screen"),
MAIN_HOME_DASHBOARD("main_home_dashboard"),
MAIN_HOME_NAVIGATION("main_home_navigation"),
PROFILE_SCREEN("profile_screen"),
IMAGE_SELECTION_POPUP("image_selection_popup"),
PHONE_NUMBER_POPUP("phone_number_popup"),
FEEDBACK_SCREEN("feedback_screen"),
NAVIGATION_SCREEN("navigation_screen");
String textValue;
ScreenName(String textValue) {
this.textValue = textValue;
}
String textValue() {
return this.textValue;
}
}
public enum Description {
BACKGROUND_POPUP("background_popup"),
OPEN_PHONE_NUMBER_SCREEN("open_phone_number_screen"),
OPEN_TERMS_AND_CONDITION_SCREEN("open_terms_and_condition"),
OPEN_PHONE_NUMBER_CONFIRMATION_POPUP("open_phone_number_confirmation_popup"),
OPEN_OTP_SCREEN("open_otp_screen"),
PHONE_NUMBER_SCREEN("phone_number_screen"),
OPEN_PROFILE_POPUP("open_profile_popup"),
SOCIAL_MEDIA_LOGIN_SCREEN("social_media_login_screen"),
MAIN_HOME_DASHBOARD("main_home_dashboard"),
OPEN_PROFILE_SCREEN("open_profile_screen"),
OPEN_RECONNECTION_POPUP("open_reconnection_popup"),
OPEN_MAIN_HOME_NAVIGATION("open_main_home_navigation"),
OPEN_IMAGE_SELECTION_POPUP("open_image_selection_popup"),
EDIT_PHONE_NUMBER_POPUP("edit_phone_number_popup"),
OPEN_GALLERY("open_gallery"),
OPEN_CAMERA("open_camera"),
OPEN_CONTACT_SCREEN("open_contact_screen"),
OPEN_SHARE_SCREEN("show_share_screen"),
OPEN_LOGIN_SCREEN("open_login_screen"),
OPEN_HOME_SCREEN("open_home_screen")
;
String textValue;
Description(String textValue) {
this.textValue = textValue;
}
String textValue() {
return this.textValue;
}
}
public enum UiElementName {
SWIPE_LEFT("swipe_left"),
SWIPE_RIGHT("swipe_right"),
SKIP_BUTTON("skip_button"),
NEXT_BUTTON("next_button"),
OK_BUTTON("ok_button"),
CANCEL_BUTTON("cancel_button"),
RESEND_OTP_BUTTON("resend_button"),
GALLERY_BUTTON("gallery_button"),
CATURE_FROM_CAMERA_BUTTON("cature_from_camera_button"),
DONE_BUTTON("done_button"),
COLLECTION_BUTTON("collection_button"),
GALLARY_BUTTON("gallary_button");
String textValue;
UiElementName(String textValue) {
this.textValue = textValue;
}
String textValue() {
return this.textValue;
}
}
}
HuaweiLog.java
Java:
import android.os.Bundle;
import android.util.Log;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class HuaweiLog {
private HuaweiEventParams.EventName eventName;
private HashMap<String, String> data = new HashMap<>();
private HashMap<String, ArrayList> testdata = new HashMap<>();
public HuaweiLog() {
}
public HuaweiEventParams.EventName getEventName() {
return eventName;
}
public HuaweiLog setEventName(HuaweiEventParams.EventName eventName) {
this.eventName = eventName;
return this;
}
public HuaweiLog setPreviousScreenName(HuaweiEventParams.ScreenName previousScreenName) {
data.put(HuaweiEventParams.Key.PREVIOUS_SCREEN_NAME.textValue(), previousScreenName.textValue());
return this;
}
public HuaweiLog setDescription(HuaweiEventParams.Description description) {
data.put(HuaweiEventParams.Key.DESCRIPTION.textValue(), description.textValue());
return this;
}
public HuaweiLog setDescription(String description) {
data.put(HuaweiEventParams.Key.DESCRIPTION.textValue(), description);
return this;
}
public HuaweiLog setCustomerId(String cId) {
data.put(HuaweiEventParams.Key.CUSTOMER_ID.textValue(), cId);
return this;
}
public HuaweiLog setCustomerMobileNumber(String mobileNumber) {
data.put(HuaweiEventParams.Key.CUSTOMER_ID.textValue(), mobileNumber);
return this;
}
public HuaweiLog setParentScreenName(HuaweiEventParams.ScreenName parentScreenName) {
data.put(HuaweiEventParams.Key.PARENT_SCREEN_NAME.textValue(), parentScreenName.textValue());
return this;
}
public HuaweiLog setScreenName(HuaweiEventParams.ScreenName screenName) {
data.put(HuaweiEventParams.Key.SCREEN_NAME.textValue(), screenName.textValue());
return this;
}
public HuaweiLog setScreenName(String screenName) {
data.put(HuaweiEventParams.Key.SCREEN_NAME.textValue(), screenName);
return this;
}
public HuaweiLog setUiElementName(String uiElementName) {
data.put(HuaweiEventParams.Key.UI_ELEMENT.textValue(), uiElementName);
return this;
}
public HuaweiLog setUiElementName(HuaweiEventParams.UiElementName uiElementName) {
data.put(HuaweiEventParams.Key.UI_ELEMENT.textValue(), uiElementName.textValue());
return this;
}
public HuaweiLog setKeyAndValue(String key, String value) {
data.put(key, value);
return this;
}
public Bundle toBundle() {
Bundle bundle = new Bundle();
try {
if (data != null && data.size() > 0) {
for (Map.Entry<String, String> entry : data.entrySet()) {
bundle.putString(entry.getKey(), entry.getValue());
Log.d("Huawei",entry.getKey()+" "+ entry.getValue());
}
}
} catch (Exception e) {
e.printStackTrace();
}
return bundle;
}
public HuaweiLog setTestDescription(ArrayList list) {
testdata.put(HuaweiEventParams.Key.DESCRIPTION.textValue(), list);
return this;
}
}
HuaweiAnalyticsClient.java
Java:
import android.content.Context;
import android.util.Log;
import com.huawei.hms.analytics.HiAnalytics;
import com.huawei.hms.analytics.HiAnalyticsInstance;
import com.huawei.hms.analytics.type.ReportPolicy;
import com.shea.pygmycollection.utils.UserDataUtils;
import java.util.HashSet;
import java.util.Set;
public class HuaweiAnalyticsClient {
private static final String TAG = HuaweiAnalyticsClient.class.getSimpleName();
private static HuaweiAnalyticsClient ourInstance;
private static HiAnalyticsInstance mHuaweiAnalyticsClient;
private HuaweiAnalyticsClient() {
}
public static HuaweiAnalyticsClient getInstance() {
if (ourInstance == null) {
ourInstance = new HuaweiAnalyticsClient();
}
return ourInstance;
}
public void initAnalytics(Context context) {
mHuaweiAnalyticsClient = HiAnalytics.getInstance(context);
if (mHuaweiAnalyticsClient == null) {
Log.e(TAG, "Analytics Client could not be initialized.");
return;
}
mHuaweiAnalyticsClient.setAnalyticsEnabled(true);
mHuaweiAnalyticsClient.setUserId("UserId");
mHuaweiAnalyticsClient.setAutoCollectionEnabled(true);
if (UserDataUtils.getUserData(context) != null) {
if (UserDataUtils.getUserId(context) != 0) {
Integer userId = UserDataUtils.getUserId(context);
Log.d(TAG, "initAnalytics is called");
if (userId != null && userId != 0) {
setHuaweiUserId(String.valueOf(userId));
putHuaweiUserProperty(HuaweiUserProperty.KeyName.USER_PHONE_NUMBER, UserDataUtils.getUserPhoneNumber(context));
} else {
setHuaweiUserId("UNKNOWN");
putHuaweiUserProperty(HuaweiUserProperty.KeyName.USER_PHONE_NUMBER, UserDataUtils.getUserPhoneNumber(context));
}
} else {
setHuaweiUserId("UNKNOWN_USER");
putHuaweiUserProperty(HuaweiUserProperty.KeyName.USER_PHONE_NUMBER, UserDataUtils.getUserPhoneNumber(context));
}
}
// Used to report an event upon app switching to the background.
ReportPolicy moveBackgroundPolicy = ReportPolicy.ON_MOVE_BACKGROUND_POLICY;
// Used to report an event at the specified interval.
ReportPolicy scheduledTimePolicy = ReportPolicy.ON_SCHEDULED_TIME_POLICY;
// Set the event reporting interval to 600 seconds.
scheduledTimePolicy.setThreshold(600);
Set<ReportPolicy> reportPolicies = new HashSet<>();
// Add the ON_SCHEDULED_TIME_POLICY and ON_MOVE_BACKGROUND_POLICY policies.
reportPolicies.add(scheduledTimePolicy);
reportPolicies.add(moveBackgroundPolicy);
// Set the ON_MOVE_BACKGROUND_POLICY and ON_SCHEDULED_TIME_POLICY policies.
mHuaweiAnalyticsClient.setReportPolicies(reportPolicies);
}
public void logEvent(HuaweiLog log) {
if (mHuaweiAnalyticsClient == null) {
throw new RuntimeException("HuaweiAnalyticsClient is not initialized. Please call initAnalytics().");
}
try {
mHuaweiAnalyticsClient.onEvent(log.getEventName().textValue(), log.toBundle());
Log.d("Huawei", log.getEventName().textValue());
} catch (Exception e) {
Log.d(TAG, "Huawei analytics failed" + e.getMessage());
}
}
public void putHuaweiUserProperty(HuaweiUserProperty.KeyName propertyKey, String value) {
if (mHuaweiAnalyticsClient == null) {
throw new RuntimeException("HuaweiAnalyticsClient is not initialized. Please call initAnalytics().");
}
try {
mHuaweiAnalyticsClient.setUserProfile(propertyKey.textValue(), value);
} catch (Exception e) {
Log.d(TAG, "Huawei analytics failed", e);
}
}
public void setHuaweiUserId(String userId) {
if (mHuaweiAnalyticsClient == null) {
throw new RuntimeException("HuaweiAnalyticsClient is not initialized. Please call initAnalytics().");
}
if (userId == null) {
mHuaweiAnalyticsClient.setUserId(null);
return;
}
mHuaweiAnalyticsClient.setUserId(userId);
}
}
AnalyticsUtils.java
Java:
import android.util.Log;
public class AnalyticUtils {
private static final String TAG = AnalyticUtils.class.getSimpleName();
public static void logHuaweiAnalyticEvent(HuaweiLog huaweiLog) {
try {
HuaweiAnalyticsClient.getInstance().logEvent(huaweiLog);
Log.d(TAG, "Huawei analytics " + huaweiLog.toString());
} catch (Exception e) {
Log.d(TAG, "Huawei analytics failed");
}
}
}
Now log the events in activity/fragments/dialog
Java:
AnalyticUtils.logHuaweiAnalyticEvent(new HuaweiLog()
.setScreenName(HuaweiEventParams.ScreenName.MAIN_SPLASH)
.setDescription(HuaweiEventParams.Description.OPEN_SHARE_SCREEN)
.setEventName(HuaweiEventParams.EventName.OPEN)
.setUiElementName(HuaweiEventParams.UiElementName.GALLARY_BUTTON)
);
Java:
AnalyticUtils.logHuaweiAnalyticEvent(new HuaweiLog()
.setScreenName(HuaweiEventParams.ScreenName.COLLECTION_SCREEN)
.setDescription(HuaweiEventParams.Description.OPEN_HOME_SCREEN)
.setEventName(HuaweiEventParams.EventName.TAP)
.setUiElementName(HuaweiEventParams.UiElementName.COLLECTION_BUTTON)
);
Result
{
"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"
}
Tips and Tricks
Make sure you added agconnect-service.json file.
Add internet permission in AndroidManifest.xml
Add the below code to download the HMS core apk
XML:
<application ...>
<meta-data
android:name="com.huawei.hms.client.channel.androidMarket"
android:value="false" />
...
</application>
Conclusion
In this article, we have learnt what is analytics, why to use analytics kit, where to use, how to use, how to integrate HMS analytics kit and how to add custom events.
Reference
Huawei Analytics
Thanks for sharing!!!
Related
This article is originally from HUAWEI Developer Forum
Forum link: https://forums.developer.huawei.com/forumPortal/en/home
This is all about integration of HMS Safety Detect API in the Android app using MVVM RxAndroid.
What is HMS Safety Detect API?
Ø The Safety Detect provides system integrity check (SysIntegrity), app security check (AppsCheck), malicious URL check (URLCheck), and fake user detection (UserDetect), helping you prevent security threats to your app.
{
"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"
}
Let’s create a Demo Project:
HUAWEI HMS Safety Detect integration requires the following preparations
Ø Creating an AGC Application.
Ø Creating an Android Studio Project.
Ø Generating a signature certificate.
Ø Generating a signature certificate fingerprint.
Ø Configuring the signature certificate fingerprint.
Ø Adding the application package name and save the configuration file.
Ø Configure the Maven address and AGC gradle plug-in.
Ø Configure the signature file in Android Studio.
In this article, we will implement SysIntegrity API in demo project using with RxAndroid and MVVM.
Call the API and handle responses.
Verify the certificate chain, signature, and domain name on the server.
1. Open AppGallery Console:
1. We need to create an application inside console.
2. We need to enable the Safety Detect api.
Go to Console > AppGallery Connect > My apps, click your app, and go to Develop > Manage APIs.
Now enable Safety Detect Api
Download the agconnect-services.json
Move the downloaded agconnect-services.json file to the app root directory of your Android Studio project.
We need to add HMS SDK dependency in app:gradle file
Code:
implementation 'com.huawei.hms:safetydetect:4.0.0.300'
We need to add maven dependency inside project:gradle file
Code:
maven { url 'http://developer.huawei.com/repo/' }
We need to add two more dependencies in app:gradle file
Code:
// MVVM
implementation 'androidx.lifecycle:lifecycle-extensions:2.1.0'
// RxAndroid
implementation 'io.reactivex.rxjava2:rxjava:2.2.8'
implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
Enable Data Binding
Code:
dataBinding {
enabled = true
}
2. Let’s implement api :
I have created following classes.
1. SysIntegrityDataSource : Which invoke the System Integrity Api with help of RxJava.
2. SysIntegrityViewModel : Which handle the response from System Integrity api and provide LiveData for view componets.
3. SysIntegrityFragment : Which observe the livedata from viewmodel class and set values in views such as textviews and button.
Note: If you are not familiar with MVVM or RxAndroid then I would like to suggest you to please go through my following articles:
· Android MyShows App — Rxandroid MVVM LiveData ViewModel DataBinding, Networking with Retrofit, Gson & Glide — Series
· Demystifying Data Binding — Android Jetpack — Series
Let’s see the implementation of SysIntegrityDataSource.java class.
Code:
public class SysIntegrityDataSource {
private static final String APP_ID = "XXXXXXXX";
private Context context;
public SysIntegrityDataSource(Context context) {
this.context = context;
}
public Single<SysIntegrityResp> executeSystemIntegrity() {
return Single.create(this::invokeSysIntegrity);
}
private void invokeSysIntegrity(SingleEmitter<SysIntegrityResp> emitter) {
byte[] nonce = ("Sample" + System.currentTimeMillis()).getBytes();
SafetyDetect.getClient(context)
.sysIntegrity(nonce, APP_ID)
.addOnSuccessListener(emitter::onSuccess)
.addOnFailureListener(emitter::onError);
}
}
invokeSysIntegrity() : This method invoke the System Integrity api and emit the data onSuccess/OnError and past it to Single<SysIntegrityResp> observable.
executeSystemIntegrity() : This method will create Single observable and return the response from invokeSysIntegrity() method.
3. Let’s implement ViewModel :
I have created SysIntegrityViewModel.java class.
Code:
public class SysIntegrityViewModel extends AndroidViewModel {
private final CompositeDisposable disposables = new CompositeDisposable();
private SysIntegrityDataSource sysIntegrityDataSource;
private MutableLiveData<SysIntegrityResp> systemIntegrityLiveData;
private MutableLiveData<String> error;
public SysIntegrityViewModel(Application app) {
super(app);
sysIntegrityDataSource = new SysIntegrityDataSource(app.getBaseContext());
systemIntegrityLiveData = new MutableLiveData<>();
error = new MutableLiveData<>();
}
public LiveData<SysIntegrityResp> observerSystemIntegrity() {
sysIntegrityDataSource.executeSystemIntegrity()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new SingleObserver<SysIntegrityResp>() {
@Override
public void onSubscribe(Disposable d) {
disposables.add(d);
}
@Override
public void onSuccess(SysIntegrityResp response) {
systemIntegrityLiveData.setValue(response);
}
@Override
public void onError(Throwable e) {
error.setValue(e.getMessage());
}
});
return systemIntegrityLiveData;
}
public LiveData<String> getError() {
return error;
}
@Override
protected void onCleared() {
disposables.clear();
}
}
MutableLiveData<SysIntegrityResp> systemintegrityLiveData: This field which provide the live data and return the value from viewmodel to fragment class.
observerSysIntegrity() : Which observe RxAndroid’s Single(observable) on main thread and set the value in systemIntegrityLiveData. If we got error while observing it will post the error in MutableLiveData<String> error.
4. Let’s implement Fragment :
I have created SysIntegrityFragment.java class Which obaserve the System Integrity api’s reponse and set the values in views.
Code:
public class SysIntegrityFragment extends Fragment {
private SysIntegrityViewModel sysIntegrityViewModel;
private FragmentSysBinding sysBinding;
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
sysBinding=DataBindingUtil.inflate(inflater, R.layout.fragment_sys, container, false);
sysIntegrityViewModel = ViewModelProviders.of(this).get(SysIntegrityViewModel.class);
sysBinding.btnSys.setOnClickListener(v->{
processView();
sysIntegrityViewModel.observerSystemIntegrity().observe(getViewLifecycleOwner(), this::setSystemIntegrity);
sysIntegrityViewModel.getError().observe(getViewLifecycleOwner(),this::showError);
});
return sysBinding.getRoot();
}
private void setSystemIntegrity(SysIntegrityResp response){
String jwsStr = response.getResult();
String[] jwsSplit = jwsStr.split("\\.");
String jwsPayloadStr = jwsSplit[1];
String payloadDetail = new String(Base64.decode(jwsPayloadStr.getBytes(), Base64.URL_SAFE));
try {
final JSONObject jsonObject = new JSONObject(payloadDetail);
final boolean basicIntegrity = jsonObject.getBoolean("basicIntegrity");
sysBinding.btnSys.setBackgroundResource(basicIntegrity ? R.drawable.btn_round_green : R.drawable.btn_round_red);
sysBinding.btnSys.setText(R.string.rerun);
String isBasicIntegrity = String.valueOf(basicIntegrity);
String basicIntegrityResult = "Basic Integrity: " + isBasicIntegrity;
sysBinding.txtBasicIntegrityTitle.setText(basicIntegrityResult);
if (!basicIntegrity) {
String advice = "Advice: " + jsonObject.getString("advice");
sysBinding.txtPayloadAdvice.setText(advice);
}
} catch (JSONException e) {
}
}
private void showError(String error){
Toast.makeText(getActivity().getApplicationContext(), error, Toast.LENGTH_SHORT).show();
sysBinding.btnSys.setBackgroundResource(R.drawable.btn_round_yellow);
sysBinding.btnSys.setText(R.string.rerun);
}
private void processView() {
sysBinding.txtBasicIntegrityTitle.setText("");
sysBinding.txtPayloadBasicIntegrity.setText("");
sysBinding.btnSys.setText(R.string.processing);
sysBinding.btnSys.setBackgroundResource(R.drawable.btn_round_processing);
}
}
We have instantiated instance of view model using ViewModel factory method.
We will consume the response on button click’s event.
If we got success response then we will display inside textviews and button otherwise we will show the error toast.
5. Let’s see the result:
Build the app and hit run button.
Click > RunDetection Case 1: Success Case 2: SDK Error Case 3: Integrity false (Rooted)
I hope you have learnt something new today. If you have any query regarding this article, please feel free to post any comments.
Any questions about this, you can try to acquire answers from HUAWEI Developer Forum.
Useful sharing,thanks
Thank you so much for sharing, very useful.
Thank you so much for sharing, very useful.
Thank you so much for sharing, very useful.
Does it work offline?
useful sharing,thanks!
Introduction
This article provides information to book any trip using Trip Booking Android app. It provides a solution for HMS based multiple kits such as Account Kit, Huawei Ads, Huawei Map Direction Polyline API, Huawei Location, Huawei Map, Huawei Awareness Weather API, and Huawei Analytics to use in Trip Booking.
The following HMS Kits used in this application:
1) Huawei Account Kit: Integrated this kit for login and logout.
2) Huawei Ads: Integrated this kit for better ads experiences so that users can find the better advertisements.
3) Huawei Analytics: Integrated this kit in this application for better analysis.
4) Huawei Map: Integrated this kit for better real time experience of trip booking so that user can identify the location of trip on map.
5) Huawei Direction API: Integrated this API for better trip booking experience such as users can identify the trip direction from his/her location on map.
6) Huawei Awareness Weather API: Integrated this API for weather forecast of trip.
7) Huawei Location: Integrated this Kit to get current location of user so that users can identify from current location to desire trip location.
Note: Refer to the previous articles.
1) Explore the world Trip Booking App, Part-1 login with Huawei ID
2) Explore the world Trip Booking App, Part-2 Ads and Analytics
3) Explore the world Trip Booking App, Part-3 Map and direction API
Prerequisite
1. A computer (desktop or laptop)
2. A Huawei phone, which is used to debug the developed app
3. HUAWEI Analytics Kit 5.0.3.
4. Android SDK applicable to devices using Android API-Level 19 (Android 4.4 KitKat) or higher.
5. Android Studio
6. Java JDK 1.7 or later (JDK 1.8 recommended).
Things Need To Be Done
To integrate HUAWEI HMS Core services, you must complete the following preparations:
1. Create an app in AppGallery Connect.
2. Create an Android Studio project.
3. Add the app package name and save the configuration file.
4. Configure the Maven repository address and AppGallery Connect gradle plug-in.
Weather Awareness API
HUAWEI Awareness Kit provides your app with the ability to obtain contextual information including users' current time, location, behavior, audio device status, ambient light, weather, and nearby beacons. Your app can gain insight into a user's current situation more efficiently, making it possible to deliver a smarter, more considerate user experience.
Integration process
1) Assigning Permissions in the Manifest File
2) Importing API Classes
3) Developing Capabilities
1) Assigning Permissions in the Manifest File
Before calling the weather awareness capability, assign required permissions in the manifest file.
Code:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
2) Importing API Classes
To use the weather awareness capability, you need to import the public capability classes of Awareness Kit, and also the weather-related classes.
Code:
import com.huawei.hmf.tasks.OnFailureListener;import com.huawei.hmf.tasks.OnSuccessListener;import com.huawei.hms.kit.awareness.Awareness;
import com.huawei.hms.kit.awareness.status.WeatherStatus;
import com.huawei.hms.kit.awareness.status.weather.Situation;
import com.huawei.hms.kit.awareness.status.weather.WeatherSituation;
3) Developing Capabilities
Obtain the Capture Client object of Awareness Kit.
Code:
public class AwarenessWeather {
private static final String TAG = AwarenessWeather.class.getName();
public CurrentWeather.Current getWeatherSituation(Context context) {
CurrentWeather.Current current = new CurrentWeather().new Current();
Awareness.getCaptureClient(context).getWeatherByDevice()
.addOnSuccessListener(weatherStatusResponse -> {
WeatherStatus weatherStatus = weatherStatusResponse.getWeatherStatus();
WeatherSituation weatherSituation = weatherStatus.getWeatherSituation();
Situation situation = weatherSituation.getSituation();
String weatherInfoStr =
"Time Zone : " + (weatherSituation.getCity().getTimeZone()) + "\n\n" +
"Weather id : " + situation.getWeatherId() + "\n\n" +
"Temperature : " + situation.getTemperatureC() + "℃" +
"/" + situation.getTemperatureF() + "℉" + "\n\n" +
"Wind speed : " + situation.getWindSpeed() + "km/h" + "\n\n" +
"Wind direction : " + situation.getWindDir() + "\n\n" +
"Humidity : " + situation.getHumidity() + "%";
Log.i(TAG, weatherInfoStr);
current.setObservationTime("Day");
current.setTemperature(Math.toIntExact(situation.getTemperatureC()));
current.setIsDay(url);
})
.addOnFailureListener(e -> {
Log.e(TAG, "get weather failed");
});
return current;
}
}
Location Kit
HUAWEI Location Kit combines the GNSS, Wi-Fi, and base station location functionalities into your app to build up global positioning capabilities, allows you to provide flexible location-based services targeted at users around the globe. Currently, it provides three main capabilities: Fused location, Activity identification, and Geofence. You can call one or more of these capabilities as required.
1) Fused location: Provides a set of simple and easy-to-use APIs for your app to quickly obtain the device location based on the GNSS, Wi-Fi, and base station location data.
2) Activity identification: Identifies user motion status through the acceleration sensor, cellular network information, and magnetometer, help to adapt the app to user behavior.
3) Geofence: Allows you to set an interesting area through an API so that your app can receive a notification when a specified action (such as leaving, entering, or staying in the area) occurs.
Integration process
1) Add following dependency in Gradle File.
Code:
implementation 'com.huawei.hms:location:5.0.2.301
2) Assigning App Permissions.
Apply for location 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" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"/>
3) Creating a Location Service Client.
Create a FusedLocationProviderClient instance using the onCreate() method of Activity and use the instance to call location-related APIs.
Code:
private FusedLocationProviderClient fusedLocationProviderClient;
private LocationRequest mLocationRequest;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
}
4) Check permission.
Code:
// check location permisiion
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) {
Log.i(TAG, "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 {
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);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1) {
if (grantResults.length > 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED
&& grantResults[1] == PackageManager.PERMISSION_GRANTED) {
Log.i(TAG, "onRequestPermissionsResult: apply LOCATION PERMISSION successful");
} else {
Log.i(TAG, "onRequestPermissionsResult: apply LOCATION PERMISSSION failed");
}
}
if (requestCode == 2) {
if (grantResults.length > 2 && grantResults[2] == PackageManager.PERMISSION_GRANTED
&& grantResults[0] == PackageManager.PERMISSION_GRANTED
&& grantResults[1] == PackageManager.PERMISSION_GRANTED) {
Log.i(TAG, "onRequestPermissionsResult: apply ACCESS_BACKGROUND_LOCATION successful");
} else {
Log.i(TAG, "onRequestPermissionsResult: apply ACCESS_BACKGROUND_LOCATION failed");
}
}
}
Huawei Map Direction API
Huawei Map provides Direction API so that user can access all the information related to Map in RESTful API.
Huawei has provided the following API endpoint to access Direction API.
https://mapapi.cloud.huawei.com/mapApi/v1
Huawei provides the following direction API:
1. Walking Route Planning
2. Bicycling Route Planning
3. Driving Route Planning
Implemented the Driving Route API with the help of Retrofit and MVVM.
Retrofit Client
Created MapApiClient class for accessing the Direction API.
Code:
public class MapApiClient {
private final static HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
private static OkHttpClient okHttpClient;
public static Service getClient() {
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
interceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
interceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS);
if (okHttpClient == null) {
okHttpClient = new OkHttpClient.Builder()
.addInterceptor(interceptor)
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build();
}
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Consants.BASE_URL)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build();
return retrofit.create(Service.class);
}
public interface Service {
@POST("mapApi/v1/routeService/driving")
Single<PolylineResponse> getPolylines(
@Query("key") String apiKey,
@Body PolylineBody polylineBody);
}
}
API Repository
I have created MapApiRepo class for accessing the API client.
Code:
public class MapApiRepo {
private MapApiClient.Service mService;
public MapApiRepo() {
this.mService = MapApiClient.getClient();
}
public Single<PolylineResponse> executeMapApi(PolylineBody polylineBody) {
return mService.getPolylines(Consants.API_KEY, polylineBody);
}
}
ViewModel
I have created MapApiViewModel class for handling the API calls.
Code:
public class MapApiViewModel extends ViewModel {
private final CompositeDisposable disposables = new CompositeDisposable();
private MapApiRepo mapApiRepo = new MapApiRepo();
private MutableLiveData<PolylineResponse> mPolylineLiveData = new MutableLiveData<>();
public LiveData<PolylineResponse> getPolylineLiveData(PolylineBody body) {
disposables.add(mapApiRepo.executeMapApi(body)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(result -> mPolylineLiveData.setValue(result),
throwable -> mPolylineLiveData.setValue(null)
));
return mPolylineLiveData;
}
@Override
protected void onCleared() {
disposables.clear();
}
}
Drawing Polyline
I have implemented this functionality in the following activity.
Code:
mapApiViewModel.getPolylineLiveData(getPolylineBody()).observe(this, result -> {
Log.d(TAG, result.toString());
getPolylineData(result);
}); private PolylineBody getPolylineBody() {
PolylineBody polylineBody = new PolylineBody();
Origin origin = new Origin();
origin.setLat("30.0444");
origin.setLng("31.2357");
Destination destination = new Destination();
destination.setLat("30.0131");
destination.setLng("31.2089");
polylineBody.setDestination(destination);
polylineBody.setOrigin(origin);
return polylineBody;
}
public void getPolylineData(PolylineResponse polylineResponse) {
List<Routes> routesList = polylineResponse.getRoutes();
List<Paths> paths = new ArrayList<>();
List<Steps> steps = new ArrayList<>();
List<Polyline> polylines = new ArrayList<>();
latLngList = new ArrayList<>();
for (int x = 0; x < routesList.size(); x++) {
//here we can access each array list with main.get(x).
for (Paths paths1 : routesList.get(x).getPaths()) {
paths.add(paths1);
}
for (int y = 0; y < paths.size(); y++) {
for (Steps step :
paths.get(y).getSteps()) {
steps.add(step);
}
}
for (int i = 0; i < steps.size(); i++) {
for (Polyline polyline :
steps.get(i).getPolyline()) {
polylines.add(polyline);
}
}
}
for (int i = 0; i < polylines.size(); i++) {
latLngList.add(new LatLng(Double.valueOf(polylines.get(i).getLat())
, Double.valueOf(polylines.get(i).getLng())));
}
hmap.addPolyline(new PolylineOptions()
.addAll(latLngList)
.color(Color.BLUE)
.width(3));
}
App Development
Created the following package inside the project. In which integrated as Account Kit, Huawei Ads, Huawei Map Direction Polyline API, Huawei Location, Huawei Map, Huawei Awareness Weather API, and Huawei Analytics.
{
"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"
}
PolyLineActivity
In this activity, I have integrated Location kit, Map, and Direction API.
Launch the application
Let us launch our application, see the result
If you have any doubts or queries. Leave your valuable comment in the comment section and do not forget to like and follow me
Conclusion
In this article, I have explained how to integrate Location Kit and Weather Awareness in Trip Booking application and draw a route between origins to destination.
References
Driving Direction API:
https://developer.huawei.com/consumer/en/doc/development/HMSCore-References-V5/directions-driving-0000001050161496-V5
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 am going to implement HMS Location Kit & Shared Preferences.
{
"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: Location 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.
Important: While adding app, the package name you enter should be the same as your Flutter project’s package name.
Note: Before you download agconnect-services.json file, make sure the required kits are enabled.
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.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
<uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" />
<uses-permission android:name="com.huawei.hms.permission.ACTIVITY_RECOGNITION" />
<application ...
</manifest>
3. Refer below URL for cross-platform plugins. Download required plugins.
https://developer.huawei.com/consum...y-V1/flutter-sdk-download-0000001050304074-V1
4. After completing all the steps above, you need to add the required kits’ Flutter plugins as dependencies to pubspec.yaml file. You can find all the plugins in pub.dev with the latest versions.
Code:
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_location:
path: ../huawei_location/
flutter:
uses-material-design: true
assets:
- assets/images/
5. After adding them, run flutter pub get command. Now all the plugins are ready to use.
6. Open main.dart file to create UI and business logics.
Location kit
HUAWEI Location Kit assists developers in enabling their apps to get quick and accurate user locations and expand global positioning capabilities using GPS, Wi-Fi, and base station locations.
Fused location: Provides a set of simple and easy-to-use APIs for you to quickly obtain the device location based on the GPS, Wi-Fi, and base station location data.
Activity identification: Identifies user motion status through the acceleration sensor, cellular network information, and magnetometer, helping you adjust your app based on user behaviour.
Geofence: Allows you to set an interested area through an API so that your app can receive a notification when a specified action (such as leaving, entering, or lingering in the area) occurs.
Integration
Permissions
First of all we need permissions to access location and physical data.
Create a PermissionHandler instance,add initState() for initialize.
Code:
final PermissionHandler permissionHandler;
@override
void initState() {
permissionHandler = PermissionHandler(); super.initState();
}
Check Permissions
We need to check device has permission or not using hasLocationPermission() method.
Code:
void hasPermission() async {
try {
final bool status = await permissionHandler.hasLocationPermission();
if(status == true){
showToast("Has permission: $status");
}else{
requestPermission();
}
} on PlatformException catch (e) {
showToast(e.toString());
}
}
If device don’t have permission,then request for Permission to use requestLocationPermission() method.
Code:
void requestPermission() async {
try {
final bool status = await permissionHandler.requestLocationPermission();
showToast("Is permission granted");
} on PlatformException catch (e) {
showToast(e.toString());
}
}
Fused Location
Create FusedLocationPrvoiderClient instance using the init() method and use the instance to call location APIs.
Code:
final FusedLocationProviderClient locationService
@override
void initState() {
locationService = FusedLocationProviderClient(); super.initState();
}
getLastLocation()
Code:
void getLastLocation() async {
try {
Location location = await locationService.getLastLocation();
setState(() {
lastlocation = location.toString();
print("print: " + lastlocation);
});
} catch (e) {
setState(() {
print("error: " + e.toString());
});
}
}
getLastLocationWithAddress()
Create LocationRequest instance and set required parameters.
Code:
final LocationRequest locationRequest;
locationRequest = LocationRequest()
..needAddress = true
..interval = 5000;
void _getLastLocationWithAddress() async {
try {
HWLocation location =
await locationService.getLastLocationWithAddress(locationRequest);
setState(() {
String street = location.street;
String city = location.city;
String countryname = location.countryName;
currentAddress = '$street' + ',' + '$city' + ' , ' + '$countryname';
print("res: $location");
});
showToast(currentAddress);
} on PlatformException catch (e) {
showToast(e.toString());
}
}
Location Update using Call back
Create LocationCallback instance and create callback functions in initstate().
Code:
LocationCallback locationCallback;
@override
void initState() {
locationCallback = LocationCallback(
onLocationResult: _onCallbackResult,
onLocationAvailability: _onCallbackResult,
);
super.initState();
}
void requestLocationUpdatesCallback() async {
if (_callbackId == null) {
try {
final int callbackId = await locationService.requestLocationUpdatesExCb(
locationRequest, locationCallback);
_callbackId = callbackId;
} on PlatformException catch (e) {
showToast(e.toString());
}
} else {
showToast("Already requested location updates.");
}
}
void onCallbackResult(result) {
print(result.toString());
showToast(result.toString());
}
I have created Helper class to store user login information in locally using shared Preferences class.
Code:
class StorageUtil {
static StorageUtil _storageUtil;
static SharedPreferences _preferences;
static Future<StorageUtil> getInstance() async {
if (_storageUtil == null) {
var secureStorage = StorageUtil._();
await secureStorage._init();
_storageUtil = secureStorage;
}
return _storageUtil;
}
StorageUtil._();
Future _init() async {
_preferences = await SharedPreferences.getInstance();
}
// get string
static String getString(String key) {
if (_preferences == null) return null;
String result = _preferences.getString(key) ?? null;
print('result,$result');
return result;
}
// put string
static Future<void> putString(String key, String value) {
if (_preferences == null) return null;
print('result $value');
return _preferences.setString(key, value);
}
}
Result
Tips & Tricks
1. Download latest HMS Flutter plugin.
2. To work with mock location we need to add permissions in Manifest.XML.
3. Whenever you updated plugins, click on pug get.
Conclusion
We implemented simple hotel booking application using Location kit in this article. We have learned how to get Lastlocation, getLocationWithAddress and how to use callback method, in flutter how to store data into Shared Preferences in applications.
Thank you for reading and if you have enjoyed this article, I would suggest you to implement this and provide your experience.
Reference
Location Kit URL
Shared Preferences URL
Read full article
Goodjob
Thank you
I thought huawei doesn't support flutter. I guess it should as it is Android only.
good
Wow
Nice.
I thought its not doable
Interesting.
Like
Overview
In this article, I will create a demo app along with the integration of HMS Ads and Analytics Kit which is based on Cross-platform Technology Xamarin. I have implemented Ads Kit and Analytics Kit. So the developer can easily monetise their efforts using Banner, Splash, Reward and Interstitial Ads also to track the user’s behaviour through the Analytics kit.
Ads Kit Service Introduction
HMS Ads kit is powered by Huawei which allows the developer to monetization services such as Banner, Splash, Reward and Interstitial Ads. HUAWEI Ads Publisher Service is a monetization service that leverages Huawei's extensive data capabilities to display targeted, high-quality ad content in your application to the vast user base of Huawei devices.
Analytics Kit Service Introduction
Analytics kit is powered by Huawei which allows rich analytics models to help you clearly understand user behaviour and gain in-depth insights into users, products, and content. As such, you can carry out data-driven operations and make strategic decisions about app marketing and product optimization.
Analytics Kit implements the following functions using data collected from apps:
1. Provides data collection and reporting APIs for collection and reporting custom events.
2. Sets up to 25 user attributes.
3. Supports automatic event collection and session calculation as well as predefined event IDs and parameters.
Prerequisite
1. Xamarin Framework
2. Huawei phone
3. Visual Studio 2019
App Gallery Integration process
1. Sign In and Create or Choose a project on AppGallery Connect portal.
{
"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. Add SHA-256 key.
3. Navigate to Project settings and download the configuration file.
4. Navigate to General Information, and then provide Data Storage location.
5. Navigate to Manage APIs and enable APIs to require by application.
6. Navigate to Huawei Analytics > Overview > Custom dashboard > Enable Analytics
Xamarin Analytics Kit Setup Process
1. Download Xamarin Plugin of all the aar and zip files from below URL:
https://developer.huawei.com/consum...ibrary-V1/xamarin-android-0000001061360985-V1
2. Open the XHiAnalytics-5.0.5.300.sln solution in Visual Studio.
3. Navigate to Solution Explorer and right-click on jar Add > Existing Item and choose aar file which download in Step 1.
4. Choose aar file from download location.
5. Right-click on added aar file, then choose Properties > Build Action > LibraryProjectZip.
Note: Repeat Step 3 and 4 for all aar file.
6. Build the Library and make DLL files.
Xamarin Ads Kit Setup Process
1. Download Xamarin Plugin of all the aar and zip files from below URL:
https://developer.huawei.com/consum..._TOPIC_0000001050175494__section1134316505481
2. Open the XAdsIdentifier-3.4.35.300.sln solution in Visual Studio.
3. Navigate to Solution Explorer and right-click on jar Add > Existing Item and choose aar file which download in Step 1.
4. Choose aar file from download location.
5. Right-click on added aar file, then choose Properties > Build Action > LibraryProjectZip.
Note: Repeat Step 3 and 4 for all aar file.
6. Build the Library and make DLL files.
Xamarin App Development
1. Open Visual Studio 2019 and Create A New Project.
2. Navigate to Solution Explore > Project > Add > Add New Folder.
3. Navigate to Folder(created) > Add > Add Existing and add all DLL files.
Read full article in forum
Ads Kit Integration
Banner Ads Integration Procedure
Kindly refer to the below link:
https://developer.huawei.com/consum...in-Guides/xamarin-banner-ads-0000001050418457
Reward Ads Integration Procedure
Kindly refer to the below link:
https://developer.huawei.com/consum...-Guides/xamarin-rewarded-ads-0000001050178541
Interstitial Ads Integration Procedure
Kindly refer to the below link:
https://developer.huawei.com/consum...ugin-Guides/interstitial-ads-0000001050176486
Splash Ads Integration Procedure
Kindly refer to the below link:
https://developer.huawei.com/consum...in-Guides/xamarin-splash-ads-0000001050418461
Analytics Kit Integration
Initializing Analytics Kit Procedure
Kindly refer to the below link:
https://developer.huawei.com/consum...-Plugin-Guides/initanalytics-0000001050141599
LoginActivity.cs
This activity performs all the operation regarding login with Huawei Id along with display banner ads at bottom of the screen along with track analytics events.
C#:
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.OS;
using Android.Runtime;
using Android.Support.V4.App;
using Android.Support.V4.Content;
using Android.Support.V7.App;
using Android.Util;
using Android.Views;
using Android.Widget;
using Com.Huawei.Agconnect.Config;
using Com.Huawei.Hmf.Tasks;
using Com.Huawei.Hms.Ads;
using Com.Huawei.Hms.Ads.Banner;
using Com.Huawei.Hms.Ads.Nativead;
using Com.Huawei.Hms.Analytics;
using Com.Huawei.Hms.Common;
using Com.Huawei.Hms.Support.Hwid;
using Com.Huawei.Hms.Support.Hwid.Request;
using Com.Huawei.Hms.Support.Hwid.Result;
using Com.Huawei.Hms.Support.Hwid.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WeatherAppDemo
{
[Activity(Label = "LoginActivity", Theme = "@style/AppTheme", MainLauncher = true)]
public class LoginActivity : AppCompatActivity
{
private static String TAG = "LoginActivity";
private HuaweiIdAuthParams mAuthParam;
public static IHuaweiIdAuthService mAuthManager;
// private NativeAd nativeAd;
private Button btnLoginWithHuaweiId;
HiAnalyticsInstance instance;
InterstitialAd interstitialAd;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
SetContentView(Resource.Layout.login_activity);
loadBannerAds();
HiAnalyticsTools.EnableLog();
// Generate the Analytics Instance
instance = HiAnalytics.GetInstance(this);
// You can also use Context initialization
// Context context = ApplicationContext;
// instance = HiAnalytics.GetInstance(context);
// Enable collection capability
instance.SetAnalyticsEnabled(true);
btnLoginWithHuaweiId = FindViewById<Button>(Resource.Id.btn_huawei_id);
btnLoginWithHuaweiId.Click += delegate
{
// Write code for Huawei id button click
mAuthParam = new HuaweiIdAuthParamsHelper(HuaweiIdAuthParams.DefaultAuthRequestParam)
.SetIdToken().SetEmail()
.SetAccessToken()
.CreateParams();
mAuthManager = HuaweiIdAuthManager.GetService(this, mAuthParam);
StartActivityForResult(mAuthManager.SignInIntent, 1011);
string text = "Login Clicked";
Toast.MakeText(Android.App.Application.Context, text, ToastLength.Short).Show();
// Initiate Parameters
Bundle bundle = new Bundle();
bundle.PutString("text", text);
instance.OnEvent("ButtonClickEvent", bundle);
navigateToHomeScreen();
};
checkPermission(new string[] { Android.Manifest.Permission.Internet,
Android.Manifest.Permission.AccessNetworkState,
Android.Manifest.Permission.ReadSms,
Android.Manifest.Permission.ReceiveSms,
Android.Manifest.Permission.SendSms,
Android.Manifest.Permission.BroadcastSms}, 100);
}
private void loadBannerAds()
{
// Obtain BannerView based on the configuration in layout
BannerView bottomBannerView = FindViewById<BannerView>(Resource.Id.hw_banner_view);
bottomBannerView.AdListener = new AdsListener();
AdParam adParam = new AdParam.Builder().Build();
bottomBannerView.LoadAd(adParam);
// Obtain BannerView using coding
BannerView topBannerview = new BannerView(this);
topBannerview.AdId = "testw6vs28auh3";
topBannerview.BannerAdSize = BannerAdSize.BannerSize32050;
topBannerview.LoadAd(adParam);
}
private void LoadInterstitialAd()
{
InterstitialAd interstitialAd = new InterstitialAd(this);
interstitialAd.AdId = "testb4znbuh3n2"; //testb4znbuh3n2 is a dedicated test ad slot ID.
AdParam adParam = new AdParam.Builder().Build();
interstitialAd.LoadAd(adParam);
}
private void ShowInterstitial()
{
interstitialAd.AdListener = new AdsListenerInterstitial(this);
// Display an interstitial ad.
if (interstitialAd != null && interstitialAd.IsLoaded)
{
interstitialAd.Show();
}
else
{
// The ad was not loaded.
}
}
private class AdsListenerInterstitial : AdListener
{
LoginActivity interstitialActivity;
public AdsListenerInterstitial(LoginActivity interstitialActivity)
{
this.interstitialActivity = interstitialActivity;
}
public override void OnAdClicked()
{
// Called when an ad is clicked.
}
public override void OnAdClosed()
{
// Called when an ad is closed.
}
public override void OnAdFailed(int errorCode)
{
// Called when an ad fails to be loaded.
}
public override void OnAdLeave()
{
// Called when a user leaves an ad.
}
public override void OnAdLoaded()
{
// Called when an ad is loaded successfully.
// Display an interstitial ad.
interstitialActivity.ShowInterstitial();
}
public override void OnAdOpened()
{
// Called when an ad is opened.
}
}
public void checkPermission(string[] permissions, int requestCode)
{
foreach (string permission in permissions)
{
if (ContextCompat.CheckSelfPermission(this, permission) == Permission.Denied)
{
ActivityCompat.RequestPermissions(this, permissions, requestCode);
}
}
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
protected override void AttachBaseContext(Context context)
{
base.AttachBaseContext(context);
AGConnectServicesConfig config = AGConnectServicesConfig.FromContext(context);
config.OverlayWith(new HmsLazyInputStream(context));
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
if (requestCode == 1011 || requestCode == 1022)
{
//login success
Task authHuaweiIdTask = HuaweiIdAuthManager.ParseAuthResultFromIntent(data);
if (authHuaweiIdTask.IsSuccessful)
{
AuthHuaweiId huaweiAccount = (AuthHuaweiId)authHuaweiIdTask.TaskResult();
Log.Info(TAG, "signIn get code success.");
Log.Info(TAG, "ServerAuthCode: " + huaweiAccount.AuthorizationCode);
Toast.MakeText(Android.App.Application.Context, "SignIn Success", ToastLength.Short).Show();
// navigateToHomeScreen(huaweiAccount);
}
else
{
Log.Info(TAG, "signIn failed: " + ((ApiException)authHuaweiIdTask.Exception).StatusCode);
Toast.MakeText(Android.App.Application.Context, ((ApiException)authHuaweiIdTask.Exception).StatusCode.ToString(), ToastLength.Short).Show();
Toast.MakeText(Android.App.Application.Context, "SignIn Failed", ToastLength.Short).Show();
}
}
}
private void showLogoutButton()
{
/*logout.Visibility = Android.Views.ViewStates.Visible;*/
}
private void hideLogoutButton()
{
/*logout.Visibility = Android.Views.ViewStates.Gone;*/
}
private void navigateToHomeScreen(/*AuthHuaweiId data*/)
{
Intent intent = new Intent(this, typeof(MainActivity));
/*intent.PutExtra("name", data.DisplayName.ToString());
intent.PutExtra("email", data.Email.ToString());
intent.PutExtra("image", data.PhotoUriString.ToString());*/
StartActivity(intent);
Finish();
}
private class AdsListener : AdListener
{
public override void OnAdClicked()
{
// Called when a user taps an ad.
Log.Info(TAG, "Ad Clicked");
Toast.MakeText(Application.Context, "Ad Clicked", ToastLength.Short).Show();
}
public override void OnAdClosed()
{
// Called when an ad is closed.
Log.Info(TAG, "Ad Closed");
Toast.MakeText(Application.Context, "Ad Closed", ToastLength.Short).Show();
}
public override void OnAdFailed(int errorCode)
{
// Called when an ad fails to be loaded.
Log.Info(TAG, "Ad Failed");
Toast.MakeText(Application.Context, "Ad Failed", ToastLength.Short).Show();
}
public override void OnAdLeave()
{
// Called when a user has left the app.
Log.Info(TAG, "Ad Leave");
/*Toast.MakeText(Android.App.Application.Context, "Ad Leave", ToastLength.Short).Show();*/
}
public override void OnAdOpened()
{
// Called when an ad is opened.
Log.Info(TAG, "Ad Opened");
/*Toast.MakeText(Android.App.Application.Context, "Ad Opened", ToastLength.Short).Show();*/
}
public override void OnAdLoaded()
{
// Called when an ad is loaded successfully.
Log.Info(TAG, "Ad Loaded");
Toast.MakeText(Application.Context, "Ad Loaded", ToastLength.Short).Show();
}
}
}
}
Tips and Tricks
1. On mobile phones whose value of targetSdkVersion is 28 or later, ad video assets may fail to be downloaded. In this case, you need to configure the app to allow HTTP network requests. For details, please refer to Configuring Network Permissions.
2. Xamarin requires the ADB daemon to be started over port 5037. If the ADB daemon runs on a different port, Visual Studio will not be able to detect your device.
Conclusion
In this article, we have learned how to integrate HMS Ads and Analytics Kit in Xamarin based Android application. We can display ads and track the user’s event in the application.
Thanks for reading this article.
Be sure to like and comments on this article, if you found it helpful. It means a lot to me.
References
https://developer.huawei.com/consum...-Guides/service-introduction-0000001050178531
https://developer.huawei.com/consum..._TOPIC_0000001050175494__section1134316505481
https://developer.huawei.com/consum...S-Plugin-Guides/introduction-0000001050139636
https://forums.developer.huawei.com/forumPortal/en/topic/0204485009808440045
Read full article in forum
Introduction
In this article, we will be integrating Huawei Ads and Game Services kit in flutter application. You can access to range of development capabilities. You can promote your game quickly and more efficiently to Huawei’s vast users as Huawei Game Services allows users to login game with Huawei IDs. You can also use the service to quickly implement achievements, game events, and game addiction prevention functions and perform in-depth game operations based on user and content localization. Huawei Ads kit helps developer to monetize application.
Huawei supports following Ads types
Banner
Interstitial
Native
Reward
Splash
Instream(Roll)
Huawei Game Services Capabilities
Game Login
Achievements
Floating window*
Game Addiction prevention*
Events
Leaderboards
Save Games*
Player statistics*
Access to Basic Game Information*
Note: Restricted to regions (*)
{
"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"
}
Development Overview
You need to install Flutter and Dart plugin in IDE and I assume that you have prior knowledge about the Flutter and Dart.
Hardware Requirements
A computer (desktop or laptop) running Windows 10.
A Huawei phone with API 4.x.x or above (with the USB cable), which is used for debugging.
Software Requirements
Java JDK 1.7 or later.
Android studio software or Visual Studio or Code installed.
HMS Core (APK) 4.X or later.
Integration process
Step 1. Create flutter project.
Step 2. Add the App level gradle dependencies, choose inside project Android > app > build.gradle.
Code:
apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect'
Add root level gradle dependencies.
Code:
maven {url 'https://developer.huawei.com/repo/'}
classpath 'com.huawei.agconnect:agcp:1.4.2.301'
Step 3: Add the below permissions in Android Manifest file.
Code:
<uses-permission android:name="android.permission.INTERNET" />
Step 4: Add plugin path in pubspec.yaml file under dependencies.
Step 5: Create a project in AppGallery Connect, find here.
pubspec.yaml
Code:
name: gameservice234demo
description: A new Flutter project.
# The following line prevents the package from being accidentally published to
# pub.dev using `pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1
environment:
sdk: ">=2.12.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
huawei_account:
path: ../huawei_account
huawei_gameservice:
path: ../huawei_gameservice
huawei_ads:
path: ../huawei_ads_301
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.2
dev_dependencies:
flutter_test:
sdk: flutter
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
# The following section is specific to Flutter.
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
How do I launch or initialize the Ads SDK?
Code:
HwAds.init();
How do I load Splash Ads?
Code:
void showSplashAd() {
SplashAd _splashAd = createSplashAd();
_splashAd
..loadAd(
adSlotId: "testq6zq98hecj",
orientation: SplashAdOrientation.portrait,
adParam: AdParam(),
topMargin: 20);
Future.delayed(Duration(seconds: 7), () {
_splashAd.destroy();
});
}
static SplashAd createSplashAd() {
SplashAd _splashAd = new SplashAd(
adType: SplashAdType.above,
ownerText: ' Huawei SplashAd',
footerText: 'Test SplashAd',
); // Splash Ad
return _splashAd;
}
How do I load Native Ad?
Code:
static NativeAd createNativeAd() {
NativeStyles stylesSmall = NativeStyles();
stylesSmall.setCallToAction(fontSize: 8);
stylesSmall.setFlag(fontSize: 10);
stylesSmall.setSource(fontSize: 11);
NativeAdConfiguration configuration = NativeAdConfiguration();
configuration.choicesPosition = NativeAdChoicesPosition.topLeft;
return NativeAd(
// Your ad slot id
adSlotId: "testu7m3hc4gvm",
controller: NativeAdController(
adConfiguration: configuration,
listener: (AdEvent event, {int? errorCode}) {
print("Native Ad event : $event");
}),
type: NativeAdType.small,
styles: stylesSmall,
);
}
How do I load Interstitial Ad?
Code:
void showInterstitialAd() {
InterstitialAd interstitialAd =
InterstitialAd(adSlotId: "teste9ih9j0rc3", adParam: AdParam());
interstitialAd.setAdListener = (AdEvent event, {int? errorCode}) {
print("InterstitialAd event : $event");
};
interstitialAd.loadAd();
interstitialAd.show();
}
How do I load Rewarded Ad?
Code:
static Future<void> showRewardAd() async {
RewardAd rewardAd = RewardAd();
await rewardAd.loadAd(
adSlotId: "testx9dtjwj8hp",
adParam: AdParam(),
);
rewardAd.show();
rewardAd.setRewardAdListener =
(RewardAdEvent event, {Reward? reward, int? errorCode}) {
print("RewardAd event : $event");
if (event == RewardAdEvent.rewarded) {
print('Received reward : ${reward!.toJson().toString()}');
}
};
}
How do I launch or initialize the game?
Code:
void init() async {
await JosAppsClient.init();
}
Use Huawei ID for login
Code:
Future<void> login() async {
helper = new HmsAuthParamHelper()
..setIdToken()
..setAccessToken()
..setAuthorizationCode()
..setEmail()
..setProfile();
huaweiId = await HmsAuthService.signIn(authParamHelper: helper);
if (huaweiId != null) {
setState(() {
isLoggedIn = true;
msg = huaweiId!.displayName;
loginLabel = "Logged in as";
print(msg);
});
getPlayer();
} else {
setState(() {
msg = " Inside else ";
});
}
}
How do I get Achievements list?
Code:
Future<void> getAchievements() async {
try {
List<Achievement> result =
await AchievementClient.getAchievementList(true);
print("Achievement:" + result.toString());
} on PlatformException catch (e) {
print("Error on getAchievementList API, Error: ${e.code}, Error Description:
${GameServiceResultCodes.getStatusCodeMessage(e.code)}");
}
}
How do I displaying the Achievements List Page of HUAWEI AppAssistant using Intent?
Code:
void showAchievementsIntent() {
try {
AchievementClient.showAchievementListIntent();
} on PlatformException catch (e) {
print("Error on showAchievementListIntent API, Error: ${e.code}, Error Description:
${GameServiceResultCodes.getStatusCodeMessage(e.code)}");
}
}
How do I call Floating window?
Code:
try {
await BuoyClient.showFloatWindow();
} on PlatformException catch (e) {
print("Error on showFloatWindow API, Error: ${e.code}, Error Description:
${GameServiceResultCodes.getStatusCodeMessage(e.code)}");
}
How do I get All Events?
Code:
Future<void> getEvents() async {
try {
List<GameEvent> result = await EventsClient.getEventList(true);
print("Events: " + result.toString());
} on PlatformException catch (e) {
print("Error on getEventList API, Error: ${e.code}, Error Description:
${GameServiceResultCodes.getStatusCodeMessage(e.code)}");
}
}
How do I submit an Event?
Code:
Future<void> sendEvent(String eventId) async {
try {
await EventsClient.grow(eventId, 1);
print("************** Event sent **************");
} on PlatformException catch (e) {
print("Error on grow API, Error: ${e.code}, Error Description:
${GameServiceResultCodes.getStatusCodeMessage(e.code)}");
}
}
How do I get All Leaderboard data?
Code:
Future<void> getLeaderboardList() async {
// check the leaderboard status
int result = await RankingClient.getRankingSwitchStatus();
// set leaderboard status
int result2 = await RankingClient.setRankingSwitchStatus(1);
List<Ranking> rankings = await RankingClient.getAllRankingSummaries(true);
print(rankings);
//To show RankingIntent
RankingClient.showTotalRankingsIntent();
}
How do I submit the ranking score?
Code:
try {
int score = 102;
RankingClient.submitRankingScores(rankingId, score);
} on PlatformException catch (e) {
print("Error on submitRankingScores API, Error: ${e.code}, Error Description:${GameServiceResultCodes.getStatusCodeMessage(e.code)}");
}
Or
try {
int score = 125;
ScoreSubmissionInfo result = await RankingClient.submitScoreWithResult(rankingId, score);
} on PlatformException catch (e) {
print("Error on submitScoreWithResult API, Error: ${e.code}, Error Description: ${GameServiceResultCodes.getStatusCodeMessage(e.code)}");
}
How do I displaying the Leaderboard List Page of HUAWEI AppAssistant using Intent?
Code:
void showLeaderboardIntent() {
try {
RankingClient.showTotalRankingsIntent();
} on PlatformException catch (e) {
print("Error on showLeaderboardListIntent API, Error: ${e.code}, Error Description:
${GameServiceResultCodes.getStatusCodeMessage(e.code)}");
}
}
Result
Tricks and Tips
Make sure that you have downloaded latest plugin.
Make sure that updated plugin path Ads in yaml.
Make sure that plugin unzipped in parent directory of project.
Makes sure that agconnect-services.json file added.
Make sure dependencies are added in build file.
Run flutter pug get after adding dependencies.
Generating SHA-256 certificate fingerprint in android studio and configure in ag-connect.
Game Services previous article you can check out here
Conclusion
In this article, we have learnt how to integrate capabilities of Huawei Ads with Game Services kit in flutter application. You can promote your game quickly and more efficiently to Huawei’s vast users as Huawei Game Services allows users to login with Huawei IDs and this can be achieved by implementing its capabilities in your application. Developer can easily integrate and monetize the application which helps developer to grow financial long with application. Similar way you can use Huawei Ads with Game Services as per user requirement in your application.
Thank you so much for reading, I hope this article helps you to understand the Huawei Ads with Game Services capabilities in flutter.
Reference
GameServices Kit
Plutter Plugin Game services
Ads Kit
Original Source