Ads Kit Integration with Cocos - Huawei Developers

1. Cocos Creator tool
2. Notepad++ for editing and writing script
3. HMS Device
4. Android Studio for Analyzing APK and Checking Log
1. Install and launch cocos creator.
2. Make sure to configure NDK Root and Android SDK Root in Cocos Creator, choose File> Settings>Select Native Develop.
In the same build popup, In the keystore section we can use default keystore (default location is /Users/<username>/.android/debug.keystore) and we can generate SHA key or we can create custom keystore and can generate SHA key.
In Command line terminal execute the command below and get SHA key:
Code:
keytool -list -v -keystore keystorepath\keystorename.keystore
4. Step 1: Create a project in AppGallery using created SHA key
Step 2: Configure the signing certificate fingerprint
Choose Project settings > General information. In the App information area, click the icon next to SHA 256 certificate fingerprint, and enter the obtained SHA-256 certificate fingerprint.
Step 3: Download agconnect-services.json file and put in setting folder in cocos project.
Example:
Right click on Assets folder and then select Open in explorer and
{
"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"
}
And put agconnect-services.json file inside settings folder
5. Click Enable for Cocos SDKHub in Service tab.
Click on association button and register project in Cocos Console
Associating a Game in Cocos Creator
You can enable third-party services for your app in Cocos Creator. But first, you need to set a Cocos AppID. Select a created game, and click Association, as shown in the following figures.
Select Ads option in Plugin Manager under Service tab.
Place mouse cursor over the "Configured" text so that "Edit" and "Delete" icons will be appeared. Click on edit icon and put public key(from AppGallery connect) in the "Payment Public key" field and select "en" option for "Support language" field and then click OK.
Code:
invokeBannerAds()
{
var params = { "adType": "Banner", "adId": "testw6vs28auh3", "pos": "0", "adSize": "BANNER_SIZE_320_50" };
sdkhub.getAdsPlugin().showAds(params);
},
invokepreloadrewardAds()
{
var params = { "adType": "Reward", "adId": "testx9dtjwj8hp" };
sdkhub.getAdsPlugin().preloadAds(params);
},
invokeRewardAds()
{
var params = { "adType": "Reward", "adId": "testx9dtjwj8hp" };
sdkhub.getAdsPlugin().showAds(params);
},
invokeNativeAdfull()
{
var params = { "adType": "Native", "adId": "testy63txaom86", "nativeLayout": "native_full", "requestCustomDislikeThisAd": "1", "choicesPosition": "3", "videoConfiguration" : "1", "audioFocusType" : "NOT_GAIN_AUDIO_FOCUS_WHEN_MUTE", "startMuted" : "0", "customizeOperateRequested" : "1"};
sdkhub.getAdsPlugin().showAds(params);
},
invokeNativeAd()
{
var params = { "adType": "Native", "adId": "testy63txaom86", "nativeLayout": "native_small", "requestCustomDislikeThisAd": "1", "choicesPosition": "3", "videoConfiguration" : "1", "audioFocusType" : "NOT_GAIN_AUDIO_FOCUS_WHEN_MUTE", "startMuted" : "0", "customizeOperateRequested" : "1"};
sdkhub.getAdsPlugin().showAds(params);
},
invokepreIntertitialsAds()
{
var params = { "adType": "Interstitial", "adId": "testb4znbuh3n2" }; sdkhub.getAdsPlugin().preloadAds(params);
},
invokeIntertitialsAds()
{
var params = { "adType": "Interstitial", "adId": "testb4znbuh3n2" };
sdkhub.getAdsPlugin().showAds(params);},
Banner Ad
Native Ad small
Native Ad Full
Reward Ad
Interstitial Ad
Tips and Tricks
1. Make sure to keep the same package name as kept in the Huawei AppGallery Connect project.
2. Both rewarded ads and interstitial ads need to call preloadAds first, and then call showAds afte receiving successful callback. Banner ads can directly call showAds
Conclusion:
HUAWEI Ads Service is a monetization service that leverages Huawei’s extensive data capabilities to display targeted, high quality ad content in your apps to the vast user base of Huawei devices.
References:
https://docs.cocos.com/creator/manual/en/cocos-service/sdkhub-plugins/sdkhub-hms.html
https://developer.huawei.com/consumer/en/hms/huawei-iap/

