Beginner: Integration of Huawei HEM Kit in Android - Huawei Developers

Introduction
Huawei provides various services for developers to make ease of development and provides best user experience to end users. In this article, we will cover integration of Huawei Enterprise Manager (HEM) Kit in Android.
Huawei Enterprise Manager (HEM) is a mobile device management solution provided for you based on the powerful platform and hardware of Huawei. The device deployment service in HEM helps install a Device Policy Controller (DPC) app automatically on enterprise devices in batches.
{
"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"
}
Development Overview
You need to install Android studio IDE and I assume that you have prior knowledge about the Android and java.
Hardware Requirements
A computer (desktop or laptop) running Windows 10.
A Huawei phone (with the USB cable), which is used for debugging.
An enterprise-oriented Huawei phone that has not been activated (running EMUI 11.0 or later). The bring your own device (BYOD) mode is not supported
Software Requirements
Java JDK installation package.
Android studio IDE installed.
HMS Core (APK) 5.X or later.
Follows the steps.
1. Create Android Project.
Open Android Studio.
Click NEW Project, select a Project Templet.
Enter project and Package Name and click on Finish:
2. Register as Huawei developer and complete identity verification in Huawei developer’s website, refer to register a Huawei ID.
3. To generate SHA-256 certificate fingerprint. On right-upper corner of android project click Gradle, choose Project Name > app > Tasks > android, and then click signingReport, as follows.
or
Also we can generate SHA-256 using command prompt.
To generating SHA-256 certificate fingerprint use below command.
4. Create an App in AppGallery Connect.
5. Download the agconnect-services.json file from AGC, copy and paste in android Project under app directory, as follows.
6. Add the below maven URL in build.gradle(Project level) file under the repositories of buildscript, , for more information refer Add Configuration.
Code:
maven { url 'https://developer.huawei.com/repo/' }
7. Add the below plugin and dependencies in build.gradle(App level).
Code:
apply plugin 'com.huawei.agconnect'
implementation "com.huawei.hms:hemsdk:1.0.0.303"
implementation 'androidx.appcompat:appcompat:1.3.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
8. Open AndroidManifest file and add below permissions.
Code:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
9. Development Procedure.
1. Create a java class MainActivity.java inside your package.
MainActivity.java
Code:
package com.android.hemdemokit;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.huawei.hem.license.HemLicenseManager;
import com.huawei.hem.license.HemLicenseStatusListener;
public class MainActivity extends Activity {
private HemLicenseManager hemInstance;
private TextView resultCodeTV;
private TextView resultCodeDescTV;
private Button btnActive;
private Button btnDeActive;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
hemInstance = HemLicenseManager.getInstance(this);
setButtonClickListener();
setStatusListener();
}
private void setButtonClickListener() {
btnActive = findViewById(R.id.active_btn);
btnDeActive = findViewById(R.id.de_active_btn);
esultCodeTV = findViewById(R.id.result_code_tv);
resultCodeDescTV = findViewById(R.id.result_code_desc_tv);
btnActive.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
hemInstance.activeLicense();
}
});
btnDeActive.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
hemInstance.deActiveLicense();
}
});
}
private void setStatusListener() {
hemInstance.setStatusListener(new MyHemLicenseStatusListener());
}
private class MyHemLicenseStatusListener implements HemLicenseStatusListener {
@Override
public void onStatus(final int errorCode, final String msg) {
resultCodeTV.post(new Runnable() {
@Override
public void run() {
resultCodeTV.setText(String.valueOf(errorCode));
}
});
resultCodeDescTV.post(new Runnable() {
@Override
public void run() {
resultCodeDescTV.setText(msg);
}
});
}
}
}
2. Create activity_main.xml layout file under app > main > res > layout folder.
activity_main.xml
XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="14dp"
android:orientation="horizontal">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="return code:"
android:textSize="16dp" />
<TextView
android:id="@+id/result_code_tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="@null"
android:drawablePadding="10dp"
android:padding="10dp"
android:text="" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="14dp"
android:orientation="horizontal">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="result description:"
android:textSize="16dp" />
<TextView
android:id="@+id/result_code_desc_tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="@null"
android:drawablePadding="10dp"
android:padding="10dp"
android:text="" />
</LinearLayout>
<Button
android:id="@+id/active_btn"
android:text="call active"
android:layout_gravity="center"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/de_active_btn"
android:text="call de_active"
android:layout_gravity="center"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
10. To build apk and run in device, choose Build > Generate Signed Bundle/APK > Build for apk or Build and Run into connected device follow the steps.
Result
1. Install application into device and click on app icon you can see below result.
2. If the EMUI device is less than targeted device, then you will get below errors.
Tips and Tricks
Always use the latest version of the library.
Add agconnect-services.json file without fail.
Add SHA-256 fingerprint without fail.
Make sure dependenciesadded in build files.
Make sure you have EMUI 11.0 and later versions.
Conclusion
In this article, we have learnt integration of Huawei HEM sdk. Also we learnt how to activate and deactivate an MDM license. HEM kit enables you to flexibly adapt your app to a wide range of device deployment scenarios for enterprises, to implement auto-deployment when they enroll a bunch of devices out of the box. This, in turn, dramatically reduces the required manual workload.
References
HEM Kit: https://developer.huawei.com/consumer/en/hms/huawei-hemkit/
Original Source

Related

Create and Draw Huawei Map on XAMARIN!

