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

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

Related

Implement the Automatic Bill Number Input Function Using ML Kit’s Text Recognition

More information like this, you can visit HUAWEI Developer Forum​
Introduction
In the previous post, we looked at how to use HUAWEI ML Kit’s card recognition function to implement the card binding function. With this function, users only need to provide a photo of their card, and your app will automatically recognize all of the key information. That makes entering card information much easier, but can we do the same thing for bills or discount coupons? Of course we can! In this post, I will show you how to implement automatic input of bill numbers and discount codes using HUAWEI ML Kit’s text recognition function.
Application
Text recognition is useful in a huge range of situations. For example, if you scan the following bill, indicate that the bill service number starts with “NO.DE SERVICIO”, and limit the length to 12 characters, you can quickly get the bill service number “123456789123” using the text recognition.
{
"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"
}
Similarly, if you scan the discount coupon below, start the discount code with “FAVE-” and limit the length to 4 characters, you’ll get the discount code “8329”, and can then complete the payment.
Pretty useful, right? You can also customize the information you want your app to recognize.
Integrating Text Recognition
So, let’s look at how to process bill numbers and discount codes.
1. Preparations
You can find detailed information about the preparations you need to make on the HUAWEI Developer.
Here, we’ll just look at the most important procedures.
1.1 Configure the Maven Repository Address in the Project-Level build.gradle File
Code:
buildscript {
repositories {
...
maven {url 'https://developer.huawei.com/repo/'}
}
}
dependencies {
...
classpath 'com.huawei.agconnect:agcp:1.3.1.300'
}
allprojects {
repositories {
...
maven {url 'https://developer.huawei.com/repo/'}
}
}
1.2 Add Configurations to the File Header
Once you’ve integrated the SDK, add the following configuration to the file header:
Code:
apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect'
1.3 Configure SDK Dependencies in the App-Level build.gradle File
Code:
dependencies {
// Import the base SDK.
implementation 'com.huawei.hms:ml-computer-vision-ocr:2.0.1.300'
// Import the Latin character recognition model package.
implementation 'com.huawei.hms:ml-computer-vision-ocr-latin-model:2.0.1.300'
// Import the Japanese and Korean character recognition model package.
implementation 'com.huawei.hms:ml-computer-vision-ocr-jk-model:2.0.1.300'
// Import the Chinese and English character recognition model package.
implementation 'com.huawei.hms:ml-computer-vision-ocr-cn-model:2.0.1.300'
}
1.4 Add these Statements to the AndroidManifest.xml File so the Machine Learning Model can Automatically Update
Code:
<manifest>
...
<meta-data
android:name="com.huawei.hms.ml.DEPENDENCY"
android:value="ocr" />
...
</manifest>
1.5 Apply for the Camera Permission
Code:
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
2. Code Development
2.1 Create an Analyzer
Code:
MLTextAnalyzer analyzer = new MLTextAnalyzer.Factory(context).setLanguage(type).create();
2.2 Set the Recognition Result Processor to Bind with the Analyzer
Code:
analyzer.setTransactor(new OcrDetectorProcessor());
2.3 Call the Synchronous API
Use the built-in LensEngine of the SDK to create an object, register the analyzer, and initialize camera parameters.
Code:
lensEngine = new LensEngine.Creator(context, analyzer)
.setLensType(LensEngine.BACK_LENS)
.applyDisplayDimension(width, height)
.applyFps(30.0f)
.enableAutomaticFocus(true)
.create();
2.4 Call the run Method to Start the Camera and Read the Camera Streams for the Recognition
Code:
try {
lensEngine.run(holder);
} catch (IOException e) {
// Exception handling logic.
Log.e("TAG", "e=" + e.getMessage());
}
2.5 Process the Recognition Result As Required
Code:
public class OcrDetectorProcessor implements MLAnalyzer.MLTransactor<MLText.Block> {
@Override
public void transactResult(MLAnalyzer.Result<MLText.Block> results) {
SparseArray<MLText.Block> items = results.getAnalyseList();
// Process the recognition result as required. Only the detection results are processed.
// Other detection-related APIs provided by ML Kit cannot be called.
…
}
@Override
public void destroy() {
// Callback method used to release resources when the detection ends.
}
}
2.6 Stop the Analyzer and Release the Detection Resources When the Detection Ends
Code:
if (analyzer != null) {
try {
analyzer.stop();
} catch (IOException e) {
// Exception handling.
}
}
if (lensEngine != null) {
lensEngine.release();
}
Demo Effect
And that’s it! Remember that you can expand this capability if you need to. Now, let’s look at how to scan travel bills.
And here’s how to scan discount codes to quickly obtain online discounts and complete payments.
Github Source Code
https://github.com/HMS-Core/hms-ml-demo/tree/master/Receipt-Text-Recognition
Awsome work !!

