Integrating HMS Banner Ads in Xamarin.Android - Huawei Developers

Introduction
Banner Ads are rectangular images that occupy a spot at the top, middle, or bottom within an app's layout. Banner Ads refreshes automatically at intervals. When a user taps a Banner Ad, the user is redirected to the advertiser's page in most cases.
Creating Binding Libraries
To support HUAWEI Ads Kit in Xamarin platform, we need to create Binding libraries. Follow the steps to create Binding libraries:
1. Download Publisher Service libraries that defined in Libraries section of Xamarin Plugin .
2. Download Publisher Service from section Xamarin Plugin.
3. Extract Publisher Service downloaded in Step 2 .
4. Open XAdsLite* solution by double clicking XAdsLite*.sln file in extracted folder of Publisher Service.
5. Each package must place under the related project. Inside the "Solution Explorer", expand each project and repeat the steps below:
Right-click Jars > Add >Existing Item.
Click on the package file you imported.
In the properties window,
i. Set the Build Action as "LibraryProjectZip " if the file type is .aar.
ii. Set the Build Action as "EmbeddedJar" if the file type is .jar.
{
"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"
}
6. The references of each package should be checked from Check Need References section and should be added to the projects as a reference (Add references from the projects section in reference management.).
7. Build the library
a. From the Visual Studio's toolbar, choose Build > Rebuild Solution.
b. In the output tab, check that all projects are Built successfully.
4. Set all library files' build action to None.
a. Hold CTRL key and select all library files by clicking on them.
b. Right click one of the library files and in the menu click Properties.
c. In the properties window, set Build Action property to None.
5. Add library references to your project
a. Right click to your project’s References section.
b. In the opened menu, click to Add Reference menu item.
c. In opened window, click Browse section. After that click to Browse button.
d. In opened window, navigate to your project's path.
e. Double click to your previously created library folder (example: Libraries).
f. Select all files in this folder and click to Add button.
g. In the Reference Manager window, check that references has been added correctly.
h. Click OK to continue.
Configuring App Information
Configuring the Signing Certificate Fingerprint
1. Sign in to AppGallery Connect and select My Projects.
2. Find your Project from list and click the Project name.
3. In the following page a message window will open requesting to enter a package name.
4. Click on Manually enter the package name button and enter unique package name that you are going to use for your App.
5. Click to Save button.
6. Please take note of this package name that will be used in the following Setting Package Name section.
7. In the App information section of the page, set SHA-256 certificate fingerprint to the SHA-256 fingerprint that is generated from the preceding section of Obtaining the SHA-256 Fingerprint from Signature File.
8. After completing configuration, click
9. Click agconnect-services.json to download the configuration file.
10. Copy the agconnect-services.json file to your project's Assets directory
Setting Package Name
You need to confirm App's package name, before generating apk
1. Right-click on project.
2. Click Properties button.
3. In the window, click on Android Manifest section.
4. Input the package name set during Step 5 of the Configuring the Signing Certificate Fingerprint section to Package name.
5. Choose File > Save Selected Items in main window or press Ctrl+S to save the changes.
Development
1. Add BannerView to theXML layout file, and set the hwads:adId and hwads:bannerSize attributes to the ad slot ID and ad size respectively.
The following sample code shows how to add BannerView to an XML layout file:
Code:
<com.huawei.hms.ads.banner.BannerView
android:id="@+id/hw_banner_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
hwads:adId="@string/banner_ad_id"
hwads:bannerSize="BANNER_SIZE_320_50" />
2. Add BannerView to the code, and set the ad slot ID and ad size.
Code:
BannerView bannerview = new BannerView(this);
// "testw6vs28auh3" is a dedicated test ad slot ID.
bannerview.AdId = "testw6vs28auh3";
bannerview.BannerAdSize = BannerAdSize.BannerSize32050;
FrameLayout adFrameLayout = FindViewById<FrameLayout>(Resource.Id.ad_frame);
adFrameLayout.AddView(bannerView);.
2. Loading an Ad
After adding BannerView, load an ad using the LoadAd() method in the BannerView class.
Code:
// Obtain BannerView based on the configuration in layout/activity_main.xml.
BannerView bannerview = new BannerView(this);
bannerview.AdId = "testw6vs28auh3";
bannerview.BannerAdSize = BannerAdSize.BannerSize32050;
// Create an ad request to load an ad.
AdParam adParam = new AdParam.Builder().Build();
bannerview.LoadAd(adParam);
3. Listening for Ad Events.
You can listen for ad events using the methods in the AdListener class.
Code:
bannerview.AdListener = new AdsListener();
private class AdsListener : AdListener
{
BannerActivity activity;
public override void OnAdClicked()
{
// Called when a user taps an ad.
}
public override void OnAdClosed()
{
// Called when an ad is closed.
}
public override void OnAdFailed(int errorCode)
{
// Called when an ad fails to be loaded.
}
public override void OnAdLeave()
{
// Called when a user has left the app.
}
public override void OnAdOpened()
{
// Called when an ad is opened.}public override void OnAdLoaded(){// Called when an ad is loaded successfully.
}
}
Displaying a Banner Ad
• Please ensure version of each .aar file.
• Before build the library project check depedent .dll file in each project Reference folder.
• Please ensure that Ads is enabled or not in AGC console.
Conclusion
This article is very helpful you how to generate .dll files of HMS Banner Ads Kit in visual studio and how to include those generated .dll files into Xamarin.Android project.
Please let me know if you have any queries.
Reference
For more information, refer the following URLs:
· https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides-V1/service-introduction-0000001050178531-V1
· https://developer.huawei.com/consum...Library/xamarin-sdk-download-0000001050175494
· https://developer.huawei.com/consum...Examples/xamarin-sample-code-0000001050177525