Hi, as you know maps are used for different purposes in most apps. In this article, I would like to show you how to use Huawei map in Xamarin and make customizations on the map. First of all, we will follow what we need to do to add Hms Map kit to our project step by step.
Then we will focus on map customizations.
Of course, before that, we will talk about the problems you may encounter until you get to this step.
Integrating the HMS Map Kit Libraries to Xamarin Project
Let’s start. First of all, we need a Huawei developer account to use Huawei mobile services and configure our app with AppGallery Connect. Please follow the link for configuration.
How to configure app in AppGallery Connect
To use the HUAWEI Map Kit SDK for Xamarin, you need to create Xamarin Android bindings libraries from HMS Map Kit SDK for Android. After downloading the SDK files at the address below, we open a blank solution in visual studio and add these projects.
Map Kit SDK for Xamarin
{
"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"
}
Then please update the aar files in the projects.
Now we will add this solution to the our project as a reference where we will go and integrate the map kit.
We added our solution to our reference. Now we will be able to use related HMS classes in our project.
Manifest & Permissions
We have to update the application’s manifest file by declaring permissions. *Before starting this, please make sure the package name is correct since the project has been added to AppGallery Connect. Make sure that the Sha256 key is entered correctly for the respective build type and agconnect-services.json file is added to your project.
Code:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
AndroidManifest.xml
Also, we need to add a meta-data element to embed your app id in the application tag between <application> tag. It is required for this app to authenticate on the Huawei’s cloud server. You can find this id in agconnect-services.json file. If you don’t do that app couldn’t render the map.
Code:
<meta-data android:name="com.huawei.hms.client.appid" android:value="appid=YOUR_APPID"/>
Creating a Map
Currently, the HMS Core Map SDK supports two map containers: MapFragment and MapView.
MapFragment is a subclass of the Android Fragment class. You can use it to place a map within a fragment. It can also function as a map container and provide an entry for accessing a HuaweiMap object. In this article we will use a Map Fragment.
First off all please add following lines to your XML file to which one you want to show map.
Code:
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
android:id="@+id/mapfragment_mapfragmentdemo"
class="com.huawei.hms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
map:cameraTargetLat="41.019879"
map:cameraTargetLng="29.007822"
map:cameraZoom="12"
/>
In our activity’s OnCreate method, set the layout file as the content view, load AGConnectService. Get a handle to the map fragment by calling FragmentManager.FindFragmentById. Then use GetMapAsync to register for the map callback.
Also, implement the IOnMapReadyCallback interface to our Activity and override OnMapReady method which is triggered when the map is ready to use.
Code:
class NewActivty : AppCompatActivity, IOnMapReadyCallback
{
private MapView mMapView;
private HuaweiMap hMap;
private MapFragment mapFragment;
string[] permissions = {
Android.Manifest.Permission.AccessCoarseLocation,
Android.Manifest.Permission.AccessFineLocation,
Android.Manifest.Permission.Internet };
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
SetContentView(Resource.Layout.activity_main);
mapFragment = FragmentManager.FindFragmentById<MapFragment>(Resource.Id.mapfragment_mapfragmentdemo);
mapFragment.GetMapAsync(this);
ActivityCompat.RequestPermissions(this, permissions, 100);
}
public void OnMapReady(HuaweiMap huaweiMap)
{
this.hMap = huaweiMap;
}
}
After adding the preceding information to the Manifest file, you need to dynamically apply for the permissions in the code (according to risky permission requirements in Android 6.0).
Show current location
To enable this function, set the MyLocationEnabled (true) of the HuaweiMap object
Code:
public void OnMapReady(HuaweiMap huaweiMap)
{
this.hMap = huaweiMap;
hMap.UiSettings.MyLocationButtonEnabled = true;
hMap.MyLocationEnabled = true;
}
Adding a Marker and Customization
I used more than one marker in my own project and I marked them on the map by customizing them.
You can do this directly in a method where you import the hmap object, but I created this function and I wanted to use this method by giving the necessary parameters externally.
Code:
private void addMarker(LatLng position, String title, String description)
{
Marker marker;
MarkerOptions marker3Options = new MarkerOptions()
.InvokePosition(position)
.InvokeTitle(title)
.InvokeSnippet(description);
Bitmap bitmap1 = ResourceBitmapDescriptor.DrawableToBitmap(this, ContextCompat.GetDrawable(this, Resource.Drawable.markerblue));
marker3Options.InvokeIcon(BitmapDescriptorFactory.FromBitmap(bitmap1));
marker = hMap.AddMarker(marker3Options);
hMap.MarkerDragStart += OnMarkerDragStart;
hMap.MarkerDrag += OnMarkerDrag;
hMap.MarkerDragEnd += OnMarkerDragEnd;
}
Now let’s see how our additions look on the map
Custom Information Window
When the markers are clicked, we can display custom information messages to inform. let’s see how to do this. First, create a layout for custom info.
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:background="@color/colorPrimary"
android:orientation="horizontal">
<ImageView
android:id="@+id/customInfoImage"
android:layout_width="45dp"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:adjustViewBounds="true" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:layout_marginRight="10dp"
android:orientation="vertical">
<TextView
android:id="@+id/customInfoTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:singleLine="true"
android:textColor="@android:color/white"
android:textSize="14sp"
android:textStyle="bold" />
<TextView
android:id="@+id/customInfoDescription"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:ellipsize="end"
android:singleLine="false"
android:maxLines="2"
android:textColor="@android:color/white"
android:textSize="12sp" />
<RatingBar
android:id="@+id/customInfoRatingBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:numStars="5"
android:outlineAmbientShadowColor="@android:color/white"
android:layout_gravity="center_vertical"
/>
</LinearLayout>
</LinearLayout>
Then we add it to the class in which the click event of the marker is triggered.
Code:
hMap.SetInfoWindowAdapter(new CustomMapInfoWindow(this));
public void OnMarkerClick(object sender, HuaweiMap.MarkerClickEventArgs e)
{
Toast.MakeText(this, $"Marker Click Marker ID: {e.P0.Id}", ToastLength.Short).Show();
}
Now let’s see how it looks on map
Shape
With the HMS Core Map SDK, you can add different shapes to a map, including polylines, polygons, and circles. We can use these features for many purposes, such as creating a route between two points, expressing a specific region, or expressing the areas covered by certain regions. So the limit here is your imagination or coverage of your project.
Adding a Polyline
You can use the code block below to draw polyline. You can add as many points as you want for the route and you can give these points dynamically according to the setup of your project.
Code:
private void drawPolyline()
{
Polyline polyline;
PolylineOptions polylineOptions = new PolylineOptions()
.Add(new LatLng(41.03472222, 28.90027778), new LatLng(41.00166667, 28.97111111), new LatLng(41.00415, 29.012449), new LatLng(40.985996056, 29.035333192));
polylineOptions.InvokeColor(Color.Red);
polylineOptions.Clickable(true);
polyline = hMap.AddPolyline(polylineOptions);
}
Adding a Polygon
You can use the code block below to denote a specific region.
Code:
private void drawPolygone()
{
Polygon polygon;
PolygonOptions polygonOptions = new PolygonOptions()
.Add(new LatLng(41.01929, 28.967267), new LatLng(41.016785, 28.986971), new LatLng(41.014623, 28.999753), new LatLng(41.001917, 28.978743), new LatLng(41.002298, 28.954132));
polygonOptions.InvokeFillColor(Color.Argb(60, 255, 200, 0));
polygonOptions.InvokeStrokeColor(Color.Green);
polygonOptions.InvokeStrokeWidth(30);
polygonOptions.Clickable(true);
polygonOptions.InvokeZIndex(2);
polygon = hMap.AddPolygon(polygon1Options);
}
Adding a Circle
Whether a circle is solid or hollow can be controlled by amending the circle attributes. By default, a circle is solid. You can create your apartment by adding the code block below. You can customize many features such as scanning the inside of the circle thickness according to your purpose.
Code:
private void drawCircle()
{
Circle circle;
LatLng circleLatLng = new LatLng(40.985996056, 29.035333192);
CircleOptions circleOptions = new CircleOptions();
circle = hMap.AddCircle(circleOptions);
circleOptions.InvokeCenter(circleLatLng);
circleOptions.InvokeRadius(1800);
circleOptions.InvokeStrokeWidth(5);
circleOptions.InvokeStrokeColor(Color.Blue);
circleOptions.InvokeStrokeWidth(30);
circleOptions.Clickable(true);
circleOptions.InvokeZIndex(2);
circle = hMap.AddCircle(circleOptions);
circleOptions.Clickable(true);
hMap.CircleClick += OnCircleClick;
}
How it looks on map
Final
For any questions, please contact me. I hope this article helped you add Huawei map to your own project and learn how to use it.
Thanks for reading!
References:
Github Link
Docs

