How to create HMS Push Kit Cordova Plugin from scratch feat. Plugman - Huawei Developers

The original article is 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"
}
Applications built specifically for mobile have been with us for more than 10 Years. Within that period the mobile development market has changed a lot. The way developers are approaching towards creating apps are not limited, in fact they have created their own ways for shortening development time. And that’s how cross-platform development was born.
Cross-platform, such as Cordova, Ionic, React Native, Flutter etc., are gaining a lot of attention especially for web developers who has knowledge about HTML,CSS, JavaScript etc. These platforms are also offering better opportunities to build native like experiences for developers.
Today we are going to learn, how to create Apache Cordova Plugin from scratch using HMS Core Capabilities.
Prerequisite
We must have latest version of Node installed on our machine.
We must have latest version of Visual Studio Code installed on our machine.
Once we installed Node, we can run the following command using command prompt (cmd) from anywhere in our environment to install Plugman and Cordova globally, so that it is available from any directory:
Code:
$ npm install -g plugman
$ npm install -g cordova
-g here indicates that Plugman installation is globally supported.
Why Plugman?
Plugman is a useful command line tool for installing and uninstalling or managing Cordova plugins. It supports multiple platform such as Android, iOS etc.
Let’s do it
First we create a separate folder in our system, where we want to create plugin. After we find a separate space, we copy the location and open command prompt to go to the specific location using cd command:
Code:
$ cd your/specific/location
Creating Plugin
We create plugin using below command.
Code:
$ plugman create --name HMSPushPlugin --plugin_id com.huawei.hmspushplugin --plugin_version 1.0.0
In the above command we are providing
a) Name of the plugin
b) Plugin id
c) Plugin version.
After creation of plugin, we use cd command to go to plugin location.
Code:
$ cd HMSPushPlugin
Adding Platform
We will add Android platform using below command.
Code:
$ plugman platform add --platform_name android
Create package.json
We will create package.json file using below command.
Code:
$ plugman createpackagejson .
Answer the questions presented, and you will end up with a package.json that looks like this:
Code:
{
"name": "hmspushplugin",
"version": "1.0.0",
"description": "hms push kit",
"cordova": {
"id": "com.huawei.hmspushplugin",
"platforms": [
"android"
]
},
"keywords": [
"ecosystem:cordova",
"cordova-android"
],
"author": "sanghati",
"license": "ISC"
}
Folder Structure
After going through all the above command, the structure of the plugin creation will look like this:
Plugin.xml is one of the most important files here. It’s what Cordova parses to figure out what platforms your plugin supports, preferences it has that the user can configure, source files we’ll include in our final app build, and more. Now if you peek into src folder, you may end up seeing native codes of Android or iOS or both. Finally, www is where the JavaScript code for our plugin lives. This is what gets called first and then kicks off Cordova to call our native code.
Role Play of Visual Studio Code
Now we open VS code and open the folder of the plugin and start modifying the plugin.xml file it is where everything happens and it’s where we should start first.
Modify the plugin.xml as shown below:
Code:
<?xml version="1.0" encoding="UTF-8"?>
<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0"
xmlns:android="http://schemas.android.com/apk/res/android"
id="com.huawei.hmspushplugin"
version="1.0.0">
<name>HMSPushPlugin</name>
<!-- Js file -->
<js-module
name="HMSPushPlugin"
src="www/HMSPushPlugin.js">
<clobbers target="cordova.plugins.HMSPushPlugin" />
</js-module>
<!-- Platform is added here -->
<platform name="android">
<framework src="src/android/build.gradle" custom="true" type="gradleReference" />
<!-- Push kit dependency -->
<framework src="com.huawei.hms:push:4.0.0.300"/>
<config-file parent="/*" target="res/xml/config.xml">
<feature name="HMSPushPlugin">
<param
name="android-package"
value="com.huawei.hmspushplugin.HMSPushPlugin.HMSPushPlugin" />
</feature>
</config-file>
<config-file parent="/*" target="AndroidManifest.xml" />
<!-- Android source file is added here -->
<source-file src="src/android/HMSPushPlugin.java" target-dir="src/com/huawei/hmspushplugin/HMSPushPlugin" />
<source-file src="src/android/MessageService.java" target-dir="src/com/huawei/hmspushplugin/HMSPushPlugin"/>
</platform>
</plugin>
If we want to change the id or name then we need to give our plugin a unique name and id. As far as naming conventions go, the id is usually of the form this-is-my-plugin, like for example huawei-cordova-pushkit-plugin.
The js-module specifies the JavaScript code that will run, and <clobbers> sets what variable the plugin will be exported under. So, in this case, our script file is www/ HMSPushPlugin.js, and when our app runs, we’ll be able to access the plugin using cordova.plugins.HMSPushPlugin.
We specify the platforms we are going to support, along with references to the corresponding native code for each. Here we added Android as platform. Inside of <config-file> we specify our Android package name and also the symbol cordova will use to identify our plugin, in this case it’s HMSPushPlugin. Finally, we have a reference to our main Java code inside of <source-file> which is where our native code lives.
Adding HMS Push Kit
As we have mentioned two <source-file> in plugin.xml file. So, we need to create add two java file in our android directory.
This is not all. For more information about this, you can visit HUAWEI Developer Forum.