Online Food ordering app ([email protected]) | Map kit | JAVA Part-2

More information like this, you can visit HUAWEI Developer Forum​
Introduction
Online food ordering is process to deliver food from restaurants. In this article will do how to integrate Map kit in food applications. Huawei Map kit offers to work and create custom effects. This kit will work only Huawei device.
In this article, will guide you to show selected hotel locations on Huawei map.
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.
Map Module
Map kit covers map info more than 200 countries and it will support many languages. It will support different types of maps like Normal, Hybrid, Satellite, terrain Map.
Use Case
1. Display Map: show buildings, roads, temples etc.
2. Map Interaction: custom interaction with maps, create buttons etc.
3. Draw Map: Location markers, create custom shapes, draw circle etc.
Output
{
"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 Map Kit APIs in manage APIs tab.
Choose Project Settings > ManageAPIs
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.huawei.hms:maps:4.0.0.301'
Root level gradle dependencies
Code:
maven <strong>{</strong>url <strong>'https://developer.huawei.com/repo/'</strong><strong>}
</strong>classpath <strong>'com.huawei.agconnect:agcp:1.3.1.300'</strong>
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>
Map Kit:
1. Create xml layout class define below snippet.
Code:
<com.huawei.hms.maps.MapView
android:layout_marginTop="?actionBarSize"
android:id="@+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent"
map:cameraZoom="8.5"
map:mapType="normal"
map:uiCompass="true"1)
map:uiZoomControls="true"/>
2. Implement OnMapReadyCallback method in activity/fragment, import onMapReady() method.
Initialize map in onCreate() then Call getMapSync().
Code:
Bundle mapViewBundle = null;
if (savedInstanceState != null) {
mapViewBundle = savedInstanceState.getBundle(BUNDLE_KEY);
}
mMapView.onCreate(mapViewBundle);
mMapView.getMapAsync(this);
4. onMapReady() method enable required settings like location button, zoom controls, title gestures, etc.
Code:
@Override
public void onMapReady(HuaweiMap huaweiMap) {
hMap = huaweiMap;
hMap.isBuildingsEnabled();
hMap.setMapType(0);
hMap.isTrafficEnabled();
hMap.setMaxZoomPreference(10);
………
}
5. addMarker() using this method we can add markers on map we can define markers position, title, icon etc. We can create custom icons.
Code:
MarkerOptions markerOptions = new MarkerOptions()
.position(new LatLng(location.lat, location.lng))
.title(response.name)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_hotel));
hMap.addMarker(markerOptions)
.showInfoWindow();
6. animateCamera() using this method we can animate the movement of the camera from the current position to the position which we defined.
Code:
CameraPosition build = new CameraPosition.Builder()
.target(new LatLng(location.lat, location.lng))
.zoom(15)
.bearing(90)
.tilt(30)
.build();
CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(build);
hMap.animateCamera(cameraUpdate);
Result:
Conclusion
In this Article, I have explained how to integrate the Map on food application, displaying selected hotel on Map.
Reference:
Map Kit :
https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/android-sdk-introduction-0000001050158633

Integrate HUAWEI ML Kit with Ease, for High-Level Business Card Recognition

