Integrate Nearby Service for an Enhanced Gaming Experience - Huawei Developers

HUAWEI Nearby Service is an important feature of HMS Core, designed to help users quickly find players in the vicinity, and automatically establish a low-latency, high-reliability, and zero-traffic data transmission channel, backed by underlying technologies such as Wi-Fi and Bluetooth. Integrating Nearby Service equips your game to provide users with a premium experience across the board.
1. Premium Attributes
1.1 One-Click Cross-Device Connections for Local Multiplayer Games
Current LAN games require that users are connected to the same router, in order for a connection to be established. If there is no router available, users have to manually enable a hotspot, complicating the process. Nearby Service resolves this persistent issue.
1.2 Face-to-Face Grouping and Friend Adding
Nearby Service provides you with functions for creating face-to-face groups and adding friends, without having to rely on social software or GPS, facilitating free and easy user interactions.
1.3 Face-to-Face Prop Sharing
Nearby Service allows users to quickly share game props with friends, helping you acquire new users and improve user stickiness.
2. Introduction to Plugins
Two encapsulated plugins are provided here. You can directly use the two plugins in the app, and view the source code of the plugins, for a thorough understanding of how to integrate the Nearby Service.
2.1 Preparations
Development environment of Unity.
Download the plugins on GitHub.
2.2 Plugin Import
Choose Assets > Import Package > Custom Package, and click Nearby Player or Discovery Plugin on the toolbar of Unity.
Wait for the package to be processed. After that, the resource list of plugins will display. Then click Import.
2.3 Key Code
2.3.1 Nearby Player Plugin
This plugin is applicable to such scenarios as creating face-to-face groups, adding friends, and sharing props. Declare the NearbyManager class in the plugin. The class provides APIs startDiscovery() and SendMessage() for users to discover nearby players and send messages.
Call startDiscovery to discover nearby players and make the current users discoverable by nearby players when the game starts.
The code of the called API is as follows:
Code:
void Start() {
AndroidMyCallback cb = new AndroidMyCallback(this);
nm = new NearbyManager(cb);
nm.startDiscovery(randomName());
}
The callback function AndroidMyCallback is used to perform operations after a successful discovery.
Code:
// Perform the subsequent operations when a player is discovered. In this demo, the player is being added to the player list.
public override void onFoundPlayer(string endpointName, string endpointId) {
mListController.AddPlayerToList(endpointName, endpointId);
}
// Perform the subsequent operations when a player is lost. In this demo, the player is being removed from the player list.
public override void onLostPlayer(string endpointId) {
mListController.RemovePlayerFromList(endpointId);
}
// Perform the subsequent operations when a player's message is received. In this demo, only the content of the message is displayed.
public override void onReceiveMsg(string endpointName, string Msg) {
mListController.ReceiveMsg(endpointName, Msg);
}
After discovering nearby players, users can send messages to the players for grouping, adding friends, or sharing props.
Code:
// In this demo, click a player's profile picture in the player list to send a grouping invitation.
private void OnClick(string endpointId) {
nm.log("OnClick. SendMessage to " + endpointId);
nm.SendMessage(endpointId, "invites you to join a game.");
}
2.3.2 Nearby Discovery Plugin
This is a plugin developed based on Unity UNET. Users are able to connect their devices on a mutual basis, even they are in different Wi-Fi environments. Declare the NearbyManager class, which offers two APIs: startBroadcast() and startDiscovery(). Two game devices can be connected by calling the above APIs.
The code of the called APIs is as follows:
Code:
private void OnClick() {
Button btn = this.GetComponent<Button>();
btn.enabled = false;
AndroidMyCallback androidMyCallback = new AndroidMyCallback(mNetworkManager);
NearbyManager nearbyManager = new NearbyManager(androidMyCallback);
nearbyManager.startBroadcast();
}
The callback function AndroidMyCallback is used to perform operations after a successful connection. Here, the networkManager API of UNET is called to start the game after a successful connection.
Code:
public class AndroidMyCallback : AndroidCallback {
private NetworkManager mNetworkManager;
public AndroidMyCallback(NetworkManager networkManager) : base() {
mNetworkManager = networkManager;
}
public override void onClientReady(string ipaddr) {
mNetworkManager.networkAddress = ipaddr;
mNetworkManager.StartClient();
}
public override void onServerReady(string ipaddr) {
mNetworkManager.StartHost();
}
}
2.4 Demo
Below we have provided two demos that have integrated the plugins detailed above, to provide you with a better understanding of the process.
Nearby-Player-Demo
{
"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"
}
UNET-NEARBY-DEMO
3. Game Apps That Have Integrated Nearby Service
Tic Tac Toe
Tic Tac Toe is a local battle game that was developed based on native Android APIs from Nearby Service, and released on the HUAWEI AppGallery platform.
NearbyGameSnake
NearbyGameSnake is a local multiplayer game that integrates Nearby Service. It is easy to play, and enables users to play directly in groups, without requiring an Internet connection.
4. Learn More
For more details, please visit HUAWEI Developers.
For more instructions, please visit Development Guide.
You can join the HMS Core developer discussion by going to Reddit.
You can download the demo and sample code from GitHub.
To solve integration problems, please go to Stack Overflow.