Related

Recipe To Integrate In-App Messaging In 10 Minutes

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

Integrating HUAWEI In-app message with Google In-app message in single Application

More information like this, you can visit HUAWEI Developer Forum​
Introduction
In-App Messaging helps you engage your app's active users by sending targeted, contextual messages that encourage to use key app features. For example, you could send an in-app message to get users to subscribe, watch a video, complete a level, or buy an item. You can customize messages as cards, banners, modals, or images, and set up triggers so that they appear exactly when benefit your users most.
Usecase
1. Add following image on Huawei App gallery connect console and google firebase console to be shown as in-app message in our app.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
2. App installed on Huawei device will fetch in-app message (image) from Huawei App gallery connect.
3. App installed on GMS devices will fetch in-app message (image) from Google firebase console.
Huawei In-App Messaging
Prerequisite
1. You must have Huawei developer account.
2. Huawei phone with HMS 4.0.0.300 or later
3. Android Studio, Jdk 1.8, SDK platform 26 and Gradle 4.6 installed.
Setup:
1. Create a project in android studio.
2. Get the SHA-256 Key.
3. Create an app in the Huawei app gallery connect.
4. Enable account kit setting in Manage APIs section.
5. Provide the SHA-256 Key in App Information Section.
6. Provide storage location.
7. After completing all the above points we need to download the agconnect-services.json from App Information Section. Place the json file in   the app folder of the android project.
8. Enter the below maven url inside the repositories of buildscript and allprojects respectively (project build.gradle file )
Code:
maven { url 'http://developer.huawei.com/repo/' }
9. Enter the below plugin in the app build.gradle file
Code:
apply plugin: 'com.huawei.agconnect'
dependencies {
implementation 'com.huawei.agconnect:agconnect-appmessaging:1.4.0.300'
}
10. Put the below permission in AndroidManifest file.
  a) android.permission.INTERNET
  b) android.permission.ACCESS_NETWORK_STATE
