Integrating In-App Purchases kit using Flutter (Cross Platform) - Huawei Developers

4. Gradle 4.6 and later
Steps to integrate service
1. We need to register as a developer account in AppGallery Connect
2. Create an app by referring to Creating a Project and Creating an App in the Project
3. Set the data storage location based on current location
4. Enabling Required Services: IAP Kit you will be asked to apply for Merchant service this process will take 2 days for review.
5. Enable settings In-app Purchases choose My Projects > Earn > In-App Purchases and click Settings.
6. Generating a Signing Certificate Fingerprint.
7. Configuring the Signing Certificate Fingerprint.
8. Get your agconnect-services.json file to the app root directory.
Development Process
Create Application in Android Studio.
1. Create Flutter project.
2. 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'3.
3. Add HMS IAP kit plugin download using below URL.
https://developer.huawei.com/consum...y-V1/flutter-sdk-download-0000001050727030-V1
4. On your Flutter project directory find and open your pubspec.yaml file and add library to dependencies to download the package from pub.dev. Or if you downloaded the package from the HUAWEI Developer website, specify the library path on your local device. For both ways, after running pub get command, the plugin will be ready to use.
Code:
name: mlsample
description: A new Flutter application.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
version: 1.0.0+1
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
huawei_iap:
path: ../huawei_iap/
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
5. We can check the plugins under External Libraries directory.
6. Open main.dart file to create UI and business logics.
Configuring Product Info
To Add a product go to MyApps > DemoApp > Operate
{
"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"
}
Click Add Product Configure product information and click Save.
After the configuration is complete, Activate the product in the list to make it valid and purchasable.
Environment Check
Before calling any service you need to check user is login or not using IapClient.isEnvReady
Code:
environmentCheck() async {
isEnvReadyStatus = null;
try {
IsEnvReadyResult response = await IapClient.isEnvReady();
setState(() {
isEnvReadyStatus = response.status.statusMessage;
});
} on PlatformException catch (e) {
if (e.code == HmsIapResults.LOG_IN_ERROR.resultCode) {
_showToast(context, HmsIapResults.LOG_IN_ERROR.resultMessage);
} else {
_showToast(context, e.toString());
}
}
}
Fetch Product Info
We can fetch the product information of products using obtainProductInfo()
Note: The SkuIds is the same as that configured in AppGallery Connect.
Code:
loadConsumables() async {
try {
ProductInfoReq req = new ProductInfoReq();
req.priceType = IapClient.IN_APP_CONSUMABLE;
req.skuIds = ["SUB_30", "PR_6066"];
ProductInfoResult res = await IapClient.obtainProductInfo(req);
setState(() {
consumable = [];
for (int i = 0; i < res.productInfoList.length; i++) {
consumable.add(res.productInfoList[i]);
}
});
} on PlatformException catch (e) {
if (e.code == HmsIapResults.ORDER_HWID_NOT_LOGIN.resultCode) {
log(HmsIapResults.ORDER_HWID_NOT_LOGIN.resultMessage);
} else {
log(e.toString());
}
}
}
Purchase Result Info
When user click into buy button, first create purchase intent request and specify the type of the product and product ID in the request parameter.
If you want to test purchase functionality you need to create testing account. Using Sandbox testing we can do payment end-to-end functionality.
Once payment successfully done we get PurchaseResultInfo object, so this object has the details of the purchase.
Code:
subscribeProduct(String productID) async {
try {
PurchaseResultInfo result = await IapClient.createPurchaseIntent(
PurchaseIntentReq(
priceType: IapClient.IN_APP_CONSUMABLE, productId: productID));
if (result.returnCode == HmsIapResults.ORDER_STATE_SUCCESS.resultCode) {
log("Successfully plan subscribed");
} else {
log(result.errMsg);
}
} on PlatformException catch (e) {
if (e.code == HmsIapResults.ORDER_HWID_NOT_LOGIN.resultCode) {
log(HmsIapResults.ORDER_HWID_NOT_LOGIN.resultMessage);
} else {
log(e.toString());
}
}
}<strong><em><strong> </strong></em></strong>
For more, you can check https://forums.developer.huawei.com/forumPortal/en/topic/0204454642374170012