Related

What Huawei Analytics Offers?

1) What is analytics? Why is it used?
How your app is used by users? which pages get more traffic?on which page customers leave the app?
If you want to understand that and direct your future developments accordingly
Analytics is just for you. Understanding user’s habits will help you to make your app better.
If your app is at a certain level or you want to move your app and business forward, you need to use analytics.
To date, there are many services that offer solutions for analytics. Huawei handled analytics as a priority on HMS.
So why would I prefer Huawei Analytics?
Easy to integrate and use
It is very easy to integrate and use the analytics dashboard after integrating Huawei Analytics.
Moreover, you can customize your tables on the dashboard as you wish and you can easily see the data you want to see, not imposed on you.
Reach Huawei users
As you know, google services are not used in the latest Huawei devices. When you integrate Huawei Analytics, you will reach all Huawei users and all other devices users. So Huawei Analytics a connective, not a divider.
Power of HMS Core
Analytics gets its power from HMS Core.
It is very easy to reach all the documents you need for integration or usage of dashboard.When there is a technical problem you can find technical support very easily.
Powerful Analysis Capabilities
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
2) How to Integrate Huawei Analytics?
For integrate Huawei Analytics kit to our application, first of all, it is necessary to register in the Huawei developer community
After adding your app to AppGallery Connect, we need to enable Analytics service to usage.
After completing the enabling process, we go to the manage API tab from the project settings, activate the analytics service and add the json file on the project settings page to our project and add HMS SDK Dependencies to your project(Note: The order of these processes is important. You should update your json file in case of any service change.).
Add build dependencies to dependencies.
Code:
implementation 'com.huawei.hms:hianalytics:4.0.0.303'
Then all you have to do is go to the class you want to collect and start collecting the data.
Code:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Enable SDK log recording
HiAnalyticsTools.enableLog();
HiAnalyticsInstance instance = HiAnalytics.getInstance(this);
//Or, use context initialization
//Context context = this.getApplicationContext();
//HiAnalyticsInstance instance = HiAnalytics.getInstance(context);
//instance.setUserProfile("userKey","value");
}
You can customize the data to be collected.
Code:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Enable SDK log recording
HiAnalyticsTools.enableLog();
HiAnalyticsInstance instance=HiAnalytics.getInstance(this);
//Or, use context initialization
//Context context = this.getApplicationContext();
//HiAnalyticsInstance instance = HiAnalytics.getInstance(context);
//instance.setUserProfile("userKey","value");
}
As you can see, we can write just a few lines of code and connect our project with Huawei Analytics. So where and how do we evaluate the data we collect, let’s look at it
3) Viewing Analytics Data
You have a 4 section in welcome page. Overview, Distirbution Analysis, Operation Analysis and Advance Analysis. By default, the Overview page of an app displays its KPIs in all channels (AppGallery and AppTouch), including App impressions, Details page views, New downloads, and In-app purchase amount.
The Distribution Analysis page displays the app usage and sales data. Use Downloads & installs to measure the installation and usage of your app. Use In-App Purchases and Paid application details to measure the sales of your app.
With Operation Analysis, you can view the financial reports of your application and set up your future strategies based on this.
Advanced Analysis is a platform where you can create personalized tables, filter your users and view them according to categories, and instantly track active users and all other data.
With Event Analysis Gains insight into user behaviour details. Activity analysis providing gains insight into user loyalty. Funnel analysis gains insight the phase in which user lost.
Huawei Analytics gives us uncountable opportunities to do. As you can see here, your limit is your imagination.
Thanks for reading!
Related Links
Thanks to Mehmet Batuhan Ulper