11. Now Sync the gradle.
Implemetation
1. 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.
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 date and time to stop sending message.
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.
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.
Google firebase In-App Messaging
Steps:
1. To enable Firebase in your app, add following lines in your root-level build.gradle file.
Code:
buildscript {
repositories {
// Check that you have the following line (if not, add it):
google() // Google's Maven repository
}
dependencies {
// ...
// Add the following line:
classpath 'com.google.gms:google-services:4.3.3' // Google Services plugin
}
}
allprojects {
// ...
repositories {
// Check that you have the following line (if not, add it):
google() // Google's Maven repository
// ...
}
}
2. In your module (app-level) Gradle file (usually app/build.gradle), apply the Google Services Gradle plugin:
Code:
apply plugin: 'com.android.application'
// Add the following line:
apply plugin: 'com.google.gms.google-services' // Google Services plugin
android {
// ...
}
3. To your module (app-level) Gradle file (usually app/build.gradle), add the dependencies.
Code:
dependencies {
// Add the Firebase SDK for Google Analytics
implementation 'com.google.firebase:firebase-analytics:17.4.4'
implementation 'com.google.firebase:firebase-auth:19.3.2'
}
4. That testing device is determined by a FirebaseInstallations ID, or FID. Find your testing app's FID by checking the Logcat in Android Studio for the following `Info` level log:
Code:
I/FIAM.Headless: Starting InAppMessaging runtime with Installation ID YOUR_INSTALLATION_ID
We will add this FID while composing in-app message on firebase console.
5. Set up your new campaign in the Firebase consoles Firebase In-App Messaging page.
6. Select your project and click Create a new campaign.
7. In this article, we will use image in-app message. Select message layout as Image only. Provide Image URL and click Next.
8. Provide campaign name and description and define your target user. Here we have not defined any target user.
9. Click Next to define campaign start time, end time, trigger event and frequency limit of in-app message.
10. Click Next and provide conditional events and additional options. These are optional. Click Save as draft.
11. Select Test on Device, and add the earlier generated FID.
12. Run the application on GMS installed device, you will see Google in-app message.
To check if device has HMS or GMS installed
Code:
public class Utils {
public static boolean isSignedIn = false;
public static boolean isGooglePlayServicesAvailable(Activity activity) {
GoogleApiAvailability googleApiAvailability = GoogleApiAvailability.getInstance();
int status = googleApiAvailability.isGooglePlayServicesAvailable(activity);
if(status != ConnectionResult.SUCCESS) {
if(googleApiAvailability.isUserResolvableError(status)) {
googleApiAvailability.getErrorDialog(activity, status, 2404).show();
}
return false;
}
return true;
}
public static boolean isHuaweiMobileServicesAvailable(Context context) {
if (HuaweiApiAvailability.getInstance().isHuaweiMobileServicesAvailable(context) == ConnectionResult.SUCCESS){
return true;
}
return false;
}
public static boolean isDeviceHuaweiManufacturer () {
String manufacturer = Build.MANUFACTURER;
Log.d("Device : " , manufacturer);
if (manufacturer.toLowerCase().contains("huawei")) {
return true;
}
return false;
}
}
References:
https://developer.huawei.com/consumer/en/doc/development/AppGallery-connect-Guides/agc-appmessage-introduction
https://firebase.google.com/docs/in-app-messaging/get-started?platform=android

How Can I Quickly Integrate App Linking of AppGallery Connect into an Unity-based App?