Android Deep Link Using Huawei App Gallery Ability

HMS App Linking Introduction
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
HMS App Linking allows you to create cross-platform links that can work as defined regardless of whether your app has been installed by a user. When a user taps the link on an Android or iOS device, the user will be redirected to the specified in-app content. If a user taps the link in a browser, the user will be redirected to the same content of the web version.
To identify the source of a user, you can set tracing parameters for various channels when creating a link of App Linking to trace traffic sources. By analyzing the link performance of each traffic source based on the tracing parameters, you can find the platform that can achieve better promotion effect for your app:
Deferred deep link: Directs a user who has not installed your app to AppGallery to download your app first and then navigate to the link in-app content directly, without requiring the user to tap the link again.
Link display in card form: Uses a social Meta tag to display a link of App Linking as a card, which will attract more users from social media.
Statistics: Records the data of all link-related events, such as numbers of link taps, first app launches, and non-first app launches for you to conduct analysis.
API Overview
1. (Mandatory) Call AppLinking.Builder to create a Builder object.
2. (Mandatory) Call AppLinking.Builder.setUriPrefix to set the URL prefix that has been applied for in Applying for a URL Prefix.
3. (Mandatory) Call AppLinking.Builder.setDeepLink to set a deep link.
4. Call AppLinking.Builder.setAndroidLinkInfo to set Android app parameters. In this method, Android app parameters are contained in an AppLinking.AndroidLinkInfo instance, which can be built by calling AppLinking.AndroidLinkInfo.Builder. If this method is not called, the link will be opened in the browser by default.
5. Call AppLinking.Builder.setIOSLinkInfo to set iOS app parameters. In this method, iOS app parameters are contained in an AppLinking.IOSLinkInfo instance, which can be built by calling AppLinking.IOSLinkInfo.Builder. If this method is not called, the link will be opened in the browser by default.
6. Call AppLinking.IOSLinkInfo.Builder.setITunesConnectCampaignInfo to set App Store Connect campaign parameters. In this method, App Store Connect campaign parameters are contained in an AppLinking.ITunesConnectCampaignInfo instance, which can be built by calling AppLinking.ITunesConnectCampaignInfo.Builder.
7. Call AppLinking.Builder.setPreviewType to set the link preview type. If this method is not called, the preview page with app information is displayed by default.
8. Call AppLinking.Builder.setSocialCardInfo to set social Meta tags. In this method, social Meta tags are contained in an AppLinking.SocialCardInfo instance, which can be built by calling AppLinking.SocialCardInfo.Builder. If this method is not called, links will not be displayed as cards during social sharing.
9. Call AppLinking.Builder.setCampaignInfo to set ad tracing parameters. In this method, campaign parameters are contained in an AppLinking.CampaignInfo instance, which can be built by calling AppLinking.CampaignInfo.Builder.
Key Concepts
URL prefix
The URL prefix is the domain name contained in a link, which is in https://Domain name format. You can use the domain name provided by AppGallery Connect for free.
Long link
A long link is a link of App Linking in its entirety. follows this format:
URL prefix+Deep link+Android app parameters+iOS app parameters+[Preview type]+[Social meta tag]+[Tracing parameters]+[Landing page display parameter]+[Site ID].
An example of a long link is as follows:
https://yourapp.drcn.agconnect.link/?deeplink=https%3A%2F%2Fyourdeeplink.com&android_deeplink=https%3A%2F%2Fyourdeeplink.com&android_open_type=1&android_package_name=tiantian.huawei&campaign_channel=huawei&campaign_medium=pic&campaign_name=%E4%BF%83%E9%94%80&ios_link=https%3A%2F%2Fyourdeeplink.com&ios_bundle_id=aapp.huawei&at=1234&pt=212&ct=1234&mt=1&preview_type=2&social_title=%E6%8E%A5%E5%85%A5%E4%BF%83%E9%94%80&landing_page_type=1&&region_id=0
Short link
If a long link is too long, it can be converted to a short link. A short link follows this format:
URL prefix+Random suffix of the string type
Prerequisite
Huawei Phone
Android Studio
AppGallery Account
App Development
Create a New Project.
Configure Project Gradle.
Code:
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
jcenter()
//TODO
maven { url 'https://developer.huawei.com/repo/' }
}
dependencies {
classpath 'com.android.tools.build:gradle:3.5.3'
//TODO
classpath 'com.huawei.agconnect:agcp:1.4.2.301'
}
}
allprojects {
repositories {
google()
jcenter()
//TODO
maven { url 'https://developer.huawei.com/repo/' }
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
3. Configure App Gradle.
Code:
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'androidx.cardview:cardview:1.0.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
//TODO
implementation 'com.huawei.agconnect:agconnect-applinking:1.4.2.301'
implementation 'com.huawei.hms:hianalytics:5.0.5.301'
4. Configure AndroidManifest.
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.hms.applinkandroid">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".applinking.DetailActivity"
android:configChanges="orientation|keyboardHidden|screenSize" />
<activity
android:name=".applinking.SettingActivity"
android:configChanges="orientation|keyboardHidden|screenSize" />
</application>
</manifest>
5. Create Activity class with XML UI.
MainActivity.java:
This activity performs all the operation of AppLinking with short and long url with Share card.
Code:
package com.hms.applinkandroid;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import com.hms.applinkandroid.applinking.DetailActivity;
import com.hms.applinkandroid.applinking.SettingActivity;
import com.huawei.agconnect.applinking.AGConnectAppLinking;
import com.huawei.agconnect.applinking.AppLinking;
import com.huawei.agconnect.applinking.ShortAppLinking;
public class MainActivity extends AppCompatActivity {
private static final String DOMAIN_URI_PREFIX = "https://applinkingtest.drcn.agconnect.link";
private static final String DEEP_LINK = "https://developer.huawei.com/consumer/cn/doc/development/AppGallery-connect-Guides";
private TextView shortTextView;
private TextView longTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
shortTextView = findViewById(R.id.shortLinkText);
longTextView = findViewById(R.id.longLinkText);
findViewById(R.id.create)
.setOnClickListener(
view -> {
createAppLinking();
});
findViewById(R.id.shareShort)
.setOnClickListener(
view -> {
shareLink((String) shortTextView.getText());
});
findViewById(R.id.shareLong)
.setOnClickListener(
view -> {
shareLink((String) longTextView.getText());
});
AGConnectAppLinking.getInstance()
.getAppLinking(this)
.addOnSuccessListener(
resolvedLinkData -> {
Uri deepLink = null;
if (resolvedLinkData != null) {
deepLink = resolvedLinkData.getDeepLink();
}
TextView textView = findViewById(R.id.deepLink);
textView.setText(deepLink != null ? deepLink.toString() : "");
if (deepLink != null) {
String path = deepLink.getLastPathSegment();
if ("detail".equals(path)) {
Intent intent = new Intent(getBaseContext(), DetailActivity.class);
for (String name : deepLink.getQueryParameterNames()) {
intent.putExtra(name, deepLink.getQueryParameter(name));
}
startActivity(intent);
}
if ("setting".equals(path)) {
Intent intent = new Intent(getBaseContext(), SettingActivity.class);
for (String name : deepLink.getQueryParameterNames()) {
intent.putExtra(name, deepLink.getQueryParameter(name));
}
startActivity(intent);
}
}
})
.addOnFailureListener(
e -> {
Log.w("MainActivity", "getAppLinking:onFailure", e);
});
}
private void createAppLinking() {
AppLinking.Builder builder = new AppLinking.Builder()
.setUriPrefix(DOMAIN_URI_PREFIX)
.setDeepLink(Uri.parse(DEEP_LINK))
.setAndroidLinkInfo(new AppLinking.AndroidLinkInfo.Builder().build())
.setSocialCardInfo(new AppLinking.SocialCardInfo.Builder()
.setTitle("华为开发者大会")
.setImageUrl("https://developer.huawei.com/consumer/cn/events/hdc2020/img/kv-pc-cn.png?v0808")
.setDescription("Description").build())
.setCampaignInfo(new AppLinking.CampaignInfo.Builder()
.setName("HDC")
.setSource("AGC")
.setMedium("App").build());
longTextView.setText(builder.buildAppLinking().getUri().toString());
builder.buildShortAppLinking().addOnSuccessListener(shortAppLinking -> {
shortTextView.setText(shortAppLinking.getShortUrl().toString());
}).addOnFailureListener(e -> {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
});
}
private void shareLink(String appLinking) {
if (appLinking != null) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, appLinking);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
private void showError(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
main_activity.xml:
Code:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/ic_bg"
android:gravity="center"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/TitleView"
android:layout_width="281dp"
android:layout_height="51dp"
android:text="Android Deep Link"
android:textColor="@android:color/white"
android:textSize="30dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.061" />
<androidx.cardview.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="@+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
card_view:cardElevation="5dp"
card_view:cardUseCompatPadding="true"
card_view:contentPadding="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="@+id/textView5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Deeplink"
android:textColor="@android:color/black"
android:textSize="18sp"
android:textStyle="bold" />
<TextView
android:id="@+id/deepLink"
android:layout_width="match_parent"
android:layout_height="59dp"
android:textColor="@android:color/black"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.241" />
<Button
android:id="@+id/create"
android:layout_width="230dp"
android:layout_height="50dp"
android:text="Create App Linking"
android:textAllCaps="false"
android:textSize="19sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.324" />
</LinearLayout>
</androidx.cardview.widget.CardView>
<androidx.cardview.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
card_view:cardElevation="5dp"
card_view:cardUseCompatPadding="true"
card_view:contentPadding="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="@+id/textView3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="Long App Linking:"
android:textColor="@android:color/black"
android:textSize="18sp"
android:textStyle="bold" />
<TextView
android:id="@+id/longLinkText"
android:layout_width="match_parent"
android:layout_height="80dp"
android:gravity="center_horizontal" />
<Button
android:id="@+id/shareLong"
android:layout_width="230dp"
android:layout_height="50dp"
android:text="Share long App Linking"
android:textAllCaps="false"
android:textSize="19sp" />
</LinearLayout>
</androidx.cardview.widget.CardView>
<androidx.cardview.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
card_view:cardElevation="5dp"
card_view:cardUseCompatPadding="true"
card_view:contentPadding="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="Short App Linking:"
android:textColor="@android:color/black"
android:textSize="18sp"
android:textStyle="bold" />
<TextView
android:id="@+id/shortLinkText"
android:layout_width="match_parent"
android:layout_height="60dp"
android:gravity="center_horizontal" />
<Button
android:id="@+id/shareShort"
android:layout_width="230dp"
android:layout_height="50dp"
android:text="Share short App Linking"
android:textAllCaps="false"
android:textSize="19sp" />
</LinearLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
</ScrollView>
App Gallery Integration process
Sign In and Create or Choose a project on AppGallery Connect portal.
Navigate to Project settings and download the configuration file.
Navigate to General Information, and then provide Data Storage location.
Navigate to Manage APIs and enable APIs which is required by application.
Navigate to AppLinking and Enable.
Add New link.
Navigate to App Linking and select Set domain name.
Copy Domain Name and add in your project.
App Build Result
Tips and Tricks
Since HUAWEI Analytics Kit 4.0.3.300, the SDK for Android has been significantly improved in the stability, security, and reliability. If the SDK you have integrated is earlier than 4.0.3.300, please upgrade it to 4.0.3.300 or later before April 30, 2021. From May 1, 2021, HUAWEI Analytics will not receive data reported by SDK versions earlier than 4.0.3.300. If you have integrated App Linking, you also need to upgrade its SDK to 1.4.1.300 or later for Android before April 30, 2021. Otherwise, functions that depend on HUAWEI Analytics will become unavailable.
Huawei strictly conforms to the General Data Protection Regulation (GDPR) in providing services and is dedicated to helping developers achieve business success under the principles of the GDPR. The GDPR stipulates the obligations of the data controller and data processor. When using our service, you act as the data controller, and Huawei is the data processor. Huawei solely processes data within the scope of the data processor's obligations and rights, and you must assume all obligations of the data controller as specified by the GDPR.
Conclusion
In this article, we have learned how to integrate AppLinking in application. In this application, I have explained that how to deep link our application with URL.
Thanks for reading this article. Be sure to like and comments to this article, if you found it helpful. It means a lot to me.
References
HMS AppLinking Doc: Link
Original Source

Integration of Huawei Account Kit in Book Reading Android app (Kotlin) - Part 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"
}
Introduction
In this article, we can learn how to integrate the Huawei Account Kit in Book Reading app. So, I will provide the series of articles on this Book Reading App, in upcoming articles I will integrate other Huawei Kits.
Account Kit
Huawei Account Kit provides for developers with simple, secure, and quick sign-in and authorization functions. User is not required to enter accounts, passwords and waiting for authorization. User can click on Sign In with HUAWEI ID button to quickly and securely sign in to the app.
Requirements
1. Any operating system (MacOS, Linux and Windows).
2. Must have a Huawei phone with HMS 4.0.0.300 or later.
3. Must have a laptop or desktop with Android Studio, Jdk 1.8, SDK platform 26 and Gradle 4.6 and above installed.
4. Minimum API Level 24 is required.
5. Required EMUI 9.0.0 and later version devices.
How to integrate HMS Dependencies
1. First register as Huawei developer and complete identity verification in Huawei developers website, refer to register a Huawei ID.
2. Create a project in android studio, refer Creating an Android Studio Project.
3. Generate a SHA-256 certificate fingerprint.
4. To generate SHA-256 certificate fingerprint. On right-upper corner of android project click Gradle, choose Project Name > Tasks > android, and then click signingReport, as follows.
Note: Project Name depends on the user created name.
5. Create an App in AppGallery Connect.
6. Download the agconnect-services.json file from App information, copy and paste in android Project under app directory, as follows.
7. Enter SHA-256 certificate fingerprint and click Save button, as follows.
Note: Above steps from Step 1 to 7 is common for all Huawei Kits.
8. Click Manage APIs tab and enable Account Kit.
9. Add the below maven URL in build.gradle(Project) file under the repositories of buildscript, dependencies and allprojects, refer Add Configuration.
Java:
maven { url 'http://developer.huawei.com/repo/' }
classpath 'com.huawei.agconnect:agcp:1.6.0.300'
[/CODE]
10. Add the below plugin and dependencies in build.gradle(Module) file.
Java:
apply plugin: id 'com.huawei.agconnect'
// Huawei AGC
implementation 'com.huawei.agconnect:agconnect-core:1.6.0.300'
// Huawei Account Kit
implementation 'com.huawei.hms:hwid:6.3.0.301'
implementation 'androidx.recyclerview:recyclerview:1.2.1'
[/CODE]
11. Now Sync the gradle.
12. Add the required permission to the AndroidManifest.xml file.
XML:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
Let us move to development
I have created a project on Android studio with empty activity let us start coding.
In the MainActivity.kt we can find the business logic.
Java:
class MainActivity : AppCompatActivity() {
private var mAuthManager: AccountAuthService? = null
private var mAuthParam: AccountAuthParams? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
sign_btn.setOnClickListener(mOnClickListener)
}
private fun signIn() {
mAuthParam = AccountAuthParamsHelper(AccountAuthParams.DEFAULT_AUTH_REQUEST_PARAM)
.setIdToken()
.setAccessToken()
.setProfile()
.createParams()
mAuthManager = AccountAuthManager.getService([email protected], mAuthParam)
startActivityForResult(mAuthManager?.signInIntent, 1002)
}
private val mOnClickListener: View.OnClickListener = object : View.OnClickListener {
override fun onClick(v: View?) {
when (v?.id) {
R.id.sign_btn -> signIn()
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 1002 ) {
val authAccountTask = AccountAuthManager.parseAuthResultFromIntent(data)
if (authAccountTask.isSuccessful) {
Toast.makeText(this, "SigIn success", Toast.LENGTH_LONG).show()
val intent = Intent([email protected], Home::class.java)
startActivity(intent)
} else {
Toast.makeText(this, "SignIn failed: " + (authAccountTask.exception as ApiException).statusCode, Toast.LENGTH_LONG).show()
}
}
}
}
In the Home.kt we can find the business logic.
Java:
class Home : AppCompatActivity() {
lateinit var recyclerView: RecyclerView
var mBookAdapter: BookAdapter? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_home)
recyclerView = findViewById(R.id.recycler_view)
mBookAdapter = BookAdapter()
recyclerView.adapter = mBookAdapter
}
}
Create BookAdapter.kt class for holding the list.
Java:
class BookAdapter(): RecyclerView.Adapter<BookAdapter.ViewHolder>() {
private var titles = arrayOf("Life", "Young Adult", "Comedy", "Women", "Tragedy", "Science Fiction",
"Horror Stories", "Drama", "Society", "Biography")
private var images = intArrayOf(R.drawable.life, R.drawable.youth, R.drawable.comedy, R.drawable.women,
R.drawable.tragedy, R.drawable.science, R.drawable.horror, R.drawable.drama,
R.drawable.society, R.drawable.biography)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BookAdapter.ViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.list_item, parent, false)
return BookAdapter.ViewHolder(view)
}
override fun onBindViewHolder(holder: BookAdapter.ViewHolder, position: Int) {
holder.itemTitle.text = titles[position]
holder.itemImage.setImageResource(images[position])
}
override fun getItemCount(): Int {
return titles.size
}
class ViewHolder(ItemView: View) : RecyclerView.ViewHolder(ItemView) {
var itemTitle: TextView = itemView.findViewById(R.id.titles)
var itemImage: ImageView = itemView.findViewById(R.id.images)
}
}
In the activity_main.xml we can create the UI screen.
Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@drawable/book_fly"
tools:context=".MainActivity">
<TextView
android:id="@+id/act_main_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:layout_marginLeft="20dp"
android:layout_marginTop="30dp"
android:text="Huawei E-Book Store"
android:textSize="32sp"
android:textColor="@color/hwid_auth_button_color_red"
android:textStyle="bold" />
<ImageButton
android:id="@+id/sign_btn"
android:layout_width="290dp"
android:layout_height="60dp"
android:layout_alignParentBottom="true"
android:layout_centerInParent="true"
android:layout_margin="15dp"
android:paddingTop="10dp"
app:srcCompat="@drawable/huawei_id_buttons" />
</RelativeLayout>
In the activity_home.xml we can create the UI screen.
Java:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:orientation="vertical"
android:paddingLeft="8dp"
android:paddingRight="8dp"
tools:context=".Home">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
android:layout_height="match_parent" />
</LinearLayout>
In the list_item.xml we can create the list of items.
Java:
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/list_view"
android:layout_marginLeft="-3dp"
android:layout_marginRight="0dp"
android:layout_marginBottom="5dp"
app:cardBackgroundColor="@color/hwid_auth_button_color_border"
app:cardCornerRadius="8dp"
app:cardElevation="3dp"
app:contentPadding="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="5dp">
<TextView
android:id="@+id/titles"
android:layout_width="160dp"
android:layout_height="50dp"
android:layout_marginStart="10dp"
android:layout_marginLeft="15dp"
android:text="Item"
android:textSize="20sp"
android:textAlignment="viewStart"
android:textColor="@color/black"
android:textStyle="bold" />
<ImageView
android:id="@+id/images"
android:layout_width="150dp"
android:layout_height="60dp"
android:layout_gravity="right"
android:layout_marginLeft="55dp" />
</LinearLayout>
</androidx.cardview.widget.CardView>
Demo
Tips and Tricks
1. Make sure you are already registered as Huawei developer.
2. Set minSDK version to 24 or later, otherwise you will get AndriodManifest merge issue.
3. Make sure you have added the agconnect-services.json file to app folder.
4. Make sure you have added SHA-256 fingerprint without fail.
5. Make sure all the dependencies are added properly.
Conclusion
In this article, we have learned how to integrate the Huawei Account Kit in Book Reading app. So, I will provide the series of articles on this Book Reading App, in upcoming articles will integrate other Huawei Kits.
I hope you have read this article. If you found it is helpful, please provide likes and comments.
Reference
Account Kit