Interesting, thanks

Related

How to use Cocos2d-x with Huawei Mobile Services

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/

【Trip to HMS Core 5.0】Add Analytics Kit to Your iOS App

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

Integration of Huawei ML Kit into Ionic Application ( Cross Platform Integration )

Introduction
Machine learning is an application of artificial intelligence that provides systems the ability to automatically learn and improve from experience without being explicitly programmed. Machine learning focuses on the development of computer programs that can access data and use it learn.
HMS ML Kit allow to support diverse artificial intelligence applications throughout a wide range of industries.
HMS ML Kit Services
1. Text-related Services
2. Language/Voice-related Services
3. Image-related Services
4. Face/Body-related Services
5. Custom Model
In this article we will focus on text related services provided by HMS ML Kit.
Ionic Framework
Ionic Framework is an open source UI toolkit for building performant, high-quality mobile and desktop apps using web technologies such as HTML, CSS, and JavaScript with integrations for popular frameworks like Angular and React.
Think of Ionic as the front-end UI framework that handles all of the look and feel and UI interactions your app needs in order to be compelling. Unlike a responsive framework, Ionic comes with very native-styled mobile UI elements and layouts that you should get with a native SDK on Android or iOS but didn’t really exist before on the web.
Since Ionic is an HTML5 framework, it needs a native wrapper like Cordova or Capacitor in order to run as a native app.
Here we will use Ionic framework with Angular and Capacitor as native wrapper.
Text-related Services
There are four type of services which comes under text related service:
1. Text Recognition
2. Document Recognition
3. Bank Card Recognition
4. General Card Recognition
Here we will use three services that is Text Recognition, Bank Card Recognition and General Card Recognition to showcase the power HMS ML Kit in Ionic application.
Demo
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Prerequisite
1) Must have a Huawei Developer Account.
2) Must have a Huawei phone with HMS 4.0.0.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) Must install node in the system
5) Must install Ionic in the system using below command:
Code:
npm install -g [user=1329689]@iONiC[/user]/cli
Things need to be done
1) Generating a Signing Certificate Fingerprint. For generating the SHA key, refer this article.
2) Create an app in the Huawei AppGallery connect and enable ML Kit in Manage Api section.
3) Provide the SHA Key in App Information Section.
4) Provide storage location.
5) Download the agconnect-services.json and store it somewhere on our computer.
6) Create a blank Ionic Project using below command:
Code:
ionic start Your_Application_Name blank --type=angular
7) Download the Cordova Ml Kit Plugin. Run the following command in the root directory of your Ionic project to install it through npm.
Code:
npm install <CORDOVA_MLKIT_PLUGIN_PATH>
8) If you want full Ionic support with code completion etc., install @iONiC-native/core in your project.
Code:
npm install [user=1329689]@iONiC[/user]-native/core --save-dev
9) Run the following command to copy the "ionic/dist/hms-ml" folder from library to "node_modules @iONiC-native" folder under your Ionic project.
Code:
cp node_modules/@hmscore/cordova-plugin-hms-ml/ionic/dist/hms-ml node_modules [user=1329689]@iONiC[/user]-native/ -r
10) Run the following command to compile the project:
Code:
ionic build
npx cap init [appName] [appId]
Where appName is the name of your app, and appId is package_name in your agconnect-services.json file (ex: com.example.app).
11) Run the following command to add android platform to your project:
Code:
ionic capacitor add android
12) Make sure your project has a build.gradle file with a maven repository address and agconnect service dependencies as shown below:
13) Add the Signing certificate configuration to the build.gradle file in the app directory as show below:
14) Add plugin to the build.gradle file in the app directory as show below:
15) Add ads service implementation into to dependencies section of build.gradle file in the app directory as show below:
16) Add agconnect-services.json and signing certificate jks file to the app directory in your Android project as show below:
17) To update dependencies, and copy any web assets to your project, run the following code:
Code:
npx capacitor sync
Let’s Code
Install FileChooser
We need to install FileChooser to select a file or in this case an image, returns a file URI. Run the following command on visual studio terminal:
Code:
npm install cordova-plugin-filechooser
npm install [user=1329689]@iONiC[/user]-native/file-chooser
ionic cap sync
Android Permission
We need android permission in order to allow our user to give their permission to the application like camera permission, storage permission etc. Run the following command on visual studio terminal:
Code:
npm install cordova-plugin-android-permissions
npm install [user=1329689]@iONiC[/user]-native/android-permissions
ionic cap sync
Avoid No Provider Error
To avoid No Provider Error, we need to add FileChooser, Android Permission and HMS ML kit in app.module.ts providers section and also make sure to import the same as shown below:
Code:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';
import { IonicModule, IonicRouteStrategy } from [user=1329689]@iONiC[/user]/angular';
import { SplashScreen } from [user=1329689]@iONiC[/user]-native/splash-screen/ngx';
import { StatusBar } from [user=1329689]@iONiC[/user]-native/status-bar/ngx';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { AndroidPermissions } from [user=1329689]@iONiC[/user]-native/android-permissions/ngx';
import { FileChooser } from [user=1329689]@iONiC[/user]-native/file-chooser/ngx';
import { HMSMLKit } from [user=1329689]@iONiC[/user]-native/hms-ml/ngx'
import { FilePath } from [user=1329689]@iONiC[/user]-native/file-path/ngx';
@NgModule({
declarations: [AppComponent],
entryComponents: [],
imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule],
providers: [
StatusBar,
SplashScreen,
AndroidPermissions,
FileChooser,
HMSMLKit,
FilePath,
{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
],
bootstrap: [AppComponent]
})
export class AppModule {}
For more information, you can visit https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0202369186369300340&fid=0101187876626530001