How Can I Quickly Integrate App Linking of AppGallery Connect into an Unity-based App?
Recently, my app needs to use cross-platform sharing links. App Linking of AppGallery Connect just meets my requirements.
Perform the following steps for service integration:
Step 1: Create an app, enable App Linking, and create a URL prefix.
Step 2: Integrate the App Linking SDK into a Unity project.
Step 3: Import the HuaweiService package to Unity Editor.
Step 4: Create a link of App Linking.
Step 5: Receive and test the link.
1. Enable App Linking and create a URL prefix.
1. Create an app or use an existing app in AppGallery Connect. Click My projects and go to Grow > App Linking, and click Enable now in the displayed page.
{
"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. On the displayed App Linking service page, click the URL prefix tab and then click Add URL prefix to create a unique URL prefix.
The system will automatically check your domain name to ensure its uniqueness.
2. Integrate the App Linking SDK into a Unity project.
Prepare the Android development environment in Unity Editor.
1. Choose Edit > Project Settings > Player > Publish Settings. In the Build area, select items for Android as required.
Note: You need to add build dependencies for Android in Unity Hub, as shown in the following figure.
2. In AppGallery Connect, click My projects, and find your project from the list. Go to Project settings > General information, download the agconnect-services.json file, and save the file to the Assets\Plugins\Android directory of your Unity project.
3. In Unity Editor, choose Edit > Project Settings > Player > Other Settings, and set the package name to the one you set in AppGallery Connect.
4. Add the following code to the project-level baseProjectTmeplate.gradle file in the Assets\Plugins\Android directory:
XML:
allprojects {
buildscript {
repositories {
maven { url 'https://developer.huawei.com/repo/' }
}
}
repositories {
maven { url 'https://developer.huawei.com/repo/' }
}
}
5. Add the following code to the app-level LauncherTmeplate.gradle file in the Assets\Plugins\Android directory:
XML:
dependencies {
implementation 'com.huawei.agconnect:agconnect-applinking:1.4.1.300'
}
3. Import the HuaweiService package to Unity Editor.
1. Import the source package to your project. You can either download the package from the Unity Asset Store, or download it from the following website:
https://share.unity.com/receive/?th...e=CHA6BzFizOIgjWvhSXYRaJiNzOcwfItJRY7dZSNEb4A
2. After the download is complete, choose Assets > Import package, select the required package, and click Import.
4. Create a link of App Linking.
You can create a link of App Linking in AppGallery Connect or by calling an API in your Unity project. Let’s see how to create a link in your Unity project.
1. Create buttons.
In Unity Editor, choose GameObject > UI > Button, and create two buttons called create and share. Click Add Component on the right to create a script file.
2. Add a method for creating a link.
Add the following method to the script file of the test app:
Java:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using HuaweiService.AppLinking;
using HuaweiService;
public class testApp : MonoBehaviour
{
private const string URI_PREFIX = "https://testcocos1203.drcn.agconnect.link";
private const string DEEP_LINK = "https://developer.huawei.com/consumer/cn/service/josp/agc/index.html";
void Start()
{
}
void Update()
{
}
public void createLongLink() {
AGConnectAppLinking.getInstance();
AppLinking.Builder builder = createBuilder();
Uri applinkingUri = builder.buildAppLinking().getUri();
var link = applinkingUri.toString();
Debug.Log ("AppLinking create" + link);
GUIUtility.systemCopyBuffer = link;
}
public AppLinking.Builder createBuilder(){
return AppLinking.newBuilder()
.setUriPrefix(URI_PREFIX)
.setDeepLink(Uri.parse(DEEP_LINK))
.setAndroidLinkInfo(
AppLinking.AndroidLinkInfo.newBuilder()
.build());
}
public void OpenLink()
{
var activity = new Activity();
var intent = new Intent();
intent.setData(Uri.parse(GUIUtility.systemCopyBuffer));
activity.startActivity(intent);
}
}
3. Bind a method to a button.
In Unity Editor, click the create button. In the On Click() area on the right, add a tap event, as shown in the following figures.
Bind a method to the share button as well.
Note: You can drag the .cs file created by clicking create to the Add Component area on the right to add a tap event.
5. Receive a link.
To receive a link, you need to configure the manifest file and set the getAppLinking method.
1、 Configure the manifest file. Here, the scheme of the deep link domain name is set in the file.
Example: DEEP_LINK = ‘https://developer.huawei.com/cn/';
Sample code:
6. Package your app and test your link.
1. After your app runs properly, tap create to create a link. Then tap share to open the link in a browser.
2. If the app can be launched, the link is normal.
7. Summary
The integration is simple. The SDK is small, and links can be shared across Android and iOS. No adaptation is required on different platforms, reducing the workload.
Operations personnel can create links in AppGallery Connect for app promotion, and you can write code in apps to create links, which is very convenient.
Reference:
HUAWEI AppGallery Connect App Linking documentation: https://developer.huawei.com/consum...ry-connect-Guides/agc-applinking-introduction
Unity documentation about App Linking: https://docs.unity.cn/cn/Packages-c...linking.html#integrating-huawei-analytics-kit
Unity Editor Installation and APK Packaging: https://forums.developer.huawei.com/forumPortal/en/topic/0204435788744370088?fid=0101187876626530001
if you have any questions,please refer to stackoverflow .
Thanks.
Ganyo1 said:
Thanks.
Click to expand...
Click to collapse
Thank you for your like. You are welcome.

How Can I Quickly Integrate Cloud Storage of AppGallery Connect into a nodeJS

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 Information​Version: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 Connect​Currently, 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 Environment​I 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 SDK​1. 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 Functions​a) 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 Functions​1. 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. Summary​Cloud 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!

Learn to integrate Login via Facebook using Huawei Auth Service (React Native)

