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

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

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

Huawei Flight Booking Application (Cloud DB) – Part 8

Introduction
Flight booking app allows user to search and book flight. In this article, we will integrate Huawei Cloud DB into demo flight booking application.
Huawei Cloud DB is a computing platform that provides functionality of traditional database with cloud computing. The cloud DB ensures data availability, reliability, consistency, security and enables seamless data synchronization between the device and cloud, and supports offline application operations, helps developers quickly develop device-cloud and multi-device synergy applications. Cloud DB builds the Mobile backend as a service capability for the AppGallery Connect platform. This provides developer to focus on application services, delivering the efficient product.
For prerequisite and set up, refer to part 1.
Usecase
1. Once user books the flight from the app, we will store flight booking information in cloud DB.
2. User can navigate to Itinerary Screen from navigation drawer to see all the flight booked by him in past.
{
"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"
}
Permissions
By default, users who access Cloud DB from the AppGallery Connect console or cloud function have all permissions, as they are assigned with administrator role.
Everyone : All users. This role has only query permission granted.
Authenticated user: Users who have passed the AppGallery Connect login.This role has the query permission by default and upsert and delete permission can be granted.
Data creator: Authenticated users who create data. Data creators can upsert or delete the data created only by themselves. The information about data creator is stored in data table system records. This role has all permissions by default and can customize the permissions.
Administrator: Developers who access Cloud DB from the AppGallery Connect console . This role has all permissions by default and can customize the permissions.
Accessing Cloud DB
Since Cloud DB is in beta stage, developers need to send a mail to activate this service in their app. Developer needs to create Huawei developer account. Once account created, developers need to create an app in App Gallery connect. After completing all the necessary steps, developer have to request the activation of the service by sending an e-mail to [email protected] with the subject as "[Cloud DB]-[Company name]-[Developer account ID]-[App ID]". To access the app ID, see Querying App Information. Usually it takes 1 to 3 days for activation, once activated , developer can integrate cloud DB service in their app.
Getting started with Cloud DB
1. Log in to AppGallery Connect and select My Projects.
2. Select Application for which you want to create object types.
3. Choose Build > Cloud DB from left panel.
4. Click on Enable now.
5. Click Add to create object type.
6. Set Object Type Name to EaseMyFlight, and click Next.
7. Click on Add fields , add the fields and click Next.
8. Click Add Index, set Index Name and Indexed Field, and click Next.
9. Add permissions as follows and click Next. (For Everyone , upsert and delete access is not allowed).
10. Click Ok. Object types are created and displayed in the object type list.
11. Click Export. Select JAVA as export file name. Enter the package name of JAVA file. package name can contain Letters A–Z or a–z, Digits 0–9, Special characters _ and .
12.Click Export. The file that contains all object types will be downloaded. Add the exported JAVA file in your project.
Cloud DB Zone
1. Log in to AppGallery Connect and select My apps.
2. Select Application for which you want to create object types.
3. Choose Build > Cloud DB from left panel.
4. Click Cloud DB Zones tab.
5. Click Add to navigate to the Cloud DB zone creation page.
6. Enter easeMyFlightZone in the Cloud DB Zone Name text box.
Development
Prerequisites
Auth Service has to be integrated. Follow this tutorial to integrate Auth Service.
1. Add cloud DB SDK dependecy in app- level build.gradle.
Code:
// Add the Cloud DB SDK.
implementation 'com.huawei.agconnect:agconnect-database:1.2.1.301'
2. Add compatibility mode to JDK 1.8 in app- level build.gradle.
Code:
compileOptions {
sourceCompatibility = 1.8
targetCompatibility = 1.8
}
3. Initialize AGConnectCloudDB in Application class.
Code:
public class EaseMyFlightApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
initAGConnectCloudDB(getApplicationContext());
}
public static void initAGConnectCloudDB(Context context) {
AGConnectCloudDB.initialize(context);
}
}
4. Get the instance of AGConnectCloudDB and create object types.
Code:
mCloudDB = AGConnectCloudDB.getInstance(); mCloudDB.createObjectType(ObjectTypeInfoHelper.getObjectTypeInfo());
5. Create the Cloud DB zone configuration file and open the Cloud DB zone.
Code:
mConfig = new CloudDBZoneConfig("easeMyFlightZone", CloudDBZoneConfig.CloudDBZoneSyncProperty.CLOUDDBZONE_CLOUD_CACHE,
CloudDBZoneConfig.CloudDBZoneAccessProperty.CLOUDDBZONE_PUBLIC);
mConfig.setPersistenceEnabled(true);
try {
mCloudDBZone = mCloudDB.openCloudDBZone(mConfig, true);
} catch (AGConnectCloudDBException e) {
Log.w(TAG, "openCloudDBZone: " + e.getMessage());
}
6. Writing Data
Data can be entered either manually from App Gallery Connect(administrator or data creater) or programmatically(authorized user) by using cloud DB SDK , if user has the permission. If same value in primary key is used, data will be modified.
Code:
public void insertDataToCloudDB(EaseMyFlight info) {
if (mCloudDBZone == null) {
Log.w(TAG, "CloudDBZone is null, try re-open it");
return;
}
CloudDBZoneTask<Integer> upsertTask = mCloudDBZone.executeUpsert(info);
upsertTask.addOnSuccessListener(new com.huawei.agconnect.cloud.database.OnSuccessListener<Integer>() {
@Override
public void onSuccess(Integer integer) {
Log.w(TAG, "upsert " + integer + " records");
}
}).addOnFailureListener(new com.huawei.agconnect.cloud.database.OnFailureListener() {
@Override
public void onFailure(Exception e) {
Log.e(TAG, "Insertion failed : "+ e.getMessage());
e.printStackTrace();
}
});
}
More information, you can visit https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0201388320242800533&fid=0101187876626530001
Does it supports BLOB Data Type ?