Related

Great way to test android apps[HMS and GMS], A/B Testing

More information about this, you can visit HUAWEI Developer Forum
​Introduction
This article will guide you to use A/B testing in android project. It will provide details to use HMS and GMS.
Steps
1. Create App in Android
2. Configure App in AGC
3. Integrate the SDK in our new Android project
4. Integrate the dependencies
5. Sync project
Procedure
Step1: Create application in android studio.
HMS related dependencies, Add below dependencies in app directory
Code:
implementation 'com.huawei.agconnect:agconnect-remoteconfig:1.3.1.300'
apply plugin:'com.huawei.agconnect'
Add below dependencies in root directory
Code:
maven { url 'http://developer.huawei.com/repo/' }
classpath 'com.huawei.agconnect:agcp:1.2.1.301'
GMS related dependencies, Add below dependencies in app directory
Code:
implementation 'com.google.android.gms:play-services-analytics:17.0.0'
implementation 'com.google.firebase:firebase-config:19.2.0'
Add below dependencies into root directory
Code:
classpath 'com.google.gms:google-services:4.3.3'
Step2: Create MobileCheckService class, using this class you can identify whether the device has HMS or GMS.
Code:
class MobileCheckService {
fun isGMSAvailable(context: Context?): Boolean {
if (null != context) {
val result: Int = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(context)
if (com.google.android.gms.common.ConnectionResult.SUCCESS === result) {
return true
}
}
return false
}
fun isHMSAvailable(context: Context?): Boolean {
if (null != context) {
val result: Int = HuaweiApiAvailability.getInstance().isHuaweiMobileServicesAvailable(context)
if (com.huawei.hms.api.ConnectionResult.SUCCESS == result) {
return true
}
}
return false
}
}
Step3: Create instance for Mobilecheckservice inside activity class. Inside OnCreate() call checkAvailableMobileService().This method return whether the device has HMS or GMS.
Code:
private fun checkAvailableMobileService() {
if (mCheckService.isHMSAvailable(this)) {
Toast.makeText(baseContext, "HMS Mobile", Toast.LENGTH_LONG).show()
configHmsTest()
} else
if (mCheckService.isGMSAvailable(this)) {
Toast.makeText(baseContext, "GMS Mobile", Toast.LENGTH_LONG).show()
configGmsTest()
} else {
Toast.makeText(baseContext, "NO Service", Toast.LENGTH_LONG).show()
}
}
Step4: If the device support HMS, then use AGConnectConfig.
Code:
private fun configHmsTest() {
val config = AGConnectConfig.getInstance()
config.applyDefault(R.xml.remote_config_defaults)
config.clearAll()
config.fetch().addOnSuccessListener { configValues ->
config.apply(configValues)
config.mergedAll
var sampleTest = config.getValueAsString("Festive_coupon")
Toast.makeText(baseContext, sampleTest, Toast.LENGTH_LONG).show()
}.addOnFailureListener { Toast.makeText(baseContext, "Fetch Fail", Toast.LENGTH_LONG).show() }
}
Step5: If the device support GMS, then use FirebaseRemoteConfig.
Code:
private fun configGmsTest() {
val firebase = FirebaseRemoteConfig.getInstance();
val configSettings = FirebaseRemoteConfigSettings.Builder().build()
firebase.setConfigSettingsAsync(configSettings)
firebase.setDefaultsAsync(R.xml.remote_config_defaults)
firebase.fetch().addOnCompleteListener { configValues ->
if (configValues.isSuccessful) {
firebase.fetchAndActivate()
var name = firebase.getString("Festive_coupon")
Toast.makeText(baseContext, name, Toast.LENGTH_LONG).show()
} else {
Toast.makeText(baseContext, "Failed", Toast.LENGTH_LONG).show()
}
}
}
App Configuration in Firebase:
Note: A/B test is using HMS configuration, refer
https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0201248355275100167&fid=0101187876626530001
Step1: To configure app into firebase Open firebase https://console.firebase.google.com/u/0/?pli=1
{
"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"
}
Step2: Click Add Project and add required information like App Name, package name, SHA-1.
Step3: After configuration is successful, then click A/B Testing in Grow menu.
To Start A/b testing experiment Click Create experiment button, It will show you list of supported experiments. Using Firebase you can do three experiments.
· Notifications
· Remote Config
· In-App Messaging
Notification: This experiment will use for sending messages to engage the right users at the right moment.
Remote Config: This experiment will use to change app-behavior dynamically and also using server-side configuration parameters.
In-App Messaging: This experiment will use to send different In-App Messages.
Step4: Choose AbTesting > Remote Config > Create a Remote Config experiment, provide the required information to test, as follows
Step5: Choose AbTesting > Remote Config > App_Behaviour, following page will display.
Step6: Click Start experiment, then start A/B test based on the experiment conditions it will trigger
Step7: After successful completion of experiment, we can get report.
Conclusion:
Using A/B test, you can control the entire experiment from HMS or GMS dashboard, this form of testing will be highly effective for the developers.
Reference:
To know more about firebase console, follow the URL https://firebase.google.com/docs/ab-testing
Share your thoughts on this article, if you are already worked with A/B tests, then you can share your experience on separation between them with us