{
"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 be integrating Huawei Auth Service in an Application. The Auth Service SDK into our app, we can easily and quickly provide functions such as registration and sign-in for our users. We can choose to provide our users with one or more of the authentication modes like Mobile number, Email address, Facebook, WeChat etc. We will integrate the authentication by Facebook into the app, so that our users can use Facebook to sign in to the app securely,
React Native
React Native helps you to create real and exciting mobile apps with the help of JavaScript only, which is supportable for both android and iOS platforms.
Just code once, and the React Native apps are available for both iOS and Android platforms which helps to save development time.
React Native is a framework that builds a hierarchy of UI components to build the JavaScript code.
It uses the same fundamental UI building blocks as regular iOS and Android apps.
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
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, as follows.
7. Enter SHA-256 certificate fingerprint and click Save, as follows.
React Native Project Preparation
8. Environment set up, refer below link.
Setting up the development environment · React Native
This page will help you install and build your first React Native app.
reactnative.dev
9. Create project using below command.
Code:
react-native init project name
10. Download the React Native Account Kit SDK and paste it under Node Modules directory of React Native project. If you cannot find node modules run below command under project directory using CLI.
“npm install” & “npm link”
11. Configure android level build.gradle
Add to buildscript/repositories and allprojects/repositories
Code:
maven {url 'http://developer.huawei.com/repo/'}
12. Configure app level build.gradle. (Add to dependencies)
Implementation project (“:react-native-hms-account”)
13. Linking the HMS Account Kit Sdk.
Run below command in the project directory
Code:
react-native link react-native-hms-account
14. Add below permissions to Android.manifest file.
XML:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
15. Enabling Auth Service
(i). Sign in to AppGallery Connect and click My projects.
(ii). Click a project that you want to enable Auth Service from the project list.
(iii). Choose Build > Auth Service. If it is the first time that you use Auth Service, click Enable now in the upper right corner.
(iv). Click Enable in the row of each authentication mode to be enabled.
For more details visit this documentation.
Development
On the app sign-in page, obtain user information from AppGallery Connect, and check whether a user has signed in. If a user has signed in, the user's home page is displayed; if no user has signed in, the sign-in page is displayed.
After a user requests to sign in using a Facebook account, obtain the user authorization information of the account.
Call FacebookAuthProvider.credential to generate a credential using the access token obtained from the Facebook account, and then call AGCAuth.signIn to implement sign-in.
JavaScript:
let credential = FacebookAuthProvider.credential("accessToken");
AGCAuth.getInstance()
.signIn(credential)
.then((signInResult) => {
// signInResult.user to get user info
})
.catch((error) => {
// error
});
Homepage.js
JavaScript:
const [list, setList] = useState([])
const [value, setValue] = useState("")
// A function that add data to the list array
function addText(text) {
if (value !== "") {
setList(prev => {
return [
...prev,
{ text: text, isSelected: false } // Adding a JS Object
]
})
setValue("")
} else {
alert("Please type in something!")
}
}
// A function that set the value of isSelected based on the state of the checkbox
function setIsSelected(index, value) {
let data = []
// Making a deep copy of the list array
for (let i = 0; i < list.length; i++) {
if (index === i) {
data.push({ ...list[i], isSelected: value }) // Updating the object at position i === index
} else {
data.push(list[i])
}
}
setList(data) // Setting the new state
}
// A function that delete an item at position idx from the list array
function deleteItem(idx) {
Alert.alert(
"Delete Item",
"Are you sure you want to delete this item?",
[
{
text: "Cancel",
style: "cancel"
},
{
text: "Yes", onPress: () => {
const data = list.filter((item, index) => index !== idx)
setList(data)
}
}
])
}
return <View style={styles.container}>
<Text style={{ ...FONTS.h1_semiBold, color: COLORS.secondary, marginBottom: 15 }}>What needs to be done.</Text>
<FlatList style={{ flex: 1 }}
data={list}
renderItem={({ item, index }) => <Card data={item} index={index} setIsSelected={setIsSelected} deleteItem={deleteItem} />}
keyExtractor={(item, index) => index.toString()}
/>
<View style={styles.textBoxWrapper}>
<TextInput
style={styles.textInput}
placeholder="New Task"
placeholderTextColor={COLORS.primary}
onChangeText={text => setValue(text)}
value={value} />
<TouchableOpacity
style={styles.btn}
onPress={() => addText(value)}>
<Text style={{ fontSize: 34, color: COLORS.secondary }}>+</Text>
</TouchableOpacity>
</View>
</View>
Testing
Run the android App using the below command.
Code:
react-native run-android
Result
Conclusion
In this article, we have learnt that how to integrate the Facebook authentication mode into the app, so that our users can use Facebook to sign in to the app securely.
Reference
Account Kit: Documentation
Account Kit: Training Video

Categories

Resources