Hi, this topic is regarding HMS Ads Service, but you given In-App-Purchase link in reference.

Great news!

Good new Incoming about Huawei

Related

Integrate Unity & Account Kit

Unity & HMS account kit integration.
In this article, we will integrate HMS account kit with Unity. We will perform Login & Logout.
Requirements ->
Unity Editor
Huawei device
Visual Studio
Output --> Upon succeful login User will get display name and other details, On UI i am populating DisplayName like below.
{
"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"
}
Step 1 Create Unity 3d project
Step 2 Register project on HMS Console as Game.
(Dont forget to put SHA key from keystore file)
Step 3 Collect below information
Step 4 Download HMS Unity Plugin (HMS Unity Plugin v1.1.2) from
Code:
https://github.com/EvilMindDevs/hms-unity-plugin/releases
Step 5 Import this plugin in Unity project like show below
Step 6 Additoinal Configuration using HMS Plugin, click on Huawei -> App Gallery
Step 7
in step 3 we collected information which we need to fill here in Huawei Plugin Editor, like show below
Step 8 Once information is filled a button will appear "Configure Manifest", click on that and close editor
Step 9 Verify details in manifest file, you can find this file in below location
Assets -> Plugins -> Android -> AndroidManifest.xml
We need to verify above filled details in this file like show below
Step 10 Update & Verify package name like below
File -> BuildSettings -> Android -> Player Settings -> Other Settings
Step 11 Install Unity Remote apk in your huawei device for running and debugging project
Please use custom keystore
Build the project and try to run -> if it gives error like manifest merger failed, which i got, open manifest file in text editor and fix it, if it has duplicate providers, once done you can see ur project running in huawei device
Step 12 HMS Plugin apis will be available as soon as prefab is added to the scene like below
Where to find prefab -> Assets -> Huawei -> Prefabs
Step 13 Scripting
I am going to create 2 scripts, both are conncted on my Player (U can connect on any element)
PlayerController - I used this to initalize HMS Account Kit
UpdateDetails - to update user name on canvas received from HMS account service.
PlayerController.cs
Code:
using System.Collections;
using System.Collections.Generic;
using HmsPlugin;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float runSpeed;
Rigidbody myRb;
Animator myAnim;
bool facingRight;
private AccountManager accountManager;
UpdateDetails updateDetails;
// Start is called before the first frame update
void Start()
{
updateDetails = GetComponent<UpdateDetails>();
myRb = GetComponent<Rigidbody>();
myAnim = GetComponent<Animator>();
facingRight = true;
accountManager = AccountManager.GetInstance(); // Initialization of account manager
accountManager.OnSignInSuccess = OnLoginSuccess;
accountManager.OnSignInFailed = OnLoginFailure;
Debug.LogWarning("kamal Start");
accountManager.SignIn(); // login
}
public void OnLoginSuccess(HuaweiMobileServices.Id.AuthHuaweiId authHuaweiId)
{
//loggedInUser.text = string.Format(LOGGED_IN, authHuaweiId.DisplayName);
Debug.LogWarning("kamal OnLoginSuccess-->"+ authHuaweiId.DisplayName);
updateDetails.updateUserName("Welcome "+authHuaweiId.DisplayName);
}
public void OnLoginFailure(HuaweiMobileServices.Utils.HMSException error)
{
//loggedInUser.text = LOGIN_ERROR;
Debug.LogWarning("kamal OnLoginSuccess");
updateDetails.updateUserName("error in login-- " + error.Message);
}
// Update is called once per frame
void Update()
{
}
}
UpdateDetails.cs -> update details on UI Canvas
Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class UpdateDetails : MonoBehaviour
{
public Text userName;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public void updateUserName(string name) {
Debug.LogWarning("kamal updateUserName-->" + name);
userName.text = name;
}
}
Result -> User name is shown on UI after login using HMS account kit.
What about Logout -> User below code snipped
Code:
accountManager.SignOut();
Nice article
I am not able to retreive email id of user once successful login, it gives me null. what might be the reason