Intermediate: How to Improve User Retention and Engagement in mobile apps using Huawei APP Linking (Flutter)

Introduction
In this article, we will learn how to implement Huawei App Linking service. This service is very important service for enterprises that are digitalizing to effectively manage deep links.
      
{
"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"
}
What can we do using App Linking?
Huawei App Linking is a very useful service to make existing deep links smarter and useful. Developers can improve user experience in their apps. If user opens the link android or iOS it can be directly forwarded to the linked content in your application.
We can use these links to direct users to promotional information or native content that they can share with others. We can create links of app linking and send them to users or users share links of app linking dynamically generated in application. User can click the link to access the content.
Do you know how it will work?
Developer can create links in different ways using App Gallery console, from app or manual by adding required parameters to a specific domain for app.
Users clicks a link if the app is not installed, the user is redirect to App Gallery to install your app otherwise your app opens directly. You can retrieve the link that was to your app and handle the deep link as per requirement of your app.
Table of content
1. Project setup
2. Create Link using App Gallery console
3. Create Link from APP
Mobile app Linking Benefits
1. Enhance the user experience: users can easily access the linked content, with essentially no navigation. If you are linking to something in your app from social media, a mobile website, etc., users are able to navigate seamlessly to that content.
2. Improve User Retention, Engagement, and Usage: Users who were deep linked showed double the activation rate, double the retention rate, and visited the app twice as frequently versus users who had not been deep linked.
3. Help Re-Engage users: When a user has your app installed, but has been inactive for a period of time, you can use deep linking to direct them to specific content to encourage use, rather than the generic home screen.
Requirements
1. Any operating system (i.e. MacOS, Linux and Windows).
2. Any IDE with Flutter SDK installed (i.e. IntelliJ, Android Studio and VsCode etc.).
3. A little knowledge of Dart and Flutter.
4. Minimum API Level 19 is required.
5. Required EMUI 5.0 and later version devices.
Setting up the APP Linking
1. First create a developer account in AppGallery Connect. After create your developer account, you can create a new project and new app. For more information, click here.
2. Generating a Signing certificate fingerprint follow below command.
Code:
keytool -genkey -keystore <application_project_dir>\android\app\<signing_certificate_fingerprint_filename>.jks -storepass <store_password> -alias <alias> -keypass <key_password> -keysize 2048 -keyalg RSA -validity 36500
3. The above command creates the keystore file in appdir/android/app.
4. Now we need to obtain the SHA256 key, follow the command.
Code:
keytool -list -v -keystore <application_project_dir>\android\app\<signing_certificate_fingerprint_filename>.jks
5. Enable the App Linking service on the App Gallery.
6. After configuring project, we need to download agconnect-services.json file in your project and add into your project.
7. After that follow the URL for cross-platform plugins add required plugin into sample.
8. The following dependencies for HMS usage need to be added to the build.gradle file under the android directory.
Code:
buildscript {
ext.kotlin_version = '1.3.50'
repositories {
google()
jcenter()
maven {url 'http://developer.huawei.com/repo/'}
}
dependencies {
classpath 'com.android.tools.build:gradle:3.5.0'
classpath 'com.huawei.agconnect:agcp:1.4.1.300'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
allprojects {
repositories {
google()
jcenter()
maven {url 'http://developer.huawei.com/repo/'}
}
}
9. Add the below plugin into build.gradle file under the android/app directory.
Code:
apply plugin: 'com.huawei.agconnect'
10. Add the required permissions to the AndroidManifest.xml file under app/src/main folder.
Code:
<uses-permission android:name="com.huawei.permission.SECURITY_DIAGNOSE" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<uses-permission android:name="android.permission.INTERNET" />
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data
android:host="developer.huawei.com"
android:scheme="http"/>
<data
android:host="developer.huawei.com"
android:scheme="https"/>
</intent-filter>
11. After completing all the above steps, you need to add the required kits’. Flutter plugins as dependencie to pubspec.yaml file. You can find all the plugins in pub.dev with the latest versions.
Code:
agconnect_applinking: ^1.2.0+201
12. To launch the url we need to add flutter url_launcher plugin.
Code:
url_launcher: ^5.7.10
After adding them, run flutter pub get command. Now all the plugins are ready to use.
Note: Set multiDexEnabled to true in the android/app directory, so the app will not crash.
Config App Linking
1. We can access the App Linking on the console side by following the My Projects > Project settings > Grow > App Linking steps.
2. Before creating our custom link we need to add URL prefix. URL Prefix are free domains provided by AppGallery Connect. If you do not have a custom domain address. We can create up to 5 URL prefixes.
Enter domain name and then click on Next button.
3. After creating the URL Prefix we can create our links after following the App Linking Tab > Create App Linking steps.
4. We need to set a short link value to the URL prefix we created. Short link value is generated automatically by Console. However, if we wish, we can arrange this area according to our wishes.
5. After setting up all the necessary information, now we will define the behavior of our deep link, by which we can determine how our deep links will behave.
6. We need to enter preview information such as title, image, description this information optional. Click Next and then click Release.
Creating Link
Now let’s create the same link within the application.create object for AGCAppLinking.
To Generate LongLinks
Code:
final AGCAppLinking agcAppLinking = new AGCAppLinking();
createLongAppLinking(BuildContext context) async {
AndroidLinkInfo androidLinkInfo = new AndroidLinkInfo(
androidOpenType:
AppLinkingAndroidLinkInfoAndroidOpenTypeConstants.APP_GALLERY,
androidPackageName: "com.huawei.sample.wellfit",
androidDeepLink:
'https://appgallery.huawei.com/#/app/C101529369');
ApplinkingInfo appLinkingInfo = ApplinkingInfo(
androidLinkInfo: androidLinkInfo,
shortAppLinkingLength: ShortAppLinkingLengthConstants.SHORT,
domainUriPrefix: 'https://wellfit.dra.agconnect.link',
deepLink: 'https://appgallery.huawei.com/#/app/C101529369',
previewType: AppLinkingLinkingPreviewTypeConstants.APP_INFO);
try {
setState(() async {
longAppLinking =
await agcAppLinking.buildLongAppLinking(appLinkingInfo);
print(longAppLinking.longLink.toString());
});
} on PlatformException catch (e) {
_showDialog(context, e.toString());
}
}
To Generate ShortLink
Code:
try {
ShortAppLinking shortAppLinking =
await agcAppLinking.buildShortAppLinking(appLinkingInfo);
print(shortAppLinking.toString());
} on PlatformException catch (e) {
_showDialog(context, e.toString());
}
Demo
                  
Tips and Tricks
1. Download latest HMS Flutter plugin.
2. Set minSDK version to 19 or later.
3. Do not forget to click pug get after adding dependencies.
4. HMS Core APK 4.0.2.300 is required.
5. Currently this service supports 5 URLs.
Conclusion
That’s it!
We have finished a complete demo of a flutter app that app handles Huawei App Linking services. This service can bring significant improvements to the user experience of our mobile apps.
Thanks for reading! If you enjoyed this story, please click the Like button and Follow. Feel free to leave a Comment below.
Reference
App Linking service URL
Original Source

Learn to deploy Links in an Application using Huawei App Linking

{
"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, we will learn how to implement App Linking service provided by Huawei. App Linking allows you to create cross-platform links that can work as defined regardless of whether your app has been installed by a user. When a user taps the link on an Android, an iOS, or a HarmonyOS device, the user will be redirected to the specified in-app content. If a user opens the link in a browser on a PC, the user will be redirected to the same content of the web version. When creating a link, you can set tracking parameters for different channels to identify traffic sources, analyze their performance, and determine the platform or campaign that best suits your app.
Requirements
1. JDK version: 1.7 or later
2. Android Studio version: 3.X or later
3. minSdkVersion: 21 or later
4. targetSdkVersion: 31 (recommended)
5. compileSdkVersion: 29 (recommended)
6. Gradle: 4.1 or later (recommended)
7. Must have a Huawei Developer Account.
8. Must have a Huawei phone with HMS 4.0.0.300 or later and running EMUI 4.0 or later.
9. React Native environment with Android Studio, Node Js and Visual Studio code.
Preparation
1. Create an app or project in the Huawei App Gallery Connect.
2. Provide the SHA Key and App Package name of the project in App Information Section.
3. Download the agconnect-services.json file.
Integration process
1. 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
2. Create project using below command.
Code:
react-native init project name
3. Download the Plugin using NPM.
Open project directory path in command prompt and run this command.
Code:
npm [email protected]/applinking
4. Configure android level build.gradle.
a. Add to buildscript/repositores.
Code:
maven {url 'http://developer.huawei.com/repo/'}
b. Add to allprojects/repositories.
Code:
maven {url 'http://developer.huawei.com/repo/'}
Development Process
Add the following configuration to the activity for processing links. Set android:host to the domain name in deepLink and android:scheme to the custom scheme. When a user taps a link containing this deep link, your app uses this activity to process the link.
<!-- AndroidManifest.xml. -->
Code:
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<!-- Add the custom domain name and scheme -->
<data android:host="<DeepLink_Host>" android:scheme="https" />
</intent-filter>
Note: Make sure you do not specify Android launch mode in your React Native project. In case you have set android:launchMode="singleTask" in your project. App Linking will not work properly so you need to remove that line from your AndroidManifest.xml file.
Open the build.gradle file in the android directory of your React Native project, and change the value of minSdkVersion in buildscript to 19.
Code:
defaultConfig {
applicationId "<package_name>"
minSdkVersion 19
/*
<Other configurations>
*/
}
Creating a Link of App Linking in a React Native App using AppGallery Connect
Log In to AppGallery Connect and Choose your App from My Projects tab.
Go to>Growing > App Linking>Enable now.
Choose URL prefix>Add URL prefix.
Select Set domain name option and then click on Next button. A page will come up will verification completion alert.
Click App Linking and then click Create App Linking for deep linking purpose. Set a short link and click Next.
Set Deep Link and click Next.
App Linking works on multiple platforms regardless of whether your app has been installed. On an Android, HarmonyOS, or iOS device that has your app installed, users will see your in-app content when they tap the link.
App Linking name: deep link name.
Default deep link: deep link used to open an app.
Android deep link: deep link preferentially opened on an Android device.
iOS deep Link URL: deep link preferentially opened on an iOS device.
Click Next and Select Set Android link behaviour for your Android application as below.
Select your application from the Add Android app menu. Redirect user to AppGallery page if the application is not installed on the device. Then click on Next button.
Receiving Links of App Linking
Short App Linking
AgcAppLinking.buildShortAppLinking () is used to get the short link url. Add this code in App.js.
Code:
AgcAppLinking.buildShortAppLinking(object).then(result => { Alert.alert("Short App Linking",result.shortLink); this.createCustomView("buildShortAppLinking : ", result.shortLink)
});
Long App Linking
AgcAppLinking.buildLongAppLinking () is used to get the long link url. Add this code in App.js.
Code:
AgcAppLinking.buildLongAppLinking(object).then(result => {
Alert.alert("Long App Linking", JSON.stringify(result));
this.createCustomView("buildLongAppLinking : ", result)
});
Output
Tips and Tricks
1. Set minSdkVersion to 19 or higher.
2. URL prefix should be unique and can contain only lowercase letters and digits.
3. Link name and Default deep link can be same and follow as https://domainname.com/xxx
Where “domainname” is URLprefix which we set above and “xxx” is specific in-app content page to re-direct.
4. You can customize the deep link, which is different from the URL prefix of the link.
5. Ensure that the App Store ID and team ID have been configured. If they are not configured, add them as prompted.
Conclusion
In this article, we have learnt integration of Huawei AppLinking service into React Native app development. Links can be created using Huawei App Linking capabilities and use them further for in –app content re-directions for large scale android applications.
Reference
App Linking: Documentation
App Linking: Training Video

Categories

Resources