Introduction
In an age of digital living, maintaining interpersonal connections has never been more important. It's a common ritual for professionals to exchange business cards, but this can come with certain hassles – having to input the contact information for each new contact, including names, companies, and addresses. That's where business card recognition comes into the picture.
How It Works
The business card recognition service utilizes the optical character recognition (OCR) technology to digitize text on a card, converting it into an editable format, and classifying the recognized information by category. When you have integrated the service into your app, your users will be able to collect information on a business card simply by snapping a picture, scanning the QR code on the card, or importing the card image.
{
"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"
}
Preparations
Before API development, there are a few things that you'll need to do in preparation, for example, configuring the Maven repository address of the HMS Core SDK in your project, and integrating the SDK for the business card recognition service.
Install Android Studio
Official download website
Installation guide
Add Huawei Maven Repository to the Project-Level build.gradle File
Open the build.gradle File in the Root Directory of Your Android Studio Project
Add the Maven Repository Address
Go to buildscript > repositories and configure the Maven repository address for the HMS Core SDK.
Code:
repositories {
maven { url 'https://developer.huawei.com/repo/' }
}
}
Go to allprojects > repositories and configure the Maven repository address for the HMS Core SDK.
allprojects {
repositories {
maven { url 'https://developer.huawei.com/repo/' }
}
}
Import the SDK
Code:
dependencies {
// Text recognition SDK.
implementation 'com.huawei.hms:ml-computer-vision-ocr:2.0.1.300'
// Text recognition model.
implementation 'com.huawei.hms:ml-computer-vision-ocr-cn-model:2.0.1.300'
implementation 'com.huawei.hms:ml-computer-vision-ocr-jk-model:2.0.1.300'
implementation 'com.huawei.hms:ml-computer-vision-ocr-latin-model:2.0.1.300'
}
Add the Manifest File
Code:
<manifest
...
<meta-data
android:name="com.huawei.hms.ml.DEPENDENCY"
android:value="ocr" />
...
</manifest>
Add Permissions
Code:
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.hardware.camera.autofocus" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.autofocus" />
Submit a Dynamic Permission Application
Code:
if (!(ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED)) {
requestCameraPermission();
}
Development
1. Create the text analyzer MLTextAnalyzer to recognize text within images. Use the custom parameter MLLocalTextSetting to configure the on-device text analyzer.
Code:
MLLocalTextSetting setting = new MLLocalTextSetting.Factory()
.setOCRMode(MLLocalTextSetting.OCR_DETECT_MODE)
.setLanguage("zh")
.create();
MLTextAnalyzer analyzer = MLAnalyzerFactory.getInstance()
.getLocalTextAnalyzer(setting);
2. Use android.graphics.Bitmap to create an MLFrame. Supported image formats include JPG, JPEG, PNG, and BMP. It is recommended that the aspect ratio for landscape business cards be 2:1 and that for portrait business cards be 1:2.
Code:
MLFrame frame = MLFrame.fromBitmap(bitmap);
3. Pass the MLFrame object to the asyncAnalyseFrame method for text recognition.
Code:
Task<MLText> task = analyzer.asyncAnalyseFrame(frame);
task.addOnSuccessListener(new OnSuccessListener<MLText>() {
@Override
public void onSuccess(MLText text) {
// Recognition success.
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
// Recognition failure.
}
});
4. After recognition is complete, stop the analyzer to release recognition resources.
Code:
try {
if (analyzer != null) {
analyzer.stop();
}
} catch (IOException e) {
// IOException
} catch (Exception e) {
// Exception
}
More Information
We have developed a demo app that demonstrates the effects of the business card recognition service.
Reference
Official website of Huawei Developers
Development Guide
HMS Core official community on Reddit
Demo and sample code
Discussions on Stack Overflow

Track Fitness Application using Huawei Health Kit