Integration of Huawei IAP Kit in Cocos

Introduction:
In this article, we will cover the Integration of IAP kit in Cocos Project using Official Plugin (Huawei HMS Core App Services).
Requirements:
1. Cocos Creator
Make sure to configure NDK Root and Android SDK Root in Cocos Creator under File>Settings>Select Native Develop.
2. Huawei device
3. Visual Studio Code
Follow the steps.
Step 1. Create Cocos project.
· Click on CocosDashboard, click New.
{
"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"
}
· Select empty Name and then click Create and Open.  
 Step 2: Enable Cocos SDKHub
  Choose Panel > Service in the menu bar to open the Service panel. After setting Cocos AppID, select Cocos SDKHub to enter the Cocos SDKHub service panel.
 Click the Enable button on the upper right to activate the Cocos SDKHub service, as shown below.
 Click on IAP option to enable IAP, as shown below.
  Step 3: Create an app in Huawei AppGallery Connect.
1. Configure IAP in Huawei AGC Console and place agconnect-services.json file in game project under setting folder.
2. Choose Project settings > Manage APIs, and enable In-App Purchases.
· Configure IAP products in AGC Console.
Step 4: Open Cocos creator.
1. Right-click on the assets folder and select Scene under File and name it. This file will contain all information inside your scene.
2. Right-click on the assets folder and select JavaScript under File and name it. This file will contain functions to perform some operation.
Step 5: Open the IapScript file and add a function to call the equivalent method of createPurchaseIntent() of java in Cocos and save the file. Use the below code.
Code:
payForProduct() {
var params = {
Product_Id: "product_id", // Product ID. Each product must have a unique ID
EXT: "Cocos Consumables Product 1", //Information stored on the merchant side, which is passed by the app when the payment API is called
};
sdkhub.getFeePlugin().feeForProduct(params);
},
Add below code inside onLoad() function. Call to the above function will give a callback to onFeeResult method that we need to define in the IapScript file.
Code:
onLoad(){
sdkhub.getFeePlugin().setListener(this.onFeeResult, this);
},
Step 6: Drag a Button from the Node Library panel to canvas and increase the Click Events to 1.
Step 7: Drag the script file to the Node tree.
Step 8: Select the button and drag the script file from the Node tree to cc.Node under Properties and select function which needs to be called from the script file.
Step 9: Once the product is purchased, they need to be consumed after that consumable product is successfully delivered.
  When sdkhub.getFeePlugin().feeForProduct(params) is called gives a callback to onFeeResult.
Code:
onFeeResult: function (code, msg) {
if (code == 30104) {
console.log("Product consumed - "+ msg) // product consumed successfully
}
var params = JSON.parse(msg);
switch (code) {
// Process the "consumeOwnedPurchase" method logic, pay succeed
case sdkhub.FeeResultCode.kFeeSucceed:
sdkhub.getFeePlugin().callFuncWithParam("consumeOwnedPurchase", params.inAppPurchaseData); // consume Owned product Purchase
break;
}
},
Step 10: Click on Build under the Project tab to generate APK file. Build project, and then click Compile. Once code compile is done, click Play to run APK on connected phone.
Make sure to keep the same package name as kept in the Huawei AppGallery Connect project.
Conclusion:
In-app purchases are one of the main sources of revenue for game apps and is a very important feature that aggregates global mainstream payment methods, covering more than 178 countries and regions. In-app purchase provides a product management system (PMS) for managing the prices and languages of products in apps (including gaming apps) in multiple locations.
References:
https://docs.cocos.com/creator/manual/en/cocos-service/sdkhub-plugins/sdkhub-hms.html
https://developer.huawei.com/consumer/en/hms/huawei-iap/
Can the public payment key be exposed on the app?

How Can I Quickly Integrate Cloud Functions of AppGallery Connect into My Cocos-based App?