Online Food ordering app ([email protected]) using AGC Auth Service | JAVA

More information like this, you can visit HUAWEI Developer Forum​
Introduction
Online food ordering is process that delivers food from local restaurants. Mobile apps make our world better and easier customer to prefer comfort and quality instead of quantity.
Sign In Module
User can login with mobile number to access food order application. Using auth service we can integrate third party sign in options. Huawei Auth service provides a cloud based auth service and SDK.
In this article, following Kits are covered:
1. AGC Auth Service
2. Ads Kit
3. Site kit
Steps
1. Create App in Android.
2. Configure App in AGC.
3. Integrate the SDK in our new Android project.
4. Integrate the dependencies.
5. Sync project.
Screens
{
"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"
}
Configuration
1. Login into AppGallery Connect, select FoodApp in My Project list.
2. Enable required APIs in manage APIs tab.
Choose Project Settings > ManageAPIs
3. Enable auth service before enabling Authentication modes as we need to enable Auth Service.
  Choose Build > Auth Service and click Enable now top right-corner
4. Enable sign in modes required for application
Integration
Create Application in Android Studio.
App level gradle dependencies.
Code:
apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect'
Gradle dependencies
Code:
implementation 'com.google.android.material:material:1.3.0-alpha02'
implementation 'com.huawei.agconnect:agconnect-core:1.4.0.300'
implementation 'com.huawei.agconnect:agconnect-auth:1.4.0.300'
implementation 'com.huawei.hms:hwid:4.0.4.300'
implementation 'com.huawei.hms:site:4.0.3.300'
implementation 'com.huawei.hms:ads-lite:13.4.30.307'
Root level gradle dependencies
Code:
maven {url 'https://developer.huawei.com/repo/'}
classpath 'com.huawei.agconnect:agcp:1.3.1.300'
Add the below permissions in Android Manifest file
Code:
<manifest xlmns:android...>
...
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application ...
</manifest>
Ads Kit: Huawei ads SDK to quickly integrate ads into your app, ads can be a powerful assistant to attract users.
Code Snippet
Code:
<com.huawei.hms.ads.banner.BannerView
android:id="@+id/huawei_banner_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
hwads:adId="testw6vs28auh3"
hwads:bannerSize="BANNER_SIZE_360_57" />
Code:
BannerView hwBannerView = findViewById(R.id.huawei_banner_view);
AdParam adParam = new AdParam.Builder()
.build();
hwBannerView.loadAd(adParam);
Auth Service:
1. Create Object for VerifyCodeSettings. Apply for verification code by mobile number based login.
Code:
VerifyCodeSettings mVerifyCodeSettings = VerifyCodeSettings.newBuilder()
.action(VerifyCodeSettings.ACTION_REGISTER_LOGIN)
.sendInterval(30)
.locale(Locale.getDefault())
.build();
2. Send mobile number, country code and verify code settings object.
Code:
if (!mMobileNumber.isEmpty() && mMobileNumber.length() == 10) {
Task<VerifyCodeResult> resultTask = PhoneAuthProvider.requestVerifyCode("+91", mMobileNumber, mVerifyCodeSettings);
resultTask.addOnSuccessListener(verifyCodeResult -> {
Toast.makeText(SignIn.this, "verify code has been sent.", Toast.LENGTH_SHORT).show();
if (!isDialogShown) {
verfiyOtp();
}
}).addOnFailureListener(e -> Toast.makeText(SignIn.this, "Send verify code failed.", Toast.LENGTH_SHORT).show());
Toast.makeText(this, mEdtPhone.getText().toString(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Invalid Phone Number!", Toast.LENGTH_SHORT).show();
}
3. Create object for Phone User Builder.
Code:
PhoneUser mPhoneUser = new PhoneUser.Builder()
.setCountryCode("+91")
.setPhoneNumber(mMobileNumber)
.setVerifyCode(otp)
.setPassword(null)
.build();
4. Check below code snippet to validate OTP.
Code:
AGConnectAuth.getInstance().createUser(mPhoneUser)
.addOnSuccessListener(signInResult -> {
Toast.makeText(SignIn.this, "Verfication success!", Toast.LENGTH_LONG).show();
SharedPrefenceHelper.setPreferencesBoolean(SignIn.this, IS_LOGGEDIN, true);
redirectActivity(MainActivity.class);
}).addOnFailureListener(e -> Toast.makeText(SignIn.this, "Verfication failed!", Toast.LENGTH_LONG).show());
Site kit: Using HMS Site kit we can provide easy access to hotels and places.
Code:
searchService.textSearch(textSearchRequest, new SearchResultListener<TextSearchResponse>() {
@Override
public void onSearchResult(TextSearchResponse response) {
for (Site site : response.getSites()) {
SearchResult searchResult = new SearchResult(site.getAddress().getLocality(), site.getName());
String result = site.getName() + "," + site.getAddress().getSubAdminArea() + "\n" +
site.getAddress().getAdminArea() + "," +
site.getAddress().getLocality() + "\n" +
site.getAddress().getCountry() + "\n";
list.add(result);
searchList.add(searchResult);
}
mAutoCompleteAdapter.clear();
mAutoCompleteAdapter.addAll(list);
mAutoCompleteAdapter.notifyDataSetChanged();
autoCompleteTextView.setAdapter(mAutoCompleteAdapter);
Toast.makeText(getActivity(), String.valueOf(response.getTotalCount()), Toast.LENGTH_SHORT).show();
}
@Override
public void onSearchError(SearchStatus searchStatus) {
Toast.makeText(getActivity(), searchStatus.getErrorCode(), Toast.LENGTH_SHORT).show();
}
});
Result:
Conclusion:
In this article we have learnt Auth service,Ads Kit & site kit Integration in food application.
Reference:
Auth Service:
https://developer.huawei.com/consumer/en/doc/development/Tools-Guides/agc-conversion-auth-0000001050157270
Ads Kit :
https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/publisher-service-introduction-0000001050064960
Site Kit :
https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/android-sdk-introduction-0000001050158571

Intermediate: How to Integrate Huawei Dark-Mode and App Status awareness into flutter Application

Introduction
In this article, we will learn how to implement Huawei Awareness kit features, so we can easily integrate these features in to our Flutter application. In this article we are going to take a look at the Awareness kit Capture API features such as Dark mode awareness and App status awareness.
{
"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 is Huawei Awareness kit Service?
Huawei Awareness kit supports to get the app insight into a users’ current situation more efficiently, making it possible to deliver a smarter, more considerate user experience and it provides the users’ current time, location, behavior, audio device status, ambient light, weather, and nearby beacons, application status, and mobile theme mode.
Restrictions
1. Dark mode: It supports EMUI 10.0 or later for Huawei devices and non-Huawei devices required Android 10.0 or later (API level 29 is required).
2. App status: It supports EMUI 5.0 or later for Huawei devices and non-Huawei devices currently it is not supporting
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. Minimum API Level 29 is required.
4. Required EMUI 10.0 For Dark-mode and EMUI 5.0 for App status.
How to integrate HMS Dependencies.
1. First of all, we need to create an app on AppGallery Connect and add related details about HMS Core to our project. For more information check this link
2. Enable the Awareness Kit in the Manage API section and add the plugin.
3. Add the required dependencies to the build.gradle file under root folder.
Code:
maven {url 'http://developer.huawei.com/repo/'}
classpath 'com.huawei.agconnect:agcp:1.4.1.300'
4. Now we can implement Awareness Kit plugin. To implement Awareness Kit to our app, we need to download the plugin. Follow the URL for cross-platform plugins.
5. After completing all the above steps, you need to add the required kits’ Flutter plugins as dependencies to pubspec.yaml file. You can find all the plugins in pub.dev with the latest versions.
Code:
huawei_awareness:
path: ../huawei_awareness/
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.
Use Awareness to get the dark mode status
With Dark-mode Status Awareness, we can detect the dark mode status of the device. We can get the status using capture API.
Code:
void loadAppTheme() async {
DarkModeResponse response = await AwarenessCaptureClient.getDarkModeStatus();
bool isDarkMode = response.isDarkModeOn;
setState(() {
if (isDarkMode) {
Provider.of<ThemeChanger>(context).setTheme(darkTheme);
} else {
Provider.of<ThemeChanger>(context).setTheme(lightTheme);
}
});
}
Use Awareness to get the Application status
With Application status Awareness, we can detect whether application is in which mode like silent, running using package name.
Code:
void checkAppStatus() async {
String packName = "******************";
ApplicationResponse response =
await AwarenessCaptureClient.getApplicationStatus(
packageName: packName);
int appState = response.applicationStatus;
setState(() {
switch (appState) {
case ApplicationStatus.Unknown:
_showDialog(context, "Demo Application Not found");
print("log1" + "Application Not found");
break;
case ApplicationStatus.Silent:
_showDialog(context, "Demo Application Currently in silent mode");
print("log1" + "Application silent");
break;
case ApplicationStatus.Running:
_showDialog(context, "Demo Application Currently in Running mode");
print("log1" + "Application Running");
break;
}
});
}
Final code here
Code:
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider<ThemeChanger>(
create: (context) => ThemeChanger(ThemeData.light()),
child: new App(),
);
}
}
class App extends StatelessWidget {
@override
Widget build(BuildContext context) {
final appState = Provider.of<ThemeChanger>(context);
return MaterialApp(
title: "WellFit",
theme: appState.getTheme(),
home: Scaffold(
body: Tabs(),
),
);
}
}
ThemeNotifier class
Code:
class ThemeChanger with ChangeNotifier {
ThemeData _themeData;
ThemeChanger(this._themeData);
getTheme() => _themeData;
setTheme(ThemeData themeData) {
_themeData = themeData;
notifyListeners();
}
}
Demo
​
Tips and Tricks
1. Download latest HMS Flutter plugin.
2. Set minSDK version to 29 or later.
3. Do not forget to click pug get after adding dependencies.
4. Do not forget to set data processing location.
5. Refer this URL for supported Devices list.
Conclusion
In this article, I have covered two services Dark-mode awareness and App status Awareness.
Using Dark-mode awareness we can easily identify which theme currently we activated in settings page.
Using App Status awareness we can monitor the application in which state like silent or running these two we covered in this article.
Thanks for reading! If you enjoyed this story, please click the Like button and Follow. Feel free to leave a Comment below.
Reference
Awareness Kit URL
Original Source

Save Contacts from QR Code using Huawei Code Recognition by Huawei HiAI in Android

Introduction
In this article we will learn how to integrate Code Recognition. We will build the contact saving application from QR code using Huawei HiAI.
Code recognition identifies the QR codes and bar codes to obtain the contained information, based on which the service framework is provided.
This API can be used to parse QR codes and bar codes in 11 scenarios including Wi-Fi and SMS, providing effective code detection and result-based service capabilities. This API can be widely used in apps that require code scanning services.
Software requirements
Any operating system (MacOS, Linux and Windows).
Any IDE with Android SDK installed (IntelliJ, Android Studio).
HiAI SDK.
Minimum API Level 23 is required.
Required EMUI 9.0.0 and later version devices.
Required process kirin 990/985/980/970/ 825Full/820Full/810Full/ 720Full/710Full
How to integrate Code Recognition.
Configure the application on the AGC.
Apply for HiAI Engine Library.
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.
Code:
implementation fileTree(include: ['*.aar', '*.jar'], dir: 'libs')
implementation 'com.google.code.gson:gson:2.8.6'
repositories {
flatDir {
dirs 'libs'
}
}
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.
Java:
Bitmap bitmap;
List<Barcode> codes;
private void initVisionBase() {
VisionBase.init(this, new ConnectionCallback() {
@Override
public void onServiceConnect() {
}
@Override
public void onServiceDisconnect() {
}
});
}
private void saveContact() {
if (codes != null && codes.size() > 0) {
Log.d("New data: ", "" + new Gson().toJson(codes));
String contactInfo = new Gson().toJson(codes.get(0));
ContactInfo info = new Gson().fromJson(contactInfo, ContactInfo.class);
Intent i = new Intent(Intent.ACTION_INSERT);
i.setType(ContactsContract.Contacts.CONTENT_TYPE);
i.putExtra(ContactsContract.Intents.Insert.NAME, info.getContactInfo().getPerson().getName());
i.putExtra(ContactsContract.Intents.Insert.PHONE, info.getContactInfo().getPhones().get(0).getNumber());
i.putExtra(ContactsContract.Intents.Insert.EMAIL, info.getContactInfo().getEmails().get(0).getAddress());
if (Integer.valueOf(Build.VERSION.SDK) > 14)
i.putExtra("finishActivityOnSaveCompleted", true); // Fix for 4.0.3 +
startActivityForResult(i, PICK_CONTACT_REQUEST);
} else {
Log.e("Data", "No Data");
}
}
class QRCodeAsync extends AsyncTask<Void, Void, List<Barcode>> {
Context context;
public QRCodeAsync(Context context) {
this.context = context;
}
@Override
protected List<Barcode> doInBackground(Void... voids) {
BarcodeDetector mBarcodeDetector = new BarcodeDetector(context);//Construct Detector.
VisionImage image = VisionImage.fromBitmap(bitmap);
ZxingBarcodeConfiguration config = new ZxingBarcodeConfiguration.Builder()
.setProcessMode(VisionTextConfiguration.MODE_IN)
.build();
mBarcodeDetector.setConfiguration(config);
mBarcodeDetector.detect(image, null, new VisionCallback<List<Barcode>>() {
@Override
public void onResult(List<Barcode> barcodes) {
if (barcodes != null && barcodes.size() > 0) {
codes = barcodes;
} else {
Log.e("Data", "No Data");
}
}
@Override
public void onError(int i) {
}
@Override
public void onProcessing(float v) {
}
});
return codes;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
}
Result
Tips and Tricks
An error code is returned if the size of an image input to the old API exceeds 20 MP. In this case, rescale the image for improved input efficiency and lower memory usage.
There are no restrictions on the resolution of the image input to the new API. However, an image larger than 224 x 224 in size and less than 20 MP is recommended.
If you are taking Video from a camera or gallery make sure your app has camera and storage permission.
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 built contact saving application and parsing the QR code image from gallery.
We have learnt the following concepts.
Introduction of Code Recognition?
How to integrate Code Recognition using Huawei HiAI
How to Apply Huawei HiAI
How to build the application
Reference
Code Recognition
Apply for Huawei HiAI
Happy coding
thanks for sharing!!

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?

Categories

Resources