Overview
Track Fitness application provides users daily step count, calorie burn, how much time user is doing exercise and total distance travelled during that time. Using these real time information, user can keep his fitness record on daily basis and can set a goal towards his fitness. This application uses the Room database for saving the records and displaying in the list. This application uses Huawei Account Kit and Health Kit for login and getting his real time step count. Let us know little about Huawei Health Kit, then we will focus on the implementation part.
Huawei Health Kit
HUAWEI Health Kit provides services for user’s health and fitness data. Using this kit, developers can get real time Step Count, Heart Rate, Body Temperature etc.
Huawei Health Kit provides the following key APIs for the Android client
1) Data Controller: Developers can use this API to insert, delete, update, and read data, as well as listen to data updates by registering a listener.
2) Activity Records Controller: Developers can use this API for tracking daily activity for users like Running, Sleeping etc.
3) Auto Recorder Controller: Developers can use this API to read sensor data in real time like step count.
Integration Started
1) First create an app in AppGallery Connect (AGC).
2) Get the SHA Key. For getting the SHA key, refer this article.
3) Click on Health kit in console.
{
"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"
}
4) Click Apply for Health Kit.
5) Select Product Type as Mobile App, APK Name as your project package name and check the required permission for your application to work, as shown below:
Finally click Submit button to apply for health kit.
6) Check if status is Enabled, as shown in below image.
7) After completing all the above points we need to download the agconnect-services.json from App Information Section. Copy and paste the Json file in the app folder of the android project.
8) Enter the below maven url inside the repositories of buildscript and allprojects (project build.gradle file):
Code:
maven { url ‘http://developer.huawei.com/repo/’ }
9) Enter the below Health Kit, account kit and auth service dependencies in the dependencies section:
Code:
implementation 'com.huawei.hms:base:4.0.0.100'
implementation 'com.huawei.hms:hwid:4.0.0.300'
implementation 'com.huawei.hms:health:5.0.3.300'
10) Enter the dependencies for saving data in Room database.
Code:
def room_version = "2.2.5"
implementation "androidx.room:room-runtime:$room_version"
annotationProcessor "androidx.room:room-compiler:$room_version"
implementation 'androidx.recyclerview:recyclerview:1.1.0'
11) Add the app ID generated when the creating the app on HUAWEI Developers to manifest file.
Code:
<meta-data
android:name="com.huawei.hms.client.appid"
android:value="Your app id"/>
12) Add the below permissions to manifest file.
Code:
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" />
<uses-permission android:name="android.permission.BODY_SENSORS" />
13) Sync the gradle. Now configuration part completed.
Let us start with the coding part which will explain how to sign in with Huawei id, get authorization access for Health Kit and generate real time step data.
Step 1: Initialize the health service.
Inside activity onCreate() method, call initService().
Code:
private void initService() {
mContext = this;
HiHealthOptions fitnessOptions = HiHealthOptions.builder().build();
AuthHuaweiId signInHuaweiId = HuaweiIdAuthManager.getExtendedAuthResult(fitnessOptions);
mSettingController = HuaweiHiHealth.getSettingController(mContext, signInHuaweiId);
}
Step 2: Huawei Id SignIn and Apply for permissions.
Code:
/**
* Sign-in and authorization method. The authorization screen will display if the current account has not granted authorization.
*/
private void signIn() {
Log.i(TAG, "begin sign in");
List<Scope> scopeList = new ArrayList<>();
// Add scopes to apply for. The following only shows an example. You need to add scopes according to your specific needs.
scopeList.add(new Scope(Scopes.HEALTHKIT_STEP_BOTH)); // View and save step counts in HUAWEI Health Kit.
scopeList.add(new Scope(Scopes.HEALTHKIT_HEIGHTWEIGHT_BOTH)); // View and save height and weight in HUAWEI Health Kit.
scopeList.add(new Scope(Scopes.HEALTHKIT_HEARTRATE_BOTH)); // View and save the heart rate data in HUAWEI Health Kit.
// Configure authorization parameters.
HuaweiIdAuthParamsHelper authParamsHelper = new HuaweiIdAuthParamsHelper(
HuaweiIdAuthParams.DEFAULT_AUTH_REQUEST_PARAM);
HuaweiIdAuthParams authParams = authParamsHelper.setIdToken()
.setAccessToken()
.setScopeList(scopeList)
.createParams();
// Initialize the HuaweiIdAuthService object.
final HuaweiIdAuthService authService = HuaweiIdAuthManager.getService(this.getApplicationContext(),
authParams);
// Silent sign-in. If authorization has been granted by the current account, the authorization screen will not display. This is an asynchronous method.
Task<AuthHuaweiId> authHuaweiIdTask = authService.silentSignIn();
// Add the callback for the call result.
authHuaweiIdTask.addOnSuccessListener(new OnSuccessListener<AuthHuaweiId>() {
@Override
public void onSuccess(AuthHuaweiId huaweiId) {
// The silent sign-in is successful.
Log.i(TAG, "silentSignIn success");
Toast.makeText(GetStartedActivity.this, "silentSignIn success", Toast.LENGTH_SHORT).show();
goToHomeScreen();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception exception) {
// The silent sign-in fails. This indicates that the authorization has not been granted by the current account.
if (exception instanceof ApiException) {
ApiException apiException = (ApiException) exception;
Log.i(TAG, "sign failed status:" + apiException.getStatusCode());
Log.i(TAG, "begin sign in by intent");
// Call the sign-in API using the getSignInIntent() method.
Intent signInIntent = authService.getSignInIntent();
// Display the authorization screen by using the startActivityForResult() method of the activity.
// You can change HihealthKitMainActivity to the actual activity.
GetStartedActivity.this.startActivityForResult(signInIntent, REQUEST_SIGN_IN_LOGIN);
}
}
});
}
More details, you can check https://forums.developer.huawei.com/forumPortal/en/topic/0203428726840520025

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!!

Categories

Resources