1. Environment
SDK Version:agconnect-storage:1.3.0.300
Platform:Cocos Creator
Device:HUAWEI P40 Pro
AppGallery Connect:
https://developer.huawei.com/consumer/en/service/josp/agc/index.html
2. Enabling and Configuring Cloud Functions in AppGallery Connect
Note: Currently, Cloud Functions is still under beta state. To use the service, you need to send an email for application. For details, check:
https://developer.huawei.com/consum...allery-connect-Guides/agc-cloudfunction-apply
1. 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 Functions, and click Enable now.
2. Create a function based on the description in the following codelab.
https://developer.huawei.com/consumer/en/codelab/CloudFunctions/index.html#4
3. Create an HTTP trigger and save the suffix of the value of Trigger URL in the Details area as the trigger identifier of future client requests.
{
"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"
}
3. Integrating the Cloud Functions SDK in Cocos Creator
1. Integrate the SDK.
Official documentation:
https://docs.cocos.com/creator/manual/en/cocos-service/agc-applinking.html
1. On the Service panel of Cocos Creator, find Cloud Functions. Currently, the Cloud Functions SDK supports only the Android platform.
2. Before integrating a service, you need to associate the service with an app. Click Association. In the dialog box that is displayed, click Create. The Cocos console is displayed.
3. On the Cocos console, create a game.
4. Go back to Cocos Creator and create, refresh, or select an association.
5. Return to the Cloud Functions page, and enable the service.
2. Download the JSON file.
1. Go to Project settings in AppGallery Connect and download the latest agconnect-services.json file.
2. Save the downloaded agconnect-services.json file to the settings directory in your Cocos project.
4. Configuring the UI Layout
Configure buttons for triggering a cloud function, obtaining the timeout interval, and setting the timeout interval separately.
5. Cloud Functions Development
1. Initialize Cloud Functions in the start block.
Code:
start () {
this._func = huawei.agc.func.funcService;
},
2. Call Cloud Functions with input parameters.
Code:
callWithParam:function() {
this._func.wrap("testcodelab-$latest").call((err, data) => {
if (err !== null) {
console.log("Cloud Function", `error: ${JSON.stringify(err)}`);
}
console.log("Cloud Function", `result: ${JSON.stringify(data)}`);
}, {
year: "2020",
}
);
},
3. Call Cloud Functions without input parameters.
JavaScript:
callWithoutParam:function() {
this._func.wrap("testcodelab-$latest").call((err, data) => {
if (err !== null) {
console.log("Cloud Function", `error: ${JSON.stringify(err)}`);
}
console.log("Cloud Function", `result: ${JSON.stringify(data)}`);
});
},
4. Obtain and set the timeout interval of a function.
JavaScript:
setTime:function() {
this._func.wrap("testcodelab-$latest").setTimeout(100,3);
console.log("Cloud Function", `setTime: ` + 100);
},
getTime:function() {
let currTime = this._func.wrap("testcodelab-$latest").getTimeout();
console.log("Cloud Function", `currTime: ` + currTime);
},
6. Packaging and Testing
In Cocos Creator, go to Project > Build…, package an Android app, and install it to your device. To verify the functions, click the buttons from top to bottom.
If the following information is displayed in JavaScript logs, the integration is successful.
7. Summary
Cloud Functions allows you to keep all functions and related code on the cloud side. You only need to call the wrap.call method to trigger the functions, which reduces the code amount and package size of your APK package.
For more details, please check:
Cloud Functions development guide:
https://developer.huawei.com/consum...connect-Guides/agc-cloudfunction-introduction
Cocos documentation:
https://docs.cocos.com/creator/manual/en/cocos-service/agc-cloudfunc.html

Simplified & Efficient Integration of Huawei Scan Kit in Xamarin Android App