In-App Purchase for Online Grocery Store

More information like this, you can visit HUAWEI Developer Forum​
This article is based on Huawei’s In-App Purchases. We can create a new sample application for online grocery store to buy fruits and vegetables with online payment using In-App Purchases.
Huawei's In-App Purchases (IAP) service integrates multiple payment methods for global payment and allows you to easily offer in-app purchases. Users can purchase a variety of products or services, including common virtual products and subscriptions, directly within your app.
HUAWEI IAP provides a product management system (PMS) for managing the prices and languages of in-app products (including games) in multiple locations.
The latest version of IAP supports the following functions:
Release: You can release an app or a game with one package and manage the prices and languages of in-app purchases. The locations supported by the PMS on the price configuration page shall prevail.
Currencies and languages: You can set one default currency and one default language for each location. Setting multiple languages for one location is not allowed.
Price: Huawei provides an in-app product price reference for each location based on the converted price (tax included) set the exchange rate. You can change the price.
Exchange rate: fixed exchange rate by which Huawei will update the price. Updating the exchange rate by Huawei will not affect your price if you do not change the price.
Intended audience: global developers. To release an in-app product (or a game) to multiple locations, you need to manage the price and language of the products locally.
These are the following 3 types of in-app products supported by the IAP:
1. Consumable: Consumables are used once, are depleted, and can be purchased again.
2. Non-consumable: Non-consumables are purchased once and do not expire.
3. Auto-renewable subscriptions: Users can purchase access to value-added functions or content in a specified period of time. The subscriptions are automatically renewed on a recurring basis until users decide to cancel.
Prerequisite
1) A computer (desktop or laptop)
2) A Huawei phone used for running the app with HUAWEI IAP integrated
3) A data cable used for connecting the computer to the Huawei phone
4) Android Studio 3.0 or later
5) Java SDK 1.7 or later
6) HMS Core (APK) 3.0.0.300 or later
7) HMS Core SDK 4.0.0.300 or later
8) Must have Huawei Developer Account
9) Must have Huawei Merchant Account
Things Need To Be Done
1) Create an app in AppGallery Connect.
2) Create an Android Studio project.
3) Start development with kit integration inside the application.
4) Launch the application.
Create a project on AppGalleryConnect portal:
1. Click My projects.
{
"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. Click Add project and provide your project details.
3. Provide your project name and click OK.
4. Navigate to General Information, and then provide Data Storage location.
5. Navigate to Manage APIs and enable APIs which require by application
6. Navigate to General information and download the agconnect-services.json file
7. Navigate to In-App Purchases and copy Public Key.
8. Navigate to My apps, click Operate, and then enter details in Add Product.
9. Click View and Edit in above screenshot, enter Product price details, and then click Save.
10. Click Activate for product activation.
Create a project in Android Studio:
1. Open your android studio and Create New Project.
2. Enter the maven url inside the repositories of buildscript and allprojects (project build.gradle file)
Add maven url and add following AppGalleryConnect class path.
Code:
buildscript {
repositories {
maven {url 'http://developer.huawei.com/repo/'}
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.6.1'
classpath 'com.huawei.agconnect:agcp:1.0.0.300'
}
}
allprojects {
repositories {
maven {url 'http://developer.huawei.com/repo/'}
google()
jcenter()
}
}
3. Add the following dependencies in app module based gradle file
Code:
implementation 'com.huawei.hms:iap:4.0.0.300'
4. Generate SHA-256 fingerprint in android studio
5. Add json file inside your application
Start development with kit integration inside the application
We have created the following package inside the project.
We have created 3 activities Home, Store, and ViewPurchases activity inside activity package.
Home Activity: In this activity, we have created a simple User interface for our online store app.
Code:
public class HomeActivity extends BaseActivity {
private ActivityHomeBinding homeBinding;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
homeBinding = DataBindingUtil.setContentView(this, R.layout.activity_home);
init();
}
private void init() {
setToolbar(homeBinding.tbWidget.findViewById(R.id.toolbar),
false, "My Online Store", homeBinding.tbWidget.findViewById(R.id.tv_toolbar_title));
homeBinding.btnBuyFromStore.setOnClickListener(v->StoreActivity.start(this));
homeBinding.btnViewYourPurchases.setOnClickListener(v->ViewPurchasesActivity.start(this));
}
}
Store Activity: In this activity we have simply displayed the all products which is available.
Code:
public class HomeActivity extends BaseActivity {
private ActivityHomeBinding homeBinding;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
homeBinding = DataBindingUtil.setContentView(this, R.layout.activity_home);
init();
}
private void init() {
setToolbar(homeBinding.tbWidget.findViewById(R.id.toolbar),
false, "My Online Store", homeBinding.tbWidget.findViewById(R.id.tv_toolbar_title));
homeBinding.btnBuyFromStore.setOnClickListener(v->StoreActivity.start(this));
homeBinding.btnViewYourPurchases.setOnClickListener(v->ViewPurchasesActivity.start(this));
}
}
This is not the end. For full content, you can visit https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0201333994591170041&fid=0101188387844930001
How can we add money into Huawei points

