INTRODUCTION
In this article we will learn how to integrate the Push Kit into a Unity project from start to finish, constantly in groups and video game development communities questions and difficulties are triggered for developers so within this article I would like to touch on different problems that can be easily solved just by following a few steps and modifying certain values within the Unity editor.
{
"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"
}
MOST COMMON QUESTIONS IN DEV COMMUNITIES
Through the development communities, we have been presented with different questions that I have been collecting little by little, below I share some that are commonly repeated.
After importing the Evil Mind plugin, my project won't run on my device?
Add the Push Manager prefab and when I run the game in game mode it doesn't compile
How can I get the token that Push Kit returns to me when it is executed?
Unity cannot locate the Android SDK and I cannot run the project.
ARTICLE GOAL
Our goal in this article will be to be able to send a notification to our phone from App Gallery Connect using the token that HMS Push Kit gives us, we will achieve this by solving the problems that arise at the time of configuration.
STEPS
Configuration App Gallery Connect.
Configure Unity to run our project.
Import Evil Mind Plugin.
Configure our project with App Gallery Connect.
Create the class and the code to get the answer.
Obtain the log of our device
Add the token to App Gallery Connect
Try our game
APP GALLERY CONFIGURATION
As we know we must create a project in App Gallery Connect and add an app in order to configure the necessary data for our project. Let's start by logging into the AGC console to create a project.
Within the projects section we can create a new project where we must create an App which will be added to our project.
Once the application is created we must fill in the following data in the form, for this it will be necessary to create our project in Unity and assign the package name.
Let's go to unity to create the necessary data, Open unity and create a new project. Once the project is created, select Build Settings> Player Settings to assign your game data.
Remember to confirm that in Other Settings you also have your package correctly. Here we will answer one of the questions we have at the beginning of this article.
After importing the Evil Mind plugin, my project won't run on my device? This generally happens to us because we do not have the Backend value configured correctly and the minimum supported API, in the following image I share the data that you should place.
With this configuration we will be able to run our game on the device that we have connected, remember that if you are using a GMS device it will be necessary to install the HMS Core apk which you can download from this league. https://m.apkpure.com/es/hms-core/com.huawei.hwid/download once downloaded you can run huawei mobile services.
Running your project on the device should have a screen similar to this, we have not added the button yet but we will do it later, the important thing is that your scene compiles correctly.
UNITY CONFIGURATION
Let's start now with the configuration of our project in Unity. What we must do is import the Evil Mind plugin to be able to obtain the upper menu of Huawei and to be able to place the data obtained from AGC. Download the plugin from the repository that I share with you now. https://github.com/EvilMindDevs/hms-unity-plugin
Download the pcustom package to your computer and import it into Unity.
You must import it from the import tab and select custom package, once imported an option will be enabled in the upper menu with the title of Huawei, when you click on it you will get the following pop up.
Download the json file from AGC and replace it in Unity the path to find the json you can find in the following image
Open the agconnect file and start putting the necessary data to paste into the Huawei plugin. In the image I am showing you in yellow what data you must take to place them in the plugin window.
When you finish assigning the data, click on the Configure Manifest button. IMPORTANT JUST GIVE A CLICK, OTHERWISE YOU WILL ADD LINES TO YOUR MANIFEST AND THE ERROR WILL BE PRESENTED Merge Manifest.
Check your android Manifest take into account that when you import the plugin, a default Manifest will be downloaded in your project, that Manifest Default has packages that belong to the example, so it is important that you only have the following <providers> as I show in the image
Add the Push Manager prefab to your scene, you can also add a button inside a Canvas to initialize the Push Kit service, leave it in the onStart () method;
Run your project again to identify errors if they occur during the compilation and construction of the project. This will not generate any effect in Push Kit nor will it grant you the token because we have not configured the SHA256 signature, possibly the console will indicate that the fingerprint has not been configured. We are going to configure this signature. Create your keystore in your project folder, go to the folder where your project is with your console and execute the following command.
Replace the name of your keystore
keytool -list -v -keystore d:key.keystore
Get the Sha 256 and place it in AGC.
CODING
We will create a script that is responsible for initializing the service and granting us the token of our device and then sending the notification through token.
Java:
namespace HmsPlugin
{
public class PushKitManager : MonoBehaviour, IPushListener
{
public Action<string> OnTokenSuccess { get; set; }
public Action<Exception> OnTokenFailure { get; set; }
public Action<RemoteMessage> OnMessageReceivedSuccess { get; set; }
// Start is called before the first frame update
void Start()
{
PushManager.Listener = this;
var token = PushManager.Token;
Debug.Log($"[HMS] Push token from GetToken is {token}");
if (token != null)
{
OnTokenSuccess?.Invoke(token);
}
}
public void OnNewToken(string token)
{
Debug.Log($"[HMS] Push token from OnNewToken is {token}");
if (token != null)
{
OnTokenSuccess?.Invoke(token);
}
}
public void OnTokenError(Exception e)
{
Debug.Log("Error asking for Push token");
Debug.Log(e.StackTrace);
OnTokenFailure?.Invoke(e);
}
public void OnMessageReceived(RemoteMessage remoteMessage)
{
OnMessageReceivedSuccess?.Invoke(remoteMessage);
}
}
}
We will also create a method only as an example to be able to initialize the service and obtain the token
Java:
public void StartNotificationService()
{
PushManager.Listener = this;
var token = PushManager.Token;
Debug.Log($"The token {token}");
if(token != null)
{
}OnTokenSuccess?.Invoke(token);
}
Now we need to obtain the token of our phone and that the Log will return us and we will place it in the push notification service.
Fill in the necessary data to send the notification such as the Title, the Body and the name of the notification. You must also configure the device parameters. In this section is where you must add the token obtained from your device.
Now just launch the notification
TIPS AND TRICKS
I dont know how to obtain logs from my Android Device. In the following steps you'll learn how to debug from your Device.
For troubleshooting and debugging, it is often very helpful to capture the device logs. The device logs contain information about the status of a running application on the device and any errors encountered. The IAP Engineering team requires logs for open issues. It is assumed here that you have an Android device configured with Developer options and attached to a PC with a USB cable. These steps show the process on a Windows system and works similarly on a Mac
1. In Unity, find the location of the Android SDK. From the Edit menu, choose Preferences/External Tools
2. Look for the Android SDK. On my system it was C:\Users\[username]\AppData\Local\Android\sdk
3. Open a command prompt, and change to this directory.
4. Change directory to the platform-tools subdirectory.
5. You should see adb.exe in this directory.
6. With the device connected via USB, run the following command:
adb devices (Mac is ./adb devices)
7. This should return device serial number followed by the word "device"
8. Run "adb logcat | findstr -i unity" (use grep on Mac) in the terminal window. This will find anything with the word "unity" in the output, case insensitive.
9. This will provide the contents of the device log that are associated with a running Unity application
The output can be quite verbose. You can browse through the log however, looking for such words as "error" and "exception". Sometimes customer support will ask for device logs, in which case you can send the output to a text file with the command "adb logcat -d | findstr -i unity > log.txt"
CONCLUSION
Push notifications are one of the trending tools in marketing arenas. No arena has been left untouched by the tool- after engaging users brilliantly on an e-commerce store, it’s the turn of the gaming app push notifications.
Mobile gaming apps have gone too far popular in today’s arena so much so that mobiles have been developed specifically for the game, consisting of the hardware that would meet the demands of the users.In this article we learned how to implement HMS Kit Push notification in oour Unity Game an it was very fast.
REFERENCES
Push Kit - Cloud Message Push- Cross-Platform Messaging Solution - HUAWEI Developer
Push Kit can satisfy the relevance and freshness of content update that your users want. Push instant messages from the cloud to user devices.
developer.huawei.com
Read In Forum
SPANISH VIDEOTUTORIAL
If you speak or understand spanish here you have the videotutorial.
Related
This article is originally from HUAWEI Developer Forum
Forum link: https://forums.developer.huawei.com/forumPortal/en/home
{
"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"
}
HMS In-App Messaging is a tool to send relevant messages to target users actively using our app to encourage them to use key app functions. For example, we can send in-app messages to encourage users to subscribe to certain products, provide tips on passing a game level, or recommend activities of a restaurant.
In-App Messaging also allow us to customize our messages, the way it will be sent and also define events for triggering message sending to our users at the right moment.
Today I am going to server you a recipe to integrate In-App Messaging in your apps within 10 minutes.
Key Ingredients Needed
· 1 Android App Project, which supports Android 4.2 and later version.
· 1 SHA Key
· 1 Huawei Developer Account
· 1 Huawei phone with HMS 4.0.0.300 or later
Preparation Needed
· First we need to create an app or project in the Huawei app gallery connect.
· Provide the SHA Key and App Package name of the android project in App Information Section.
· Provide storage location in convention section under project setting.
· Enable App Messaging setting in Manage APIs section.
· After completing all the above points we need to download the agconnect-services.json from App Information Section. Copy and paste the json file in the app folder of the android project.
· Copy and paste the below maven url inside the repositories of buildscript and allprojects respectively (project build.gradle file)
Code:
maven { url 'http://developer.huawei.com/repo/' }
· Copy and paste the below class path inside the dependency section of project build.gradle file.
Code:
classpath 'com.huawei.agconnect:agcp:1.3.1.300'
· Copy and paste the below plugin in the app build.gradle file
Code:
apply plugin: 'com.huawei.agconnect'
· Copy and paste below library in the app build.gradle file dependencies section
Code:
implementation 'com.huawei.agconnect:agconnect-appmessaging:1.3.1.300'
· Put the below permission in AndroidManifest file.
a) android.permission.INTERNET
b) android.permission.ACCESS_NETWORK_STATE
· Now Sync the gradle.
Android Code
1. First we need AAID for later use in sending In-App Messages. To obtain AAID, we will use getAAID() method.
2. 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);
}
});
3. To initialize the AGConnectAppMessaging instance we will use.
Code:
AGConnectAppMessaging appMessaging = AGConnectAppMessaging.getInstance();
4. To allow data synchronization from the AppGallery Connect server we will use.
Code:
appMessaging.setFetchMessageEnable(true);
5. To enable message display.
Code:
appMessaging.setDisplayEnable(true);
6. 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.
Till now we added libraries, wrote the code in android studio using java etc. in the heated pan and the result will look like this:
Code:
public class MainActivity extends AppCompatActivity {
private String TAG = "MainActivity";
private AGConnectAppMessaging appMessaging;
private HiAnalyticsInstance instance;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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);
}
});
HiAnalyticsTools.enableLog();
instance = HiAnalytics.getInstance(this);
instance.setAnalyticsEnabled(true);
instance.regHmsSvcEvent();
inAppMessaging();
}
private void inAppMessaging() {
appMessaging = AGConnectAppMessaging.getInstance();
appMessaging.setFetchMessageEnable(true);
appMessaging.setDisplayEnable(true);
appMessaging.setForceFetch();
}
}
App Gallery Connect
Before we start using one of our key ingredients i.e. Huawei App Gallery Connect using Huawei Developer Account to serve In-App Messages, I would like to inform you that we can server the main dish into three different flavour or types:
A. Pop-up Message Flavour
B. Banner Message Flavour
C. An Image Message Flavour
In-App Message Using Pop-up Flavour
Let’s serve the main dish using Pop-up Message Flavour.
Step 1: Go to Huawei App Gallery Connect
Step 2: Select My projects.
Step 3: After selecting my projects, select the project which we have create earlier. It will look like this:
Step 4: After selecting the project, we will select App Messaging from the menu. It will look like this:
Step 5: Select New button to create new In-App Message to send to the device.
Step 6: Provide the Name and Description. It will look like this:
Step 7: In the Set style and content section, we have to select the type (which is Pop-up), provide a title, a message body, and choose colour for title text, body text and the background of the message. It will look like this:
Step 8: After providing the details in set style and content section, we will move on to the Image section. We will provide two image here for portrait and landscape mode of the app. Remember for portrait the image aspect ratio should be 3:2 (300x200) and for landscape the image aspect ratio should be either 1:1 (100x100) or 3:2 (300x200). It will look like this:
https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/001/647/156/2640091000001647156.20200512212645.95630192255042904397797509198276:50510525101557:2800:FA1CFD7E5EA43100725399BB4787A4B9FB44B8E02776FF83D09816D732E0AA63.png
Step 9: We can also provide a button in the Pop-up message using Button Section. The button contains an action. This Action contains two option. We can provide user with Disable Message action or redirect user to particular URL. The section will look like this:
Step 10: We will now move to the next section i.e Select Sending Target section. Here we can click New condition to add a condition for matching target users. Condition types include app version, OS version, language, country/region, audience, user attributes, last interaction, and initial startup.
Note: In this article, we didn’t used any condition. But you are free to use any condition to send targeted In-App Messages.
The section will look like this:
Step 11: The next section is the Set Sending Time section.
a) We can schedule a date and time to send message.
b) We can also provide an End date and time to stop sending message.
c) We can also display message on an events by using trigger event functionality. For example, we can display a discount of an item in a shopping app. A trigger event is required for each in-app message.
d) Also we can flexibly set the frequency for displaying the message.
This is how it will look:
Step 12: The last section is the Set Conversion Event section. As off now we will keep it as none. It will look like this:
Step 13: Click Save in the upper right corner to complete message creation. Also we can click Preview to preview the display effect of your message on a mobile phone or tablet.
Note: Do not hit the publish button yet. Just save it.
Step 14: 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. To that we need to find the message that you need to test, and click Test in the Operation column as it is shown below:
Step 15: Click Add test user and enter the AAID of the test device in the text box. Also run the app in order to find AAID of the test device in the logcat of the Android Studio.
Step 16: Finally we will publish the message. We will select publish in the operation column. It will look like this:
The Dish
More articles like this, you can visit HUAWEI Developer Forum.
This post will show you how to use Cocos2d-x on Android and integrate with Huawei mobile services.
What is Cocos?
Cocos have two main product Cocos Creator and Cocos2d-x.
Cocos2d-x — is a open-source, cross platform game engine. It includes the engine and the cocos command-line tool. Its let us to develop in C++, JavaScript or Lua.
{
"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"
}
Cocos Creator — is a unified game development tool focused on content creation. You can
create your entire game, from start to finish, using this tool. It uses JavaScript natively and can
export to C++. Read more about Cocos Creator. Cocos Creator integrates the entire mobile browser
game solution into the editor tool, eliminating the need to shuttle between multiple
software applications.
With the Cocos Creator editor open, a one-click automated process takes the least amount of time.
In this article we will focus Cocos2d-x game engine integration.
You can download stabile version from here. (cocos2d-x-3.17.2 used for this article).
Build Requirements
Python 2.7.5+(NOT Python 3)
NDK r16+ is required to build Android games(with android studio we will add)
Android Studio 3.0.0+ to build Android games(tested with 3.6.3)
Windows 7+ (tested with Windows 10)
Environment Setup
Unzip cocos installed file then run this command for setup environment.
Code:
cd cocos2d-x
setup.py
NDK Root Path Configuration
Skip this steps when the command prompt ask you to enter android sdk root path and ndk root path. We will configure paths with android studio. After installation restart your computer.
How to create a new game?
Single command line is enough to create a game.
Code:
cocos new <game name> -p
<package identifier> -l <language> -d <location>
cocos new MyGame -p
com.package.name -l cpp -d N PROJECTS_DIR
You can also create a Lua project with -l lua or JS project with -l js .
After create new project. Open “proj.android” folder in anroid studio.
Android Studio Configurations
File -> Settings -> Android SDK -> SDK Platforms: Download your android version to use
File -> Settings -> Android SDK -> SDK Tools:
Install
Android SDK Build-Tools
NDK
CMake
Android Emulator
Android SDK Platform-Tools
Android SDK Tools
Google USB Driver
Inter x86 Emulator
Note: Configure CPU architecture with “grandle.properties” file;
update Line "34" PROP_APP_ABI=armeabi-v7a:arm64-v8a:x86
Update android gradle plugin lates version. “../proj.android/gradle/wrapper/gradle-wrapper.properties”
NDK configuration
File -> Project Structure -> SDK Location -> Android SDK Location: Choose default one (we already download).
Cocos2d-x Main Components
Director: You can think of the Director the same way you think about a movie director.
The Director controls every aspect of your game. What is shown on the screen, what sounds
are played, what happens with player input, and much more.
Scene: A Scene is a container that holds Sprites, Labels, Nodes and other objects that
your game needs. A Scene is responsible for running game logic and rendering the content on a
per-frame basis.
Sprite: A Sprite is a 2D image that can be animated or transformed by changing its properties.
Most all games will havemultiple Sprite objects ranging from the hero, an enemy or a level boss.
Scene Graph: The scene graph is a data structure that arranges a graphical scene, into a
tree structure. This tree structure is what is used to render objects onscreen in a specific order.
Renderer: In an oversimplified definition the renderer is responsible for taking everything
you want on the screen and getting it there, technically. No need to delve into this further at this time.
Events: What do you do when the player moves around? What about touch events
or keyboard input? These all trigger events that can be acted upon as needed.
Audio: Perhaps your game has background music and or sound effects.
UI Components: Things like Button, Label, ScrollView, etc. Items that help you layout your
game and related interfaces.
Physics Engine: The physics engine is responsible for emulating the laws of physics
realistically within the application.
Well a Sprite is only a Sprite if you move it around. If you don’t move it around it is just a Node
How to use Huawei Mobile Services ?
Cocos2d-x provide the sdkbox to integrate mobile services. This tool help us to use Huawei mobile services.
This tools now supporting Account kit, Game Service, In-App Purchases. Ads kit now developing process and push kit also will come next versions.
Dowload from this link. Drag and drop zip file to your project.
Open a terminal and use the following command to install the SDKBOX HMS plugin. Normally we can download hms plugin directly but now its stating process because of that I use staging server to get plugin.
Code:
sdkbox import hms//staging server
sdkbox import HMS --staging
After this command our project build.gradle files will updated for HMS. If dependencies version are old you can update them.
HMS for android
Create App in AppGallery
Enable Module you need(enable AccountKit and Game Service,we will use this)
Configure app signature(release)
download app info agconnect-services.json
For detail you can follow this link.
Update gradle.properties file:
PROP_MIN_SDK_VERSION=17
RELEASE_STORE_FILE=yourSignFile.jks
RELEASE_STORE_PASSWORD=password
RELEASE_KEY_ALIAS=alias
RELEASE_KEY_PASSWORD=password
Cocos Development
Now our application is ready to run with HMS. We will invoke HMS function via plugin, before that I want to show Cocos file structure.
The resources folder is a common repository for all the various assets that your game will use, such as graphics, sound, etc.
The Classes folder is perhaps most important of all, this is where your non platform specific code goes.
An AppDelegate is a helper object that goes with the main window and handles events common to applications such as starting up, minimizing and closing. You won’t really spend much time here, that instead is where the Scene file comes in.
AppDelegate header is pretty straight forward, it declares a constructor, destructor and four methods, initGLContextAttrs, applicationDidFinishLaunching, applicationDidEnterBackground and applicationWillEnterForeground. All four of these methods are pure virtual functions from ApplicationProtocol, from which Application ( and in turn AppDelegate ) inherit, so we must provide an implementation of each, even if it’s empty
Initialize HMS
We will use AppDelegate.cpp for initialize the plugin.
Code:
#include
"PluginHMS/PluginHMS.h"
bool AppDelegate::applicationDidFinishLaunching()
{
#ifdef SDKBOX_ENABLED
sdkbox::PluginHMS::init();
#endif
AppDelegate class create HelloWorld screen. We will create menu screen for login and logout with HMS account kit.
Update HelloWorld.h for menu.
Code:
public:
......
void showMenu(const std::string& menuName);
void genMainMenu();
void genAccountMenu();
private:
cocos2d::Label*mTitle;
cocos2d::Menu*mMenu;
We will create listener for HMS and we will invoke this in init() function.
Code:
#include "HelloWorldScene.h"
#include "SimpleAudioEngine.h"
#include "PluginHMS/PluginHMS.h"
#include "json/rapidjson.h"
#include "json/document.h"
.....
//Listener for HMS
class PluginHMSListener : public sdkbox::HMSListener {
public:
PluginHMSListener(HelloWorld* scene): hw(scene) {
}
void onLogin(int code, const std::string& errorOrJson) {
cocos2d::log("HMS onLogin: %d, %s", code, errorOrJson.c_str());
if (0 != code) {
showMsg("login failed:" + errorOrJson);
return;
}
rapidjson::Document doc;
doc.Parse(errorOrJson.c_str());
std::ostringstream ss;
ss << "Login success:" << doc["displayName"].GetString();
showMsg(ss.str());
}
private:
HelloWorld* hw;
};
bool HelloWorld::init()
{
sdkbox::PluginHMS::setListener(new PluginHMSListener(this));
sdkbox::PluginHMS::buoyShow();
......
return true;
}
This function for login via HMS.
Code:
void HelloWorld::genAccountMenu() {
mMenu->addChild(MenuItemLabel::create(Label::createWithSystemFont("Login", "arial", 24), [](Ref*){
showMsg("to login...");
// sdkbox::PluginHMS::login(0); // slient login
sdkbox::PluginHMS::login(1); // login (id token)
// sdkbox::PluginHMS::login(2); // login (author code)
}));
mMenu->addChild(MenuItemLabel::create(Label::createWithSystemFont("Logout", "arial", 24), [](Ref*){
showMsg("to logout...");
sdkbox::PluginHMS::logout();
}));
}
Running a project
First runnig may take a long time. It will compile more than 600 cpp file.
After clicking “Account Test”:
After clicking “Login”.
Finally our project connected Huawei account.
Thanks for reading.
I hope this gives you a starting point for Cocos2d-x and integration with HMS. Feel free to check out the full source code in github.
Links:
codelab
Codelabs provide a technical expert guidance, tutorial and hands-on coding experience. Here you can learn about…
developer.huawei.com
http://docs.sdkbox.com/en/plugins/hms/v3-cpp/
More articles like this, you can visit HUAWEI Developer Forum
HUAWEI Analytics Kit 5.0 version has been updated, and it supports iOS SDK now, enabling one-stop, unified analysis of cross-platform Android and iOS users. It looks into user-centric analysis and helps you understand user behavior on the Android and iOS platforms. Today I want to share with you how to add Analytics Kit to your iOS App. The version I integrated is 5.0.0.300.
The general steps we will walk through include:
Configuring App Information in AppGallery Connect
Integrating the HMS Core SDK
Accessing HUAWEI Analytics Kit
Configuring App Information in AppGallery Connect
Follow the steps below to configure App Information in AppGallery Connect for your iOS application. If you have both an Android and an iOS version of your app, you can set them within the same project, this will allow you to finish the data analysis conveniently.
{
"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"
}
Getting Started:
1. Have your Bundle ID ready for your iOS app (ask your developers for this).
2. Go to AppGallery Connect and create a new project.
Once you’ve created a new project, you’ll see a page, and the side navigation bar shows the AGC's various function menus.
3. Click Add app, and create an iOS application.
Here the App package ID is the Bundle ID.
Click OK, and then you will get the configuration file agconnect-services.plist.
Click Manage APIs, and here we’ve already had the Analytics API enabled.
Back to the side navigation bar, and go to the HUAWEI Analytics tab, you will see all kinds of functions, including User analysis, Behavior analysis, etc. Select any menu to Enable Analytics service.
On the Project access settings page, set the data storage location, time zone, currency, user data storage time, and calendar week, and click Finish.
Integrating the HMS Core SDK (in Cocoapods Mode)
I prefer the Cocoapods Mode. You can also integrate the HMS Core SDK into the Xcode Project Manually.
1. Add the AppGallery Connect configuration file of the app to your XCode project.
a. Click Download agconnect-services.plist to obtain your iOS config file (agconnect-services.plist).
b. Move your agconnect-services.plist file into the root of your Xcode project.
2. Edit the Podfile file
a. Create a Podfile if you don't already have one:
$ cd your-project-directory
$ pod init
b. To your Podfile, add the pods that you want to use in your app: Add pod 'HiAnalytics', that is, the dependency for pod.
Example Podfile file:
Code:
# Uncomment the next line to define a global platform for your project
# platform :iOS, '9.0'
target 'HiAnalyticsSwiftDemo' do
# Comment the next line if you don't want to use dynamic frameworks
use_frameworks!
# Pods for HiAnalyticsSwiftDemo
pod 'HiAnalytics'
target 'HiAnalyticsSwiftDemoUITests' do
# Pods for testing
end
end
c. Install the pods, then open your .xcworkspace file to see the project in Xcode:
$ pod install
$ open your-project.xcworkspace
Accessing HUAWEI Analytics Kit
1. Initialize Analytics SDK in your app
The final step is to add initialization code to your application. Initialize AppDelegate through the config interface.
Objective C sample code: Perform initialization in AppDelegate.m.
Code:
#import "AppDelegate.h"
#import <HiAnalytics/HiAnalytics.h>
@interface AppDelegate ()
@end
@implementation AppDelegate
...
- (BOOL)Application:(UIApplication *)Application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after Application launch.
[HiAnalytics config];//Initialization
return YES;
}
...
@end
Swift code example: Perform initialization in AppDelegate.swift.
Code:
import UIKit
import HiAnalytics
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
...
func Application(_ Application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after Application launch.
HiAnalytics.config();//Initialization
return true
}
...
}
2. Record defined events using the onEvent API.
For definitions of the events, please refer to Event Description.
3. Call APIs of HUAWEI Analytics Kit to implement the corresponding functions. For details, please refer to API Reference.
During the development, you can use DebugView to view the event records in real time, observe the results, and adjust the event tracing scheme.
Enabling/Disabling the Debug Mode
1.To enable the debug mode:
Go to Product > Scheme > Edit Scheme from the Xcode menu. On the Arguments page, click + to add the -HADebugEnabled parameter. After the parameter is added, click Close to save the setting.
Code:
1. –HADebugEnabled
2.To disable the debug mode
Code:
1. -HADebugDisabled
After the data is successfully reported, you can go to HUAWEI App Debugging to view the data, as shown in the following figure.
Q&A:
1. I have integrated the iOS SDK of HUAWEI Analytics Kit into my app but why no log events are collected when the app is running?
When this problem occurs, it is probable that the run log parameters have not been set. You can set the log level to any of the following values: -HALogLevelDebug, -HALogLevelInfo, -HALogLevelWarn, and -HALogLevelError.
For example, to set the log level to -HALogLevelDebug, perform the following steps:
Choose Product > Scheme > Edit Scheme from the Xcode menu.
On the Arguments page, click + to add the -HALogLevelDebug parameter.
After the parameter is added, click Close to save the setting.
Face problems during development? Take it easy. Go to Stack Overflow and raise your questions. Huawei experts will get back to you as soon as possible.
https://stackoverflow.com/questions/tagged/huawei-mobile-services?tab=Newest
HUAWEI AppGallery Connect Cloud Storage provides maintenance-free cloud storage functions.Recently, the Cloud Storage Node.js SDK for server integration has been released. I’ve been using it for a while. You can also access the sample code on GitHub.
1. Configuring the Environment and Version InformationVersion:cloudstorage-server”: “1.0.0”
Environment:Window-Node -v14.15.0,npm v6.14.8,Visual Studio Code
Test Device:PC
cloudstorage-server”: “1.0.0”
AppGallery Connect: https://developer.huawei.com/consumer/en/service/josp/agc/index.html
SDK version: agconnect/cloudstorage-server”: “1.0.0”
SDK integration command: npm install — save @agconnect/cloudstorage-server
2. Enabling and Configuring Cloud Storage in AppGallery ConnectCurrently, Cloud Storage is still in beta testing. To use the service, you’ll first need to send an application by email. For details, visit the following address:
https://developer.huawei.com/consum...Gallery-connect-Guides/agc-cloudstorage-apply
Create an app first and add it to a project, or select an app from the project list on the My projects page in AppGallery Connect.
Under the project, go to Build > Cloud Storage, and click Enable now.
{
"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"
}
Configure a storage instance as required.
Define the security rules. In this example, the default rules are used.
Note: By default, only authorized users have read and write permissions.
3. Installing the Node.js EnvironmentI won’t be describing the detailed procedure for installing the Node.js environment, but here are a few tips:
1. You can download the Node.js package for Windows from this website: https://nodejs.org/en/download/.
2. When you install the environment, the related npm will be automatically installed. You can check its version number by running the following command.
3. I like to use Visual Studio Code (VS Code) for developing Node.js code. If you need to install one, here’s the website: http://code.visualstudio.com/
4. Once you’ve finished installing VS Code, open the testNodeJSDemo project, create a JavaScript file, and write some code.
5. Run the JavaScript file in VS Code. Go to RUN > Run and Debug. Select the Node.js file, and you can see the output at the bottom.
4. Integrating the SDK1. Open the CLI, go to your project directory, and run the npm init command to create the package.json file. Keep pressing Enter to apply the default parameters.
2. Run the following command to add the Server SDK dependency of Cloud Storage to the file:
Code:
npm install --save @agconnect/cloudstorage-server
3. Download the authentication credential of the Server SDK from AppGallery Connect and save the credential to the path of the created project. If no credential is available, just create one.
5. Developing Functionsa) Perform the initialization.You need to initialize both the Server SDK and the storage instance.
Code:
var { AGCClient, CredentialParser } = require("@agconnect/common-server");
var credential = CredentialParser.toCredential("./agc-apiclient-testnodejs.json");
AGCClient.initialize(credential);
const {StorageManagement} = require('@agconnect/cloudstorage-server');
b) Configure the storage instance.Copy the bucket name of the project in AppGallery Connect and run the following code to initialize the bucket:
Code:
let bucketName = '9105385871708601205-ffeon'; // Configure the storage instance in AppGallery Connect.
c) Upload a file.In this example, I upload the test123.txt file in the project path. You can use a file as required.
Code:
// uploadFile();
function uploadFile() {
const storage = new StorageManagement();
const bucket = storage.bucket(bucketName);
bucket.upload('./test123.txt')
.then(res => console.log(res))
.catch(err => console.log(err));
}
d) Download a file.Here, I download the test123.txt file from the root directory on the cloud and rename the downloaded file test_download.txt. This is just an example.
Code:
const fs = require('fs');
// downloadFile();
function downloadFile() {
const storage = new StorageManagement();
const bucket = storage.bucket(bucketName);
const remoteFile = bucket.file('test123.txt');
const localFile = './test_download.txt';
remoteFile.createReadStream()
.on('error', err => {
})
.on('end', () => {
})
.pipe(fs.createWriteStream(localFile))
}
e) Delete a file.Here, I delete the test123.txt file in the root directory from the cloud. This is also an example.
Code:
// deleteFile();
function deleteFile() {
const storage = new StorageManagement();
const bucket = storage.bucket(bucketName);
const file = bucket.file('test123.txt');
file.delete().then(res => {
}).catch(err => {
})
}
f) List all files.Here, I list all files in the root directory from the cloud.
Code:
//getFileList();
function getFileList() {
const storage = new StorageManagement();
const bucket = storage.bucket(bucketName);
bucket.getFiles({delimiter: '/'}).then(res => {
console.log(res)
}).catch(err => {
console.log(err);
})
}
6. Verifying Functions1. Verify the upload function.Delete the comment tag before uploadFile(); and run the node CloudStorage.js command to upload a file.
We can now see the uploaded test123.txt file in AppGallery Connect.
2. Verify the download function.Delete the comment tag before downloadFile(); and run the node CloudStorage.js command to download a file. If you see no information, don’t worry, it’s normal.
You’ll then see the downloaded test_download.txt file in the following path.
3. Verify the function of listing files.Delete the comment tag before getFileList(); and run the node CloudStorage.js command to view all files in the root directory. The following information is displayed.
You can see the same files displayed in AppGallery Connect.
4. Verify the deletion function.Delete the comment tag before deleteFile(); and run the node CloudStorage.js command to delete a file. This function will also give back no output.
You can see that the test123.txt file in AppGallery Connect has been deleted as well.
7. SummaryCloud Storage allows you to manage your project files using Node.js code without the hassle of building a server and O&M. Also, with AppGallery Connect, a web console, you can easily manage your files on the cloud.
In addition to file upload, download, and deletion, Cloud Storage also offers functions such as listing files and setting metadata.
Cloud Storage development guide:
https://developer.huawei.com/consum...-connect-Guides/agc-cloudstorage-introduction
Cloud Storage sample code:
https://github.com/AppGalleryConnec...ster/agc-cloudstorage-demo-nodejs/nodejs-demo
Is it free of cost?
Cloud Storage needs any prior permissions or approvals to use in app ?
Basavaraj.navi said:
Is it free of cost?
Click to expand...
Click to collapse
It has 10 GB of free storage per month, beyond which a fee will be charged. For more details, see this document.
shikkerimath said:
Cloud Storage needs any prior permissions or approvals to use in app ?
Click to expand...
Click to collapse
Cloud Storage is still in beta state. To use this service, send an email to [email protected] for application.After this, you can use it directly!
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Introduction
In this article, I will explain how to subscribe the topic using integrating the Huawei Push Kit into React Native project. React Native is a tool announced and open-sourced by Facebook in April 2015. It is a cross-platform mobile app development framework that is derived from Facebook's earlier open-source JavaScript framework React. It helps to adapt to native mobile app platforms.
Push Kit
Push notifications offers a great way to increase your application’s user engagement and boost your retention rates by sending meaningful messages or by informing users about your application. Push Kit supports two types of messages: notification messages and data messages. You can send notifications and data messages to your users from your server using the Push Kit APIs or directly from the AppGallery Push Kit Console.
Requirements
1. Any operating system (MacOS, Linux and Windows).
2. Must have a Huawei phone with HMS 4.0.2.300 or later.
3. Must have a laptop or desktop with Android Studio, Jdk 1.8, SDK platform 26 and Gradle 4.6 installed.
4. Minimum API Level 21 is required.
5. Required EMUI 9.0.0 and later version devices.
Integrate HMS Dependencies and React Native Project Preparation
1. First register as Huawei developer and complete identity verification in Huawei developers website, refer to register a Huawei ID.
2. Create a project in android studio, refer Creating an Android Studio Project.
3. Generate a SHA-256 certificate fingerprint.
4. To generate SHA-256 certificate fingerprint. Choose View > Tool Windows > Gradle > Signingreport > SHA256 code.
Or use cmd as explained in SHA256 CODE
5. Create an App in AppGallery Connect.
6. Download the agconnect-services.json file from App information, copy and paste in android Project under app directory.
7. Enter SHA-256 certificate fingerprint and click Save, as follows.
8. Click Manage APIs tab and enable Push Kit.
9. Environment set up, refer below link
https://reactnative.dev/docs/environment-setup
10. Create project using below command
Code:
react-native init projectname
11. You can install react native command line interface on npm, using the install -g react-native-cli command as shown below.
Code:
npm install –g react-native-cli
12. Integrate the Hmspush plugin
npm i @hmscore/react-native-hms-push
13. Add the AGC Plugin dependency.
Code:
apply plugin: 'com.huawei.agconnect'
14. Add to dependencies.
Code:
Implementation project (': react-native-hms-push)
15. Project level build.gradle/buildScript directory set minSdkVersion to 19 or higher higher. In android/signingConfigs/config node, enter the keystore file credentials.
Code:
signingConfigs {
config {
storeFile file(<keystore_file_name>)
storePassword ‘<store_password>’
keyAlias ‘<alias>’
keyPassword ‘<key_password>’
}
}
16. Navigate to App level android/build.gradle directory in your React Native project. Follow the steps:
-Add to buildscript/repositories
Code:
maven {url 'http://developer.huawei.com/repo/'}
-Add to buildscript/dependencies
Code:
classpath 'com.huawei.agconnect:agcp:1.3.1.300’'3)
17. Navigate to android/settings.gradle and add the following.
Code:
include ':react-native-hms-push'
project(':react-native-hms-push').projectDir = new File(rootProject.projectDir, '../node_modules/@hmscore/react-native-hms-push/android')
18. Add below permissions in Android.manifest file.
XML:
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Development
Obtain a Token:
In order to push notifications to a device, you need to obtain a token. To get the token, use getToken method from HmsPushInstanceId module.
JavaScript:
HmsPushInstanceId.getToken("")
.then((result) => {
this.log("getToken", result);
})
.catch((err) => {
alert("[getToken] Error/Exception: " + JSON.stringify(err));
});
Add Push Notifications
To push a notification message to your device, navigate to your Huawei developer console and choose Project>Growing>Push Kit>Add notification.
Subscribing the Topics
Subscribing to a topic enables the users to receive data messages by the subscribed topic. To subscribe a topic, use subscribe method from HmsPushMessaging module.
JavaScript:
subscribe() {
HmsPushMessaging.subscribe(this.state.topic)
.then((result) => {
this.log("subscribe", result);
})
.catch((err) => {
alert("[subscribe] Error/Exception: " + JSON.stringify(err));
});
}
To push a notification or data message by topic, navigate to the Huawei push console to push a new notification, choose push scope as Subscriber and then select the topic of the message to be sent.
Unsubscribe the topics
Unsubscribing from a topic lets the user not to listen data messages by the unsubscribed topic. To unsubscribe from a topic, use unsubscribe method of the HmsPushMessaging module.
JavaScript:
unsubscribe() {
HmsPushMessaging.unsubscribe(this.state.topic)
.then((result) => {
this.log("unsubscribe", result);
})
.catch((err) => {
alert("[unsubscribe] Error/Exception: " + JSON.stringify(err));
});
}
Run the application (Generating the Signed Apk):
1. Open project directory path in command prompt. Navigate to android directory and run the below command for signing the apk.
Code:
gradlew assembleRelease
Result
Tips and Tricks
1. Set minSDK version to 24 or later, otherwise you will get AndriodManifest merge issue.
2. Make sure you have added the agconnect-services.json file to app folder.
3. Make sure you have added SHA-256 fingerprint without fail.
4. Make sure all the dependencies are added properly.
5. For project cleaning navigate to android directory and run the below command.
Code:
gradlew clean
Conclusion
In this article, we can learn about how to integrate Push Kit and how to subscribe the topic in React native project. It will guide you to increase your application’s user engagement and boost your retention rates by sending meaningful messages or by informing users about your application.
Reference
Push Kit: Documentation
Push Kit: Training Video