Overview
In this article, I will create a demo app along with the integration of Huawei Scan Kit which is based on Cross-platform Technology Xamarin. User can easily scan 1D and 2D barcodes using this application. This Xamarin based application easily detects, magnifies, and recognizes barcodes from a distance. I will provide the easy way of implementing scan kit in Xamarin app.
Service Introduction
Huawei Scan Kit allows reading barcodes in any form like 1D and 2D. It also provides the best scan mechanism to detect, magnifie and recognize the barcodes. it automatically captures the whole barcode even in lowlight, reflective, dirty, blurry, or printed.
Scan Kit supports 13 formats of barcodes such as-
1D barcodes: EAN-8, EAN-13, UPC-A, UPC-E, Codabar, Code 39, Code 93, Code 128, and ITF
2D barcodes: QR code, Data Matrix, PDF417, and Aztec
Scan Kit provides 4 views of scan barcodes.
1. Default View- Scan barcodes using the camera or from images in the album.
2. Customized View- Scan barcodes using the camera.
3. Bitmap- Scan barcodes using the camera or from images in the album.
4. Multiprocessor- Scan barcodes using the camera or from images in the album.
Recognize multiple barcodes simultaneously.
Work with ML Kit to recognize different objects (such as barcodes and faces) at the same time.
Prerequisite
1. Xamarin Framework
2. Huawei phone
3. Visual Studio 2019
App Gallery Integration process
1. Sign In and Add 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. Navigate to Project Setting > Add app
3. Add SHA-256 key
4. Navigate to Project settings > download the configuration file
Xamarin Scan Kit Setup Process
1. Download Xamarin Plugin all the aar and zip files from below URL-
https://developer.huawei.com/consum...y-V1/xamarin-sdk-download-0000001057674337-V1
2. Open the XHmsScan-1.2.3.300.sln solution in Visual Studio
3. Navigate to Solution Explorer > Right click on jar > Add >Exsiting Item and choose aar file which downloaded in Step 1
4. Right click on added aar file then choose Properties > Build Action > LibraryProjectZip
Note- Repeat Step 3 & 4 for all aar file
5. Build the Library and make DLL files
6. Success Build
Xamarin App Development
1. Open Visual Studio 2019 and Create a new project
2. Navigate to Solution Explore > Project > Add Folder > Add Json file
3. Navigate to Solution Explore >Project > Add > Add New Folder and keep all DLL files
4. Navigate to Folder(created) > Add > Add Existing and add all DLL files then Select all DLL files and Right Click > Properties >Build Action >None
5. Navigate to Solution Explore > Project > Reference > Right Click > Add References then Navigate to Browse and add all DLL files from recently added Folder
6. Navigate to Solution Explore > Project > Add > Class > Activity
MainActivity.cs
In this activity, I will redirect all the scan view based activity.
Code:
using Android.App;
using Android.OS;
using Android.Support.V7.App;
using Android.Runtime;
using Android.Widget;
using Android.Content;
namespace Demo
{
[Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)]
public class MainActivity : AppCompatActivity
{
private Button btnImage, btnDefault, btnCustom;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
SetContentView(Resource.Layout.main_view);
btnImage = FindViewById<Button>(Resource.Id.btn_bitmap);
btnImage.Click += delegate
{
Intent intent = new Intent(this, typeof(ImageActivity));
StartActivity(intent);
};
btnDefault = FindViewById<Button>(Resource.Id.btn_bitmap);
btnDefault.Click += delegate
{
Intent intent = new Intent(this, typeof(DefaultActivity));
StartActivity(intent);
};
btnCustom = FindViewById<Button>(Resource.Id.btn_bitmap);
btnCustom.Click += delegate
{
Intent intent = new Intent(this, typeof(DefinedActivity));
StartActivity(intent);
};
}
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);
}
}
}
For more, you can check https://forums.developer.huawei.com/forumPortal/en/topic/0203454633259850011

Using Huawei App Messaging in Flutter