Beginner: Find Nearby ATMS with integration of Huawei Site Kit in Banking app (Kotlin)

{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Introduction
In this article, I will be integrating Huawei Site Kit in an Application.
Site Kit
This kit is used for getting the places and near-by places on keyword search. HUAWEI Site Kit provide users with convenient and secure access to diverse, place-related services.
Use Case
The Site Kit will be used to find nearby ATMs in a Banking Application which can perform basic functions such as Enter Pin, Withdraw Money, Deposit Money and Check Balance.
Requirements
1. Any operating system (MacOS, Linux and Windows).
2. Must have a Huawei phone with HMS 4.0.2.300 or later.
3. Must have a laptop or desktop with Android Studio, Jdk 1.8, SDK platform 26 and Gradle 4.6 installed.
4. Minimum API Level 21 is required.
5. Required EMUI 9.0.0 and later version devices.
Integrate HMS Dependencies
1. First register as Huawei developer and complete identity verification in Huawei developers website, refer to register a Huawei ID.
2. Create a project in android studio, refer Creating an Android Studio Project.
3. Generate a SHA-256 certificate fingerprint.
4. To generate SHA-256 certificate fingerprint. Choose View > Tool Windows > Gradle > Signingreport > SHA256 code.
Or use cmd as explained in SHA256 CODE
5. Create an App in AppGallery Connect.
6. Download the agconnect-services.json file from App information, copy and paste in android Project under app directory, as follows.
7. Enter SHA-256 certificate fingerprint and click Save, as follows.
8. Click Manage APIs tab and enable Site Kit.
9. Add the below maven URL in build.gradle(Project) file under the repositories of buildscript, dependencies and allprojects, refer Add Configuration.
Code:
maven { url 'http://developer.huawei.com/repo/' }
classpath 'com.huawei.agconnect:agcp:1.6.0.300'
10. Add the below plugin and dependencies in build.gradle(Module) file.
Code:
apply plugin: 'com.huawei.agconnect'
// Huawei AGC
Code:
implementation 'com.huawei.agconnect:agconnect-core:1.6.0.300'
// Site Kit
Code:
implementation 'com.huawei.hms:site:5.2.0.300'
11. Now Sync the gradle.
12. Add the required permission to the Manifestfile.xml file.
Code:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!--check wifi state-->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
Development
activity_main.xml
XML:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:context=".MainActivity"
android:id="@+id/activity_main"
android:background="@color/purple_200">
<Button
android:id="@+id/btTrans"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="90dp"
android:layout_marginTop="100dp"
android:text="@string/click_to_start_transaction"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
tools:layout_editor_absoluteY="327dp" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="70dp"
android:layout_marginTop="10dp"
android:text="@string/welcome_to_world_s_best_bank"
android:textSize="20dp" />
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:srcCompat="@drawable/hello" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="570dp"
android:layout_marginStart="120dp"
android:text="@string/find_atm"
android:textSize="18sp"
android:textStyle="bold"
android:visibility="visible" />
<EditText
android:id="@+id/search_query"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAlignment="center"
android:hint="@string/search_atm_here"
android:inputType="text"
android:padding="5dp"
android:layout_marginTop="530dp"/>
<Button
android:id="@+id/button_text_search"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="220dp"
android:layout_marginStart="60dp"
android:text="@string/search"
android:textAllCaps="false" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#D3D3D3"
android:gravity="center_vertical"
android:padding="5dp"
android:text="@string/result"
android:textSize="16sp"
android:layout_marginTop="600dp"/>
<TextView
android:id="@+id/response"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textIsSelectable="true"
android:layout_marginTop="640dp"
/>
</FrameLayout>
MainActivity.kt
Code:
class MainActivity : AppCompatActivity() {
private var searchService: SearchService? = null
private var resultTextView: TextView? = null
private var queryInput: EditText? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
try {
searchService = SearchServiceFactory.create(
this,
URLEncoder.encode(
"CgB6e3x9Z0Sl/zgHigt2p775VippBazEDe6ujGs/R7iLuwd4Sum+m6aBgecx+gWQtkuVJu/BOp1UeLktd9cyuf66",
"utf-8"
)
)
} catch (e: UnsupportedEncodingException) {
Log.e("MainActivity", "encode apikey error")
}
queryInput = findViewById(R.id.search_query)
resultTextView = findViewById(R.id.response)
}
fun search(view: View?) {
val textSearchRequest = TextSearchRequest()
textSearchRequest.setQuery(queryInput!!.text.toString())
textSearchRequest.setHwPoiType(HwLocationType.TOWER)
searchService.textSearch(
textSearchRequest,
object : SearchResultListener<TextSearchResponse?>() {
fun onSearchResult(textSearchResponse: TextSearchResponse?) {
val response = StringBuilder("\n")
response.append("success\n")
var count = 1
var addressDetail: AddressDetail
if (null != textSearchResponse) {
if (null != textSearchResponse.getSites()) {
for (site in textSearchResponse.getSites()) {
addressDetail = site.getAddress()
response
.append(
String.format(
"[%s] name: %s, formatAddress: %s, country: %s, countryCode: %s \r\n",
"" + count++, site.getName(), site.getFormatAddress(),
if (addressDetail == null) "" else addressDetail.getCountry(),
if (addressDetail == null) "" else addressDetail.getCountryCode()
)
)
}
} else {
response.append("textSearchResponse.getSites() is null!")
}
} else {
response.append("textSearchResponse is null!")
}
Log.d("MainActivity", "search result is : $response")
resultTextView!!.text = response.toString()
}
fun onSearchError(searchStatus: SearchStatus) {
Log.e("MainActivity", "onSearchError is: " + searchStatus.getErrorCode())
}
})
}
}
Cloud Debugging
Use Cloud Debugging in HMS Toolkit to debug the app on a real device.
To use Cloud Debugging, you need to sign in using a HUAWEI ID, complete identity verification, and then authorize the sign-in.
Choose HMS > CloudDebugging.
You can use Available Devices. Select a device and click RUN.
Result
Tips and Tricks
1. Set minSDK version to 24 or later, otherwise you will get AndriodManifest merge issue.
2. Make sure you have added the agconnect-services.json file to app folder.
3. Make sure you have added SHA-256 fingerprint without fail.
4. Make sure all the dependencies are added properly.
Conclusion
In this article, we have learnt integration of Site Kit in Banking application. It will guide you to show nearby ATM based on the user input.
Reference
Site Kit: Documentation