Ads Kit Integration with Cocos

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

Convert Image to document using Huawei HiAI Engine in Android

Introduction
In this article, we will learn how to convert image to document such as PPT or pdf format. As for users, it is inefficient to manually organize, edit, or improve the note-taking snapshots at conferences or images of paper documents.
Document converter enables apps to convert document images into electronic documents conveniently, such as PPT files. It can recognize documents and the texts in images, and return the recognized content to the client, which will restore the results into a PPT file.
How to integrate Document Converter
1. Configure the application on the AGC.
2. Apply for HiAI Engine Library.
3. Client application development process.
Configure application on the AGC
Follow the steps
Step 1: We need to register as a developer account in AppGallery Connect. If you are already a developer ignore this step.
Step 2: Create an app by referring to Creating a Project and Creating an App in the Project
Step 3: Set the data storage location based on the current location.
Step 4: Generating a Signing Certificate Fingerprint.
Step 5: Configuring the Signing Certificate Fingerprint.
Step 6: Download your agconnect-services.json file, paste it into the app root directory.
Apply for HiAI Engine Library
What is Huawei HiAI?
HiAI is Huawei’s AI computing platform. HUAWEI HiAI is a mobile terminal–oriented artificial intelligence (AI) computing platform that constructs three layers of ecology: service capability openness, application capability openness, and chip capability openness. The three-layer open platform that integrates terminals, chips, and the cloud brings more extraordinary experience for users and developers.
How to apply for HiAI Engine?
Follow the steps
Step 1: Navigate to this URL, choose App Service > Development and click HUAWEI HiAI.
{
"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 2: Click Apply for HUAWEI HiAI kit.
Step 3: Enter required information like Product name and Package name, click Next button.
Step 4: Verify the application details and click Submit button.
Step 5: Click the Download SDK button to open the SDK list.
Step 6: Unzip downloaded SDK and add into your android project under libs folder.
Step 7: Add jar files dependences into app build.gradle file.
implementation fileTree(include: ['*.aar', '*.jar'], dir: 'libs')
implementation 'com.google.code.gson:gson:2.8.6'
repositories {
flatDir {
dirs 'libs'
}
}Copy codeCopy code
Client application development process
Follow the steps.
Step 1: Create an Android application in the Android studio (Any IDE which is your favorite).
Step 2: Add the App level Gradle dependencies. Choose inside project Android > app > build.gradle.
Code:
apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect'
Root level gradle dependencies.
Code:
maven { url 'https://developer.huawei.com/repo/' }
classpath 'com.huawei.agconnect:agcp:1.4.1.300'
Step 3: Add permission in AndroidManifest.xml
XML:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
Step 4: Build application.
Request the runtime permission
Java:
private void requestPermissions() {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int permission1 = ActivityCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE);
int permission2 = ActivityCompat.checkSelfPermission(this,
Manifest.permission.CAMERA);
if (permission1 != PackageManager.PERMISSION_GRANTED || permission2 != PackageManager
.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, 0x0010);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
Java:
private void convertDocument() {
DocConverter docConverter = new DocConverter(this);//Construct Detector.
VisionImage image = VisionImage.fromBitmap(mBitmap);
VisionTextConfiguration config = new VisionTextConfiguration.Builder()
.setAppType(VisionTextConfiguration.APP_NORMAL)
.setProcessMode(VisionTextConfiguration.MODE_IN)
.setDetectType(TextDetectType.TYPE_TEXT_DETECT_FOCUS_SHOOT)
.setLanguage(VisionTextConfiguration.ENGLISH)
.build();
DocConverterConfiguration docConfig = new DocConverterConfiguration.Builder().build();
docConfig.setTextConfig(config);
MyCallBack cb = new MyCallBack();
int result_code = docConverter.detectSlide(image, cb);
}
class MyCallBack implements SlideCallback {
public void onDocDetect(DocCoordinates coor) {
Log.d("MainActivity", coor.toString());
}
public void onDocRefine(Bitmap bitmap) {
}
public void onSuperResolution(Bitmap bitmap) {
//Set super resolution image to image view
}
public void onTextRecognition(Text text) {
Log.d("MainActivity", text.getValue());
mTxtViewResult.setText(text.getValue());
}
public void onError(int errorCode) {
Log.d("MainActivity", "Error code: "+errorCode);
}
}
Result
Tips and Tricks
An image with a width ranging from 1080 pixels to 2560 pixels is recommended.
Multi-thread invoking is currently not supported.
If you are taking Video from a camera or gallery make sure your app has camera and storage permissions.
Add the downloaded huawei-hiai-vision-ove-10.0.4.307.aar, huawei-hiai-pdk-1.0.0.aar file to libs folder.
Check dependencies added properly.
Latest HMS Core APK is required.
Min SDK is 21. Otherwise you will get Manifest merge issue.
Conclusion
In this article, we have learnt what is the document convertor using Huawei HiAI using android and java. We have learnt how to convert the image to pdf. Huawei HiAI gives immense control on the text from image.
Reference
Document convertor
Apply for Huawei HiAI
Can we get the same content format of document after image is converted into text?

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