Huawei AppGallery Connect’s App Messaging service allows you to send targeted, useful in-app messages to your users.
The look and content of messages are completely customisable, and there is a wide range of triggers and filters that can be used to decide who will receive a message and when.
Let's take a look today at how we can set this up to work within a flutter project.
As always we will start with a fresh project but of course, you can just as easily use this guide to build the service into an app you already have!
Installing the Flutter Environment​
Download the Flutter SDK.
Decompress the package to any directory.
Add the Flutter command file to the environment variable.
Download the Flutter and Dart plugins in Android Studio.
{
"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"
}
Enabling the Service and Creating a Flutter project​Sign in to AppGallery Connect, click My projects, click your project, go to Grow > App Messaging, and click Use now. For more information, please refer to App Messaging.
If you do not have an Android project, create one first.
After completing these steps, you can start creating an in-app message.
Click New in the upper right corner.
Set Name and Description
Set the style and content and click Next.
Select a message type from the Layout drop-down list, and set its style and content. Currently, the Modal, Image, and Banner message types are supported.
Set target users and click Next.
In App, select the name of the app package for which you need to publish the in-app message.
You can click New condition to add a condition for matching target users, which include app version, OS version, language, country/region, audience, and more. Among the types, User attributes are defined under HUAWEI Analytics > Management > User attributes, and Prediction is defined by creating prediction tasks under My projects > Grow > Prediction.
Set the message sending time
Message display is triggered by specific events. App Messaging supports two types of trigger events: preset events and HUAWEI Analytics events.
(Optional) Set conversion events. Before setting a conversion event, you need to toggle it on first, which can be done as follows:
Go to HUAWEI Analytics > Management > Events and toggle Mark as conversion event and Event switch on for the specified event. In addition to the events the SDK collects, you can also create a preset or custom event for event tracking and analysis.
Finally, Click Save or Publish.
Integrating the Service SDK​Add dependencies​Start by creating a Flutter project in Android Studio (or opening one).
Then add the agconnect-services.json file from your AppGallery project to the android/app directory
Within the project level build.gradle file make sure to include the huawei maven repo and add the agcp package as a dependency.
Code:
buildscript {
repositories {
google()
mavenCentral()
maven { url 'https://developer.huawei.com/repo/' }
}
dependencies {
classpath 'com.android.tools.build:gradle:7.0.4'
classpath 'com.huawei.agconnect:agcp:1.6.2.300'
}
}
Next in your app level build.gradle apply the agconnect plugin as so:
Code:
apply plugin: 'com.android.application'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
apply plugin: 'com.huawei.agconnect'
Then in your pubspec.yaml file add the App Messaging SDK dependency.
Code:
dependencies:
flutter:
sdk: flutter
agconnect_appmessaging: ^1.2.0+300
Displaying an In-App Message​If you choose to display a message using the default message layout, the development process is totally coding-free.
By integrating the SDK as above you are all good to go, your creating message will be displayed as per its filters and triggers.
You can also call APIs provided by the service SDK to customize your in-app message.
Customising the Message Layout​Add the following code to onCreate in MainActivity,
Code:
AGCAppMessagingCustomEventStreamHandler.addCustomView();
so that the service SDK can listen to the corresponding event and apply the customized layout.
Code:
streamSubscriptionDisplay = agconnectAppmessaging.customEvent.listen((event) {
showDialog(context ,event.toString());
agconnectAppmessaging.handleCustomViewMessageEvent
(AppMessagingEventType.onMessageDismiss(AppMessagingDismissTypeConstants.CLICK));
});
Then the message is displayed in your app.
Code:
void _showDialog(BuildContext context, String content) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
key: Key("dialog"),
title: Text("Result"),
content: Text(content),
actions: <Widget>[
FlatButton(
child: new Text("Close"),
onPressed: () {
Navigator.of(context).pop();
},
)
],
);
});
}
Testing an In-App Message​App Messaging allows you to test an in-app message before it is published. You need to obtain the Anonymous Application Identifier (AAID) of your test device by adding the following code to your Android app module.
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();
textView.setText(aaid);
Log.d(TAG, "getAAID success:" + aaid );
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
Log.d(TAG, "getAAID failure:" + e);
}
});
Sign in to AppGallery Connect, go to Grow > App Messaging > Messages, find the message that you created, click and select Test in the Operation column.
Click Add test user and enter the AAID
Click Save. Check whether the test message is properly displayed on your test device

Categories

Resources