Huawei Flight Booking Application (App messaging and analytics integration) – Part 2

More information like this, you can visit HUAWEI Developer Forum​
Introduction
Flight booking app allows user to search and book flight. In this article, we will integrate app messaging and analytics into demo flight booking application.
UseCase
1. We will show app-messaging image on app screen showing list of searched flight. When user tap on app-messaging image, it will redirect to webpage showing guidelines for international arrivals and departures. Add following image URL on Huawei App gallery connect.
{
"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. We will use Huawei analytics to report few events like successful sign in and number of flights available between source destination.
For prerequisite and set up, refer to part 1.
Huawei App messaging
App Messaging of AppGallery Connect used to send relevant messages to target users actively using your app to encourage them to use key app functions. For example, you can send in-app messages to encourage users to subscribe certain products, provide tips on passing a game level, or recommend activities of a restaurant.
Implemetation
1. Add dependency in the app build.gradle file.
Code:
dependencies {
implementation 'com.huawei.agconnect:agconnect-appmessaging:1.4.0.300'
}
2. We need AAID for later use in sending In-App Messages. To obtain AAID, we will use getAAID() method.
3. Add following code in your project to obtain AAID.
Code:
HmsInstanceId inst = HmsInstanceId.getInstance(this);
Task<AAIDResult> idResult = inst.getAAID();
idResult.addOnSuccessListener(new OnSuccessListener<AAIDResult>() {
@Override
public void onSuccess(AAIDResult aaidResult) {
String aaid = aaidResult.getId();
Log.d(TAG, "getAAID success:" + aaid );
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
Log.d(TAG, "getAAID failure:" + e);
}
});
4. To initialize the AGConnectAppMessaging instance we will use.
Code:
AGConnectAppMessaging appMessaging = AGConnectAppMessaging.getInstance();
5. To allow data synchronization from the AppGallery Connect server we will use.
Code:
appMessaging.setFetchMessageEnable(true);
6. To enable message display.
Code:
appMessaging.setDisplayEnable(true);
7. To specify that the in-app message data must be obtained from the AppGallery Connect server by force we will use.
Code:
appMessaging.setForceFetch();
Since we are using a test device to demonstrate the use of In-App Messaging, so we use setForceFetch API. The setForceFetch API can be used only for message testing. Also In-app messages can only be displayed to users who have installed our officially released app version.
Creating Image In-App Messaging on App Gallery connect
1. Sign in to AppGallery Connect and select My projects.
2. Select your project from the project list.
3. Navigate Growing > App Messaging and click New.
4. Set Name and Description for your in-app message.
5. Provide the in-app message Type. For image in-app message, select type as Image.
6. Provide image URL.
7. Provide the action for image tapping.
8. Click Next to move on to the next section, that is, Select Sending Target section. Here we can define Condition for matching target users. In this article, we did not use any condition.
9. The next section is the Set Sending Time section.
We can schedule a date and time to send in-app message.
We can also provide an End data and time to stop sending message.
We can also display message on an events by using trigger event functionality.
Also we can flexibly set the frequency for displaying the in-app message.
10. Click Next, find Set conversation events. It associates the display or tap of the app message with a conversion event. The conversion relationship will be displayed in statistics. As off now we will keep it as none.
11. Click Save in the upper-right corner to complete message creation.
12. In-app messages can only be displayed to users who have installed our officially released app version. App Messaging allows us to test an in-app message when our app is still under tests. Find the message that you need to test, and click Test in the Operation column as shown below.
13. Provide the AAID of the test device in the text box. Click Save.
14. Click Publish.
Huawei Analytics
In this section, will show you how to use main APIs of HUAWEI Analytics Kit to report some custom events. App will report event like successful login, number of search flights.
1. Add the dependencies in app build.gradle file.
Code:
implementation 'com.huawei.hms:hianalytics:5.0.1.301'
2. The MainActivity.java is launched once user has successfully signed in. In onCreate(), we will call initializeAnalytics()to report successful signed in event.
Code:
private void initializeAnalytics() {
//Enable Analytics Kit Log
HiAnalyticsTools.enableLog();
//Generate the Analytics Instance
instance = HiAnalytics.getInstance(this);
//Parameter definition
Bundle bundle = new Bundle();
bundle.putBoolean("IsLoggedIn", true);
//Reporting event
instance.onEvent("LoginStatus", bundle);
}
3. To report number of flight available between origin and destination.
Code:
httpHandler.setFlightSearchListner(new OnFightSearchListner() {
@Override
public void onSuccess(ArrayList<Quote> quoteList) {
if(quoteList!= null && quoteList.size() > 0) {
Bundle bundle = new Bundle();
bundle.putBoolean("FlightSearchStatus", true);
bundle.putInt("FlightSearchCount", quoteList.size());
//Reporting event
instance.onEvent("FlightSearchStatus", bundle);
}
adapter = new OneWayFlightAdapter(quoteList);
recyclerView.setAdapter(adapter);
}
@Override
public void OnFailure(Exception e) {
// not implemented yet.. will do later
Log.e(TAG, e.getMessage());
}
});
To Check Analysis on App Gallery Connect
1. On the left side panel, click on Huawei Analyze > Behaviour Analysis > Event Analysis.
Conclusion:
In this article, we learnt how to integrate Huawei app-messaging and analytics to report event in application.
Can we integrate push messages along with in-app messaging?
well explained, can we load gifs also?

Implementing Real-Time Transcription in an Easy Way

Background​The real-time onscreen subtitle is a must-have function in an ordinary video app. However, developing such a function can prove costly for small- and medium-sized developers. And even when implemented, speech recognition is often prone to inaccuracy. Fortunately, there's a better way — HUAWEI ML Kit, which is remarkably easy to integrate, and makes real-time transcription an absolute breeze!
Introduction to ML Kit​ML Kit allows your app to leverage Huawei's longstanding machine learning prowess to apply cutting-edge artificial intelligence (AI) across a wide range of contexts. With Huawei's expertise built in, ML Kit is able to provide a broad array of easy-to-use machine learning capabilities, which serve as the building blocks for tomorrow's cutting-edge AI apps. ML Kit capabilities include those related to:
Text (including text recognition, document recognition, and ID card recognition)
Language/Voice (such as real-time/on-device translation, automatic speech recognition, and real-time transcription)
Image (such as image classification, object detection and tracking, and landmark recognition)
Face/Body (such as face detection, skeleton detection, liveness detection, and face verification)
Natural language processing (text embedding)
Custom model (including the on-device inference framework and model development tool)
Real-time transcription is required to implement the function mentioned above. Let's take a look at how this works in practice:
{
"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"
}
Now let's move on to how to integrate this service.
Integrating Real-Time Transcription​Steps
Registering as a Huawei developer on HUAWEI Developers
Creating an app
Create an app in AppGallery Connect. For details, see Getting Started with Android.
We have provided some screenshots for your reference:
3. Enabling ML Kit
4. Integrating the HMS Core SDK.
Add the AppGallery Connect configuration file by completing the steps below:
Download and copy the agconnect-service.json file to the app directory of your Android Studio project.
Call setApiKey during app initialization.
To learn more, go to Adding the AppGallery Connect Configuration File.
5.Configuring the maven repository address
Add build dependencies.
Import the real-time transcription SDK.
Code:
implementation 'com.huawei.hms:ml-computer-voice-realtimetranscription:2.2.0.300'
Add the AppGallery Connect plugin configuration.
Method 1: Add the following information under the declaration in the file header:
Code:
apply plugin: 'com.huawei.agconnect'
Method 2: Add the plugin configuration in the plugins block.
Code:
plugins {
id 'com.android.application'
// Add the following configuration:
id 'com.huawei.agconnect'
}
Please refer to Integrating the Real-Time Transcription SDK to learn more.
Setting the cloud authentication information
When using on-cloud services of ML Kit, you can set the API key or access token (recommended) in either of the following ways:
Access token
You can use the following API to initialize the access token when the app is started. The access token does not need to be set again once initialized.
MLApplication.getInstance().setAccessToken("your access token");
API key
You can use the following API to initialize the API key when the app is started. The API key does not need to be set again once initialized.
MLApplication.getInstance().setApiKey("your ApiKey");
For details, see Notes on Using Cloud Authentication Information.
Code Development​
Create and configure a speech recognizer.
Code:
MLSpeechRealTimeTranscriptionConfig config = new MLSpeechRealTimeTranscriptionConfig.Factory()
// Set the language. Currently, this service supports Mandarin Chinese, English, and French.
.setLanguage(MLSpeechRealTimeTranscriptionConstants.LAN_ZH_CN)
// Punctuate the text recognized from the speech.
.enablePunctuation(true)
// Set the sentence offset.
.enableSentenceTimeOffset(true)
// Set the word offset.
.enableWordTimeOffset(true)
// Set the application scenario. MLSpeechRealTimeTranscriptionConstants.SCENES_SHOPPING indicates shopping, which is supported only for Chinese. Under this scenario, recognition for the name of Huawei products has been optimized.
.setScenes(MLSpeechRealTimeTranscriptionConstants.SCENES_SHOPPING)
.create();
MLSpeechRealTimeTranscription mSpeechRecognizer = MLSpeechRealTimeTranscription.getInstance();
Create a speech recognition result listener callback.
Code:
// Use the callback to implement the MLSpeechRealTimeTranscriptionListener API and methods in the API.
protected class SpeechRecognitionListener implements MLSpeechRealTimeTranscriptionListener{
@Override
public void onStartListening() {
// The recorder starts to receive speech.
}
@Override
public void onStartingOfSpeech() {
// The user starts to speak, that is, the speech recognizer detects that the user starts to speak.
}
@Override
public void onVoiceDataReceived(byte[] data, float energy, Bundle bundle) {
// Return the original PCM stream and audio power to the user. This API is not running in the main thread, and the return result is processed in a sub-thread.
}
@Override
public void onRecognizingResults(Bundle partialResults) {
// Receive the recognized text from MLSpeechRealTimeTranscription.
}
@Override
public void onError(int error, String errorMessage) {
// Called when an error occurs in recognition.
}
@Override
public void onState(int state,Bundle params) {
// Notify the app of the status change.
}
}
The recognition result can be obtained from the listener callbacks, including onRecognizingResults. Design the UI content according to the obtained results. For example, display the text transcribed from the input speech.
Bind the speech recognizer.
Code:
mSpeechRecognizer.setRealTimeTranscriptionListener(new SpeechRecognitionListener());
Call startRecognizing to start speech recognition.
Code:
mSpeechRecognizer.startRecognizing(config);
Release resources after recognition is complete.
Code:
if (mSpeechRecognizer!= null) {
mSpeechRecognizer.destroy();
}
(Optional) Obtain the list of supported languages.
Code:
MLSpeechRealTimeTranscription.getInstance()
.getLanguages(new MLSpeechRealTimeTranscription.LanguageCallback() {
@Override
public void onResult(List<String> result) {
Log.i(TAG, "support languages==" + result.toString());
}
@Override
public void onError(int errorCode, String errorMsg) {
Log.e(TAG, "errorCode:" + errorCode + "errorMsg:" + errorMsg);
}
});
We have finished integration here, so let's test it out on a simple screen.
Tap START RECORDING. The text recognized from the input speech will display in the lower portion of the screen.
We've now built a simple audio transcription function.
Eager to build a fancier UI, with stunning animations, and other effects? By all means, take your shot!
For reference:​Real-Time Transcription
Sample Code for ML Kit
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

Reel in Users with Topic-based Messaging

Smartphones are everywhere these days and play an important role in our daily lives. The popularization of smartphones has led to a wave of mobile apps hitting the market. So, the homogeneous competition between apps is more fierce than ever and developers are trying their best to figure out how best to attract users to their apps. Most developers resort to message pushing, which leads to an exponential growth of pushed messages. As a result, users quickly become flooded with pushed messages and struggle to find the information they need.
The explosion of pushed messages means that crafting eye-catching messages that appeal to users has never been more crucial and challenging. Like many other developers, I also encountered this problem. I have pushed many promotional messages to users of my app, but the outcome is not particularly positive. So I wondered if it is possible to push messages only to a specific user group, for example, sending car-related product promotion messages to users with cars.
It occurred to me that I came across HMS Core Push Kit, which provides a function that allows developers to send topic-based messages. With this function, developers can customize messages by topic to match users' habits or interests and then regularly send these messages to user devices via a push channel. For example, a weather forecast app can send weather forecast messages concerning a city that users have subscribed to, or a movie ticket-booking app can send reminders to users who have followed a particular movie.
Isn't that exactly what I need? So I decided to play about with this function, and it turned out to be very effective. Below is a walkthrough of how I integrated this function into my app to send topic-based messages. I hope this will help you.
Development Procedure​
Generally, three development steps are required for using the topic-based messaging function.
Step 1: Subscribe to a topic within the app.
Step 2: Send a message based on this topic.
Step 3: Verify that the message has been received.
The figure below shows the process of messaging by topic subscription on the app server.
{
"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"
}
You can manage topic subscriptions in your app or on your app server. I will detail the procedures and codes for both of these methods later.
Key Steps and Coding​
Managing Topic Subscription in Your App​
The following is the sample code for subscribing to a topic:
Code:
public void subtopic(View view) {
String SUBTAG = "subtopic";
String topic = "weather";
try {
// Subscribe to a topic.
HmsMessaging.getInstance(PushClient.this).subscribe(topic).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(Task<Void> task) {
if (task.isSuccessful()) {
Log.i(SUBTAG, "subscribe topic weather successful");
} else {
Log.e(SUBTAG, "subscribe topic failed,return value is" + task.getException().getMessage());
}
}
});
} catch (Exception e) {
Log.e(SUBTAG, "subscribe faied,catch exception:" + e.getMessage());
}
}
The figure below shows that the topic is successfully subscribed to.
The following is the sample code for unsubscribing from a topic:
Code:
public void unsubtopic(View view) {
String SUBTAG = "unsubtopic";
String topic = "weather";
try {
// Subscribe to a topic.
HmsMessaging.getInstance(PushClient.this).unsubscribe(topic).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(Task<Void> task) {
if (task.isSuccessful()) {
Log.i(SUBTAG, "unsubscribe topic successful");
} else {
Log.e(SUBTAG, "unsubscribe topic failed,return value is" + task.getException().getMessage());
}
}
});
} catch (Exception e) {
Log.e(SUBTAG, "subscribe faied,catch exception:" + e.getMessage());
}
}
The figure below shows that the topic is successfully unsubscribed from.
Managing Topic Subscription on Your App Server​
Obtaining an Access Token​
You can call the API (https://oauth-login.cloud.huawei.com/oauth2/v3/token) of the HMS Core Account Kit server to obtain an app-level access token for authentication.
Request for obtaining an access token
Code:
POST /oauth2/v3/token HTTP/1.1
Host: oauth-login.cloud.huawei.com
Content-Type: application/x-www-form-urlencoded
grant_type=client_credentials&
client_id=<APP ID >&
client_secret=<APP secret >
Demonstration of obtaining an access token
Subscribing to and Unsubscribe from Topics​
Your app server can subscribe to or unsubscribe from a topic for your app by calling the corresponding subscription and unsubscription APIs of the Push Kit server. The URLs of the subscription and unsubscription APIs differ slightly, but the header and body of the subscription request are the same as those of the unsubscription request. The details are as follows:
URL of the subscription API
Code:
https://push-api.cloud.huawei.com/v1/[appid]/topic:subscribe
URL of the unsubscription API
Code:
https://push-api.cloud.huawei.com/v1/[appid]/topic:unsubscribe
Example of the request header, where the token following Bearer is the access token obtained in the previous step
Code:
Authorization: Bearer CV0kkX7yVJZcTi1i+uk...Kp4HGfZXJ5wSH/MwIriqHa9h2q66KSl5
Content-Type: application/json
Example of the request body
Code:
{
"topic": "weather",
"tokenArray": [
"AOffIB70WGIqdFJWJvwG7SOB...xRVgtbqhESkoJLlW-TKeTjQvzeLm8Up1-3K7",
"AKk3BMXyo80KlS9AgnpCkk8l...uEUQmD8s1lHQ0yx8We9C47yD58t2s8QkOgnQ"
]
}
Request demonstration
Sending Messages by Topic​
You can send messages based on a created topic through the HTTPS protocol. The sample code for HTTPS-based messaging is as follows:
Code:
{
"validate_only": false,
"message": {
"notification": {
"title": "message title",
"body": "message body"
},
"android": {
"notification": {
"click_action": {
"type": 1,
"action": "com.huawei.codelabpush.intent.action.test"
}
}
},
"topic": "weather"
}
}
The figure below shows that the message is received and displayed on the user device.
Precautions​
1. Your app can subscribe to any existing topics, or create new topics. When subscribing to a topic that does not exist, your app will request Push Kit to create such a topic. Then, any other app can subscribe to this topic.
2. The Push Kit server provides basic APIs for managing topics. You can subscribe to or unsubscribe from a topic using a maximum of 1000 tokens at a time. Each app can have a maximum of 2000 different topics.
3. The subscription relationship between the topic and token takes effect one minute after the subscription is complete. After the subscription takes effect, you'll be able to specify one topic, or a set of topic matching conditions to send messages in batches.
That's all for integrating the topic-based messaging function. In addition to this function, I also found that Push Kit provides functions such as scenario-based messaging and geofence-based messaging, which I think are very useful because they allow apps to push messages that are suitable for users' scenarios to users.
For example, with the scenario-based messaging function, an app can automatically send messages to users by scenario, such as when headsets are inserted, the Bluetooth car stereo is disconnected, or the motion status changes. With the geofence-based messaging function, an app can send messages to users by location, such as when users enter a shopping mall or airport and stay there for a specified period of time.
These functions, I think, can help apps improve user experience and user engagement. If you want to try out these functions, click here to view the official website.
Conclusion​
The key to a successful app that stands out from the crowd is crafting messages that immediately grasp users' attention. This requires customizing messages by topic to match users' habits or interests, then regularly sending these messages to user devices via a push channel. As I illustrated earlier in this article, my solution for doing so is to integrate the topic-based messaging function in Push Kit, and it turns out to be very effective. If you have similar demands, have a try on this function and you may be surprised.

Categories

Resources