Integration of Huawei Account Kit in Attendance Tracker Android app (Kotlin) - Part 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"
}
Introduction
In this article, we can learn how to integrate the Huawei Account Kit of Obtaining Icon Resources feature in Attendance Tracker app. So, I will provide the series of articles on this Attendance Tracker App, in upcoming articles I will integrate other Huawei Kits.
Account Kit
Huawei Account Kit provides for developers with simple, secure, and quick sign-in and authorization functions. User is not required to enter accounts, passwords and waiting for authorization. User can click on Sign In with HUAWEI ID button to quickly and securely sign in to the app.
Requirements
1. Any operating system (MacOS, Linux and Windows).
2. Must have a Huawei phone with HMS 4.0.0.300 or later.
3. Must have a laptop or desktop with Android Studio, Jdk 1.8, SDK platform 26 and Gradle 4.6 and above installed.
4. Minimum API Level 24 is required.
5. Required EMUI 9.0.0 and later version devices.
How to integrate HMS Dependencies
1. First register as Huawei developer and complete identity verification in Huawei developers website, refer to register a Huawei ID.
2. Create a project in android studio, refer Creating an Android Studio Project.
3. Generate a SHA-256 certificate fingerprint.
4. To generate SHA-256 certificate fingerprint. On right-upper corner of android project click Gradle, choose Project Name > Tasks > android, and then click signingReport, as follows.
Note: Project Name depends on the user created name.
5. Create an App in AppGallery Connect.
6. Download the agconnect-services.json file from App information, copy and paste in android Project under app directory, as follows.
7. Enter SHA-256 certificate fingerprint and click Save button, as follows.
Note: Above steps from Step 1 to 7 is common for all Huawei Kits.
8. Click Manage APIs tab and enable Account Kit.
9. Add the below maven URL in build.gradle(Project) file under the repositories of buildscript, dependencies and allprojects, refer Add Configuration.
Code:
maven { url 'http://developer.huawei.com/repo/' }
classpath 'com.huawei.agconnect:agcp:1.6.0.300'
10. Add the below plugin and dependencies in build.gradle(Module) file.
Java:
apply plugin: id 'com.huawei.agconnect'
// Huawei AGC
implementation 'com.huawei.agconnect:agconnect-core:1.6.0.300'
// Huawei Account Kit
implementation 'com.huawei.hms:hwid:6.3.0.301'
11. Now Sync the gradle.
12. Add the required permission to the AndroidManifest.xml file.
XML:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
Let us move to development
I have created a project on Android studio with empty activity let us start coding.
In the MainActivity.kt we can find the business logic for login icon.
Java:
class MainActivity : AppCompatActivity() {
lateinit var mAuthManager: AccountAuthService
private var mAuthParam: AccountAuthParams? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
btn_click.setOnClickListener(mOnClickListener)
}
private fun findResources() {
mAuthParam = AccountAuthParamsHelper(AccountAuthParams.DEFAULT_AUTH_REQUEST_PARAM)
.setIdToken()
.setAccessToken()
.setProfile()
.createParams()
mAuthManager = AccountAuthManager.getService([email protected], mAuthParam)
startActivityForResult(mAuthManager?.signInIntent, 1002)
// Obtain Icon steps
val task : Task<AccountIcon> = mAuthManager.channel
task.addOnSuccessListener { accountIcon ->
// Obtain icon information
Toast.makeText(this, "Display Name: " + accountIcon.description, Toast.LENGTH_LONG).show()
// Log.i("TAG", "displayName:" + accountIcon.description)
}
task.addOnFailureListener { e ->
// The information fails to be obtained.
if (e is ApiException) {
Log.i("TAG", "getChannelfailed status:" + e.statusCode)
}
}
}
private val mOnClickListener: View.OnClickListener = object : View.OnClickListener {
override fun onClick(v: View?) {
when (v?.id) {
R.id.btn_click -> findResources()
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 1002 ) {
val authAccountTask = AccountAuthManager.parseAuthResultFromIntent(data)
if (authAccountTask.isSuccessful) {
Toast.makeText(this, "SigIn success", Toast.LENGTH_LONG).show()
val intent = Intent([email protected], Home::class.java)
startActivity(intent)
}
else {
Toast.makeText(this, "SignIn failed: " + (authAccountTask.exception as ApiException).statusCode, Toast.LENGTH_LONG).show()
}
}
}
}
In the activity_main.xml we can create the UI screen.
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/main_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"
android:text="Welcome back! Login"
android:textSize="28sp"
android:textColor="@color/design_default_color_primary"
android:textStyle="bold" />
<TextView
android:id="@+id/txt_username"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="40dp"
android:text=" Username"
android:textColor="@color/black"
android:textSize="16sp" />
<EditText
android:id="@+id/edt_main_name"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="5dp"
android:hint=" Enter your username"
android:drawableLeft="@drawable/ic_baseline_person"
android:drawablePadding="3dp"
android:drawableTint="@color/design_default_color_primary"
android:textSize="17sp" />
<TextView
android:id="@+id/txt_password"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"
android:text=" Password"
android:textColor="@color/black"
android:textSize="16sp" />
<EditText
android:id="@+id/main_password"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="5dp"
android:hint=" Enter your password"
android:drawableTint="@color/design_default_color_primary"
android:drawableLeft="@android:drawable/ic_lock_idle_lock"
android:textSize="17sp" />
<TextView
android:id="@+id/forgot_password"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:layout_marginEnd="35dp"
android:textAlignment="textEnd"
android:layout_marginTop="10dp"
android:textColor="@color/black"
android:text=" Forgot password?"
android:textSize="16sp" />
<Button
android:id="@+id/click_login"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="30dp"
android:padding="5dp"
android:textColor="@color/black"
android:text="LOGIN" />
<TextView
android:id="@+id/txt_signin"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="40dp"
android:textAlignment="center"
android:layout_marginBottom="10dp"
android:text=" Or SigIn Using"
android:textColor="@color/black"
android:drawablePadding="3dp"
android:textSize="17sp" />
<ImageView
android:id="@+id/btn_click"
android:layout_width="50dp"
android:layout_height="60dp"
android:layout_gravity="center_horizontal"
app:srcCompat="@drawable/hwid_auth_button_normal" />
</LinearLayout>
Find the ic_baseline_person.xml for UI design.
Code:
Find the ic_baseline_person.xml for UI design.
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24"
android:tint="?attr/colorControlNormal">
<path
android:fillColor="@android:color/white"
android:pathData="M12,12c2.21,0 4,-1.79 4,-4s-1.79,-4 -4,-4 -4,1.79 -4,4 1.79,4 4,4zM12,14c-2.67,0 -8,1.34 -8,4v2h16v-2c0,-2.66 -5.33,-4 -8,-4z"/>
</vector>
Demo
Tips and Tricks
1. Make sure you are already registered as Huawei developer.
2. Set minSDK version to 24 or later, otherwise you will get AndriodManifest merge issue.
3. Make sure you have added the agconnect-services.json file to app folder.
4. Make sure you have added SHA-256 fingerprint without fail.
5. Make sure all the dependencies are added properly.
Conclusion
In this article, we have learned how to integrate the Huawei Account Kit of Obtaining Icon Resources feature in Attendance Tracker app. So, I will provide the series of articles on this Attendance Tracker App, in upcoming articles will integrate other Huawei Kits.
I hope you have read this article. If you found it is helpful, please provide likes and comments.
Reference
Account Kit – Documentation
Account Kit – Training Video

Categories

Resources