Introduction
In this article, we can learn the integration of user address in apps by Huawei Identity Kit. The Identity Kit provides an easy interface to add or edit or delete user details and enables the users to grant permission for apps to access their addresses through a single click on the screen.
This kit is mainly used in e-commerce, food delivery and logistics apps to deliver the products in an easy and safe way to users.
Services
Address Management: Users can enter and edit address information.
Address Access: Increases productivity by allowing user to access address information with the required permission from users.
Address Selection: Users can select addresses quickly and reliably.
Advantages
Easy access: Only one interface to integrate address selection service.
Extensive coverage: More than 170 countries and regions are covered.
Privacy protection: Strict compliance with European General Data Protection Regulation (GDPR) regulations and compliant use of address data.
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 installed.
4. Minimum API Level 21 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.
{
"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"
}
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 tick icon, as follows.
Note: Above steps from Step 1 to 7 is common for all Huawei Kits.
8. 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.4.1.300'
9. Add the below plugin and dependencies in build.gradle(Module) file.
Code:
apply plugin: 'com.huawei.agconnect'
// Huawei AGC
implementation 'com.huawei.agconnect:agconnect-core:1.5.0.300'
// Identity Kit.
implementation 'com.huawei.hms:identity:4.0.4.300'
10. Now Sync the gradle.
11. Add the required permission to the AndroidManifest.xml file.
Code:
<uses-permission android:name="android.permission.INTERNET"/>
Let us move to development
I have created a project on Android studio with empty activity let's start coding.
In the MainActivity.kt we can create the business logic.
Code:
class MainActivity : AppCompatActivity() {
private val GET_ADDRESS = 1000
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
query_user_address.setOnClickListener {
if(isNetworkAvailable([email protected])){
getUserAddress()
}
else {
Toast.makeText(this, "Please check your internet connection...", Toast.LENGTH_SHORT).show()
}
}
}
// To parse user address selection, returning the selected user address and displaying the selected user address in text view.
@SuppressLint("SetTextI18n")
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
Toast.makeText(this, "onActivityResult requestCode $requestCode resultCode $resultCode", Toast.LENGTH_SHORT).show()
when (requestCode) {
GET_ADDRESS -> when(resultCode) {
RESULT_OK -> {
val userAddress = UserAddress.parseIntent(data)
if(userAddress != null){
val sb = StringBuilder()
sb.apply {
append("name: ${userAddress.name} ,")
append("city: ${userAddress.administrativeArea} ,")
append("area: ${userAddress.locality} ,")
append("address: ${userAddress.addressLine1} ${userAddress.addressLine2} ,")
append("phone: ${userAddress.phoneNumber} ,")
}
Toast.makeText(this, "user address is $sb", Toast.LENGTH_SHORT).show()
user_address.text = sb.toString()
}else {
user_address.text = "Failed to get user address."
}
}
RESULT_CANCELED -> {
}
else -> Toast.makeText(this, "Result is wrong, result code is $resultCode", Toast.LENGTH_SHORT).show()
}
else -> {
}
}
}
// To query the user addresses and open the user address selection page.
private fun getUserAddress() {
val req = UserAddressRequest()
val task = com.huawei.hms.identity.Address.getAddressClient(this).getUserAddress(req)
task.addOnSuccessListener { result ->
Toast.makeText(this, "onSuccess result code: ${result.returnCode}", Toast.LENGTH_SHORT).show()
try{
startActivityForResult(result)
}
catch (e: IntentSender.SendIntentException){
e.printStackTrace()
}
}.addOnFailureListener { e ->
Toast.makeText(this, "on Failed result code: ${e.message}", Toast.LENGTH_SHORT).show()
}
}
private fun startActivityForResult(result: GetUserAddressResult){
val status = result.status
if(result.returnCode == 0 && status.hasResolution()){
Toast.makeText(this, "The result had resolution", Toast.LENGTH_SHORT).show()
status.startResolutionForResult(this, GET_ADDRESS)
}
else {
Toast.makeText(this, "the response is wrong, the return code is ${result.returnCode}", Toast.LENGTH_SHORT).show()
}
}
fun isNetworkAvailable(context: Context?): Boolean {
if(context != null){
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val aNetworkInfo = connectivityManager.activeNetworkInfo
aNetworkInfo?.let{
return aNetworkInfo.isAvailable
}
}
return false
}
}
In the activity_main.xml we can create the UI screen.
Code:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:padding="10dp"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:ignore="MissingConstraints"
android:orientation="vertical">
<TextView
android:id="@+id/user_address"
android:layout_width="match_parent"
android:layout_height="35dp"
android:hint="show shipping address"
android:textAllCaps="false"
android:textSize="15sp"
android:text="Show User Address"/>
<Button
android:id="@+id/query_user_address"
android:layout_width="match_parent"
android:layout_marginTop="10sp"
android:layout_height="wrap_content"
android:textAllCaps="false"
android:textSize="15sp"
android:text="Get Huawei User Address"/>
<TextView
android:id="@+id/demo_introduce"
android:layout_width="match_parent"
android:textSize="15sp"
android:layout_height="320dp"
android:layout_marginLeft="0dp"
android:layout_marginTop="50dp"
android:layout_marginRight="0dp"
android:layout_marginBottom="0dp"
android:text="@string/demo_introduction" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
Demo
Tips and Tricks
1. Make sure you are already registered as Huawei developer.
2. Set minSDK version to 21 or later.
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
6. The Identity Kit functions can be used only after signin with registered Huawei ID.
7. A maximum of 10 user addresses are allowed.
Conclusion
In this article, we have learnt integration of user address feature in apps by Huawei Identity Kit. It allows the user to login with Huawei ID and can access the easy interface to add or edit or delete user details. It helps to deliver the online booking products by e-commerce, food delivery and logistics apps in an easy and safe way to users.
I hope you have read this article. If you found it is helpful, please provide likes and comments.
Reference
Identity Kit
Original Source
How many addresses we can add to the device?
Basavaraj.navi said:
How many addresses we can add to the device?
Click to expand...
Click to collapse
max 10 address we can store in device
Related
Introduction
In this article, we can learn the integration of landmark recognition feature in apps using Huawei Machine Learning (ML) Kit. The landmark recognition can be used in tourism scenarios. For example, if you have visited any place in the world and not knowing about that monument or natural landmarks? In this case, ML Kit helps you to take image from camera or upload from gallery, then the landmark recognizer analyses the capture and shows the exact landmark of that picture with results such as landmark name, longitude and latitude, and confidence of the input image. A higher confidence indicates that the landmark in input image is more likely to be recognized. Currently, more than 17,000 global landmarks can be recognized. In landmark recognition, the device calls the on-cloud API for detection and the detection algorithm model runs on the cloud. During commissioning and usage, make sure the device has Internet access.
{
"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"
}
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 installed.
4. Minimum API Level 21 is required.
5. Required EMUI 9.0.0 and later version devices.
Integration Process
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 tick icon, as follows.
Note: Above steps from Step 1 to 7 is common for all Huawei Kits.
8. Click Manage APIs tab and enable ML 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.4.1.300'
10. Add the below plugin and dependencies in build.gradle(Module) file.
Code:
apply plugin: 'com.huawei.agconnect'
// Huawei AGC
implementation 'com.huawei.agconnect:agconnect-core:1.5.0.300'
// Import the landmark recognition SDK.
implementation 'com.huawei.hms:ml-computer-vision-cloud:2.0.5.304'
11. Now Sync the gradle.
12. Add the required permission to the AndroidManifest.xml file.
Java:
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<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 create the business logic.
Java:
class MainActivity : AppCompatActivity(), View.OnClickListener {
private val images = arrayOf(R.drawable.forbiddencity_image, R.drawable.maropeng_image,
R.drawable.natural_landmarks, R.drawable.niagarafalls_image,
R.drawable.road_image, R.drawable.stupa_thimphu,
R.drawable.statue_image)
private var curImageIdx = 0
private var analyzer: MLRemoteLandmarkAnalyzer? = null
// You can find api key in agconnect-services.json file.
val apiKey = "Enter your API Key"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
this.btn_ok.setOnClickListener(this)
//Images to change in background with buttons
landmark_images.setBackgroundResource(images[curImageIdx])
btn_next.setOnClickListener{
curImageIdx = (curImageIdx + 1) % images.size
nextImage()
}
btn_back.setOnClickListener {
curImageIdx = (curImageIdx - 1) % images.size
prevImage()
}
}
private fun nextImage(){
landmark_images.setBackgroundResource(images[curImageIdx])
}
private fun prevImage(){
landmark_images.setBackgroundResource(images[curImageIdx])
}
private fun analyzer(i: Int) {
val settings = MLRemoteLandmarkAnalyzerSetting.Factory()
.setLargestNumOfReturns(1)
.setPatternType(MLRemoteLandmarkAnalyzerSetting.STEADY_PATTERN)
.create()
analyzer = MLAnalyzerFactory.getInstance().getRemoteLandmarkAnalyzer(settings)
// Created an MLFrame by android graphics. Recommended image size is large than 640*640 pixel.
val bitmap = BitmapFactory.decodeResource(this.resources, images[curImageIdx])
val mlFrame = MLFrame.Creator().setBitmap(bitmap).create()
//set API key
MLApplication.getInstance().apiKey = this.apiKey
//set access token
val task = analyzer!!.asyncAnalyseFrame(mlFrame)
task.addOnSuccessListener{landmarkResults ->
[email protected](landmarkResults[0])
}.addOnFailureListener{ e ->
[email protected](e)
}
}
private fun displayFailure(exception: Exception){
var error = "Failure: "
error += try {
val mlException = exception as MLException
"""
error code: ${mlException.errCode}
error message: ${mlException.message}
error reason: ${mlException.cause}
""".trimIndent()
} catch(e: Exception) {
e.message
}
landmark_result!!.text = error
}
private fun displaySuccess(landmark: MLRemoteLandmark){
var result = ""
if(landmark.landmark != null){
result = "Landmark: " + landmark.landmark
}
result += "\nPositions: "
if(landmark.positionInfos != null){
for(coordinate in landmark.positionInfos){
result += """
Latitude: ${coordinate.lat}
""".trimIndent()
result += """
Longitude: ${coordinate.lng}
""".trimIndent()
}
}
if (result != null)
landmark_result.text = result
}
override fun onClick(v: View?) {
analyzer(images[curImageIdx])
}
override fun onDestroy() {
super.onDestroy()
if (analyzer == null) {
return
}
try {
analyzer!!.stop()
} catch (e: IOException) {
Toast.makeText(this, "Stop failed: " + e.message, Toast.LENGTH_LONG).show()
}
}
}
In the activity_main.xml we can create the UI screen.
XML:
<?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"
tools:context=".MainActivity">
<ImageView
android:id="@+id/landmark_images"
android:layout_width="match_parent"
android:layout_height="470dp"
android:layout_centerHorizontal="true"
android:background="@drawable/forbiddencity_image"/>
<TextView
android:id="@+id/landmark_result"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/landmark_images"
android:layout_marginLeft="15dp"
android:layout_marginTop="15dp"
android:layout_marginBottom="10dp"
android:textSize="17dp"
android:textColor="@color/design_default_color_error"/>
<Button
android:id="@+id/btn_back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginLeft="5dp"
android:textAllCaps="false"
android:text="Back" />
<Button
android:id="@+id/btn_ok"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="OK" />
<Button
android:id="@+id/btn_next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginRight="5dp"
android:textAllCaps="false"
android:text="Next" />
</RelativeLayout>
Demo
Tips and Tricks
1. Make sure you are already registered as Huawei developer.
2. Set minSDK version to 21 or later.
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.
6. The recommended image size is large than 640*640 pixel.
Conclusion
In this article, we have learnt integration of landmark recognition feature in apps using Huawei Machine Learning (ML) Kit. The landmark recognition is mainly used in tourism apps to know about the monuments or natural landmarks visited by user. The user captures image, then the landmark recognizer analyses the capture and provides the landmark name, longitude and latitude, and confidence of input image. In landmark recognition, device calls the on-cloud API for detection and the detection algorithm model runs on the cloud.
I hope you have read this article. If you found it is helpful, please provide likes and comments.
Reference
ML Kit - Landmark Recognition
Original Source
{
"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 Account Kit in an Application.
Account Kit
Account Kit provides you with simple, secure and quick sign-in and authorization functions. Instead of entering accounts and passwords and waiting for authentication, users can just tap the Sign in with HUAWEI ID button to quickly and securely sign in to your app with their HUAWEI IDs.
Use Case
The Account Kit will be used to log in into 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 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.
Code:
apply plugin: 'com.huawei.agconnect'
// Huawei AGC
Code:
implementation 'com.huawei.agconnect:agconnect-core:1.6.0.300'
// Account Kit
Code:
implementation 'com.huawei.hms:hwid:6.3.0.301'
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"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
tools:context=".MainActivity">
<Button
android:id="@+id/sign_in"
android:layout_width="83dp"
android:layout_height="95dp"
android:text="Login with Huawei"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.542"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.471" />
</androidx.constraintlayout.widget.ConstraintLayout>
Main Activity
Java:
class MainActivity : AppCompatActivity() {
var sign_in: Button? = null
var authParams: AccountAuthParams? = null
var service: AccountAuthService? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
sign_in = findViewById<View>(R.id.sign_in) as Button
sign_in.setOnClickListener(object : OnClickListener() {
fun onClick(view: View?) {
authParams =
AccountAuthParamsHelper(AccountAuthParams.DEFAULT_AUTH_REQUEST_PARAM).setAuthorizationCode()
.createParams()
service = AccountAuthManager.getService([email protected], authParams)
startActivityForResult(service.getSignInIntent(), 8888)
}
})
}
override fun onActivityResult(requestCode: Int, resultCode: Int, @Nullable data: Intent?) {
// Process the authorization result to obtain the authorization code from AuthAccount.
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 8888) {
val authAccountTask: jdk.internal.org.jline.utils.ShutdownHooks.Task<AuthAccount> =
AccountAuthManager.parseAuthResultFromIntent(data)
if (authAccountTask.isSuccessful()) {
// The sign-in is successful, and the user's ID information and authorization code are obtained.
val authAccount: AuthAccount = authAccountTask.getResult()
Log.i("MainActivity", "serverAuthCode:" + authAccount.getAuthorizationCode())
Log.i("MainActivity", "getDisplayName:" + authAccount.getDisplayName())
Log.i("MainActivity", "getResult:" + authAccountTask.getResult())
} else {
// The sign-in failed.
Log.e(
"MainActivity",
"sign in failed:" + (authAccountTask.getException() as ApiException).getStatusCode()
)
}
}
}
}
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.
Go to HMS > CloudDebugging.
You can use Available Devices. Select a device and click RUN.
Result
Conclusion
In this article, we have learnt that how HMS Toolkit helps us to Connects users from a wide range of devices, including phones, tablets, and smart displays. It serves over 900 million users from 190+ countries and regions worldwide and supports 70+ Languages. It guarantees two-factor authentication, real-time risk prediction, and GDPR compliance.
Reference
Account Kit: Documentation
{
"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 Analytics Kit and Ads 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.
Analytics Kit
HUAWEI Analytics Kit provides analysis models to understand user behaviour and gain in-depth insights into users, products and content. It helps you to gain insight about user behaviour on different platforms based on the user behaviour events and user attributes reported by through apps.
AppGallery Connect
Find the Analytics using AppGallery connect dashboard.
Choose My Projects > Huawei Analytics > Overview > Project overview.
Project overview displays the core indicators of current project, such as the number of new users, User activity, User acquisition, User revisit, New user retention, Active user retention, User characteristics and Popular pages etc. providing a quick overview of the users and how they are using your app.
Ads Kit
Huawei Ads provides to developers a wide-ranging capabilities to deliver good quality ads content to users. This is the best way to reach target audience easily and can measure user productivity. It is very useful when we publish a free app and want to earn some money from it.
HMS Ads Kit has 7 types of Ads kits. Now we can implement Interstitial Ads in this application.
Interstitial ads are full-screen ads that cover the interface of an app. Such an ad is displayed when a user starts, pauses or exits an app, without disrupting the user's experience.
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 HUAWEI Analytics.
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'
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 Analytics Kit
implementation 'com.huawei.hms:hianalytics:6.4.0.300'
// Huawei Ads Kit
implementation 'com.huawei.hms:ads-lite:13.4.51.300'
11. Now Sync the gradle.
12. Add the required permission to the AndroidManifest.xml file.
Java:
// Analytics Kit
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.huawei.appmarket.service.commondata.permission.GET_COMMON_DATA" />
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 Analytics.
Java:
class MainActivity : AppCompatActivity() {
// Initialize the Analytics
var mInstance: HiAnalyticsInstance? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
sign_btn.setOnClickListener(mOnClickListener)
// Initialize the Analytics function
initAna()
}
private fun initAna() {
// Enable Analytics Kit Log
HiAnalyticsTools.enableLog()
// Generate the Analytics Instance
mInstance = HiAnalytics.getInstance(this)
// Enable collection capability
mInstance?.setAnalyticsEnabled(true)
}
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) {
// Analytics data to send custom events
val bundle = Bundle()
bundle.putString("email", data!!.extras!!.getString("email" ))
bundle.putString("name", data.extras!!.getString("name"))
bundle.putString("phone", data!!.extras!!.getInt("phone").toString())
bundle.putString("marks", data!!.extras!!.getFloat("86.5").toString())
mInstance!!.onEvent(HAEventType.SIGNIN, bundle)
Toast.makeText(this, "SigIn success", Toast.LENGTH_LONG).show()
} else {
Toast.makeText(this, "SignIn failed: " + (authAccountTask.exception as ApiException).statusCode, Toast.LENGTH_LONG).show()
}
}
}
}
In the ListActivity.kt we can find the business logic for Ads.
Java:
class ListActivity : AppCompatActivity() {
// Initialize the Interstitial Ads Kit
private var interstitialAd: InterstitialAd? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_list)
title = getString(R.string.interstitial_ad)
btn_alltypes.setOnClickListener {
loadInterstitialAd()
}
showInterstitialAd()
val actionBar = supportActionBar
actionBar!!.setDisplayHomeAsUpEnabled(true)
}
private val adListener: AdListener = object : AdListener() {
override fun onAdLoaded() {
super.onAdLoaded()
showToast("Ad loaded")
// Display an interstitial ad.
showInterstitialAd()
val intent = Intent([email protected], Home::class.java)
startActivity(intent)
}
override fun onAdFailed(errorCode: Int) {
showToast("Ad load failed with error code: $errorCode")
Log.d(TAG, "Ad load failed with error code: $errorCode")
val intent = Intent([email protected], Home::class.java)
startActivity(intent)
}
override fun onAdClosed() {
super.onAdClosed()
showToast("Ad closed")
Log.d(TAG, "onAdClosed")
val intent = Intent([email protected], Home::class.java)
startActivity(intent)
}
override fun onAdClicked() {
Log.d(TAG, "onAdClicked")
super.onAdClicked()
}
override fun onAdOpened() {
Log.d(TAG, "onAdOpened")
super.onAdOpened()
}
override fun onAdLeave() {
Log.d(TAG, "onAdLeaves")
super.onAdLeave()
}
}
private fun loadInterstitialAd() {
// Load an interstitial ad.
interstitialAd = InterstitialAd(this)
val adParam = AdParam.Builder().build()
interstitialAd!!.adId = getString(R.string.video_ad_id)
interstitialAd!!.loadAd(adParam)
interstitialAd!!.adListener = adListener
}
private val adId: String
get() = if (btn_alltypes.isClickable) {
getString(R.string.image_ad_id)
} else {
getString(R.string.video_ad_id)
}
private fun showInterstitialAd() {
// Display the ad
if (interstitialAd != null && interstitialAd!!.isLoaded) {
interstitialAd!!.show(this)
} else {
Toast.makeText(this, "Ad did not load", Toast.LENGTH_LONG).show()
}
}
private fun showToast(text: String) {
runOnUiThread {
Toast.makeText([email protected], text, Toast.LENGTH_LONG).show()
}
}
companion object {
private val TAG = ListActivity::class.java.simpleName
}
override fun onSupportNavigateUp(): Boolean {
finish()
return super.onSupportNavigateUp()
}
}
In the activity_main.xml we can create the UI screen.
XML:
<?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">
<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_list.xml we can create the UI screen.
XML:
<?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"
android:paddingTop="10dp"
android:paddingBottom="10dp"
tools:context=".ListActivity">
<Button
android:id="@+id/btn_alltypes"
android:layout_width="310dp"
android:layout_height="wrap_content"
android:layout_marginTop="70dp"
android:textAlignment="center"
android:layout_gravity="center_horizontal"
android:textSize="20sp"
android:textColor="@color/black"
android:padding="10dp"
android:textAllCaps="false"
android:text="Types of Books" />
</LinearLayout>
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 Analytics Kit and Ads 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
Analytics Kit
Ads Kit - Interstitial Ads
{
"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 capture the bills of text images using this Money Management app. This app converts the images to quality visibility by zooming. So, whenever the user purchases some shopping or spending, he can capture the bill using this application and can save in memory.
So, I will provide the series of articles on this Money Management App, in upcoming articles I will integrate other Huawei Kits.
If you are new to this application, follow my previous articles.
Beginner: Find the introduction Sliders and Huawei Account Kit Integration in Money Management Android app (Kotlin) - Part 1
Beginner: Integration of Huawei Ads Kit and Analytics Kit in Money Management Android app (Kotlin) – Part 2
Beginner: Manage the Budget using Room Database in Money Management Android app (Kotlin) – Part 3
ML Kit - Text Image Super-Resolution
The ML Kit - Text Image Super-Resolution feature of Huawei ML Kit. It provides better quality and visibility of old and blurred text on an image. When you take a photograph of a document from far or cannot properly adjust the focus, the text may not be clear. In this situation, it can zoom an image that contains the text up to three times and significantly improves the definition of the text.
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 19 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 ML 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.4.1.300'
10. Add the below plugin and dependencies in build.gradle(Module) file.
Java:
apply plugin: 'com.huawei.agconnect'
// Huawei AGC
implementation 'com.huawei.agconnect:agconnect-core:1.5.0.300'
// Import the text image super-resolution base SDK.
implementation 'com.huawei.hms:ml-computer-vision-textimagesuperresolution:2.0.4.300'
// Import the text image super-resolution model package.
implementation 'com.huawei.hms:ml-computer-vision-textimagesuperresolution-model:2.0.4.300'
11. Now Sync the gradle.
12. Add the required permission to the AndroidManifest.xml file.
XML:
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Let us move to development
I have created a project on Android studio with empty activity let us start coding.
In the CaptureActivity.kt we can find the business logic.
Java:
class CaptureActivity : AppCompatActivity(), View.OnClickListener {
private var analyzer: MLTextImageSuperResolutionAnalyzer? = null
private val QUALITY = 1
private val ORIGINAL = 2
private var imageView: ImageView? = null
private var srcBitmap: Bitmap? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_capture)
imageView = findViewById(R.id.bill)
srcBitmap = BitmapFactory.decodeResource(resources, R.drawable.bill_1)
findViewById<View>(R.id.btn_quality).setOnClickListener(this)
findViewById<View>(R.id.btn_original).setOnClickListener(this)
createAnalyzer()
}
// Find the on click listeners
override fun onClick(v: View?) {
if (v!!.id == R.id.btn_quality) {
detectImage(QUALITY)
} else if (v.id == R.id.btn_original) {
detectImage(ORIGINAL)
}
}
private fun release() {
if (analyzer == null) {
return
}
analyzer!!.stop()
}
// Find the method to detect bills or text images
private fun detectImage(type: Int) {
if (type == ORIGINAL) {
setImage(srcBitmap!!)
return
}
if (analyzer == null) {
return
}
// Create an MLFrame by using the bitmap.
val frame = MLFrame.Creator().setBitmap(srcBitmap).create()
val task = analyzer!!.asyncAnalyseFrame(frame)
task.addOnSuccessListener { result -> // success.
Toast.makeText(applicationContext, "Success", Toast.LENGTH_LONG).show()
setImage(result.bitmap)
}.addOnFailureListener { e ->
// Failure
if (e is MLException) {
val mlException = e
// Get the error code, developers can give different page prompts according to the error code.
val errorCode = mlException.errCode
// Get the error message, developers can combine the error code to quickly locate the problem.
val errorMessage = mlException.message
Toast.makeText(applicationContext,"Error:$errorCode Message:$errorMessage", Toast.LENGTH_LONG).show()
// Log.e(TAG, "Error:$errorCode Message:$errorMessage")
} else {
// Other exception
Toast.makeText(applicationContext, "Failed:" + e.message, Toast.LENGTH_LONG).show()
// Log.e(TAG, e.message!!)
}
}
}
private fun setImage(bitmap: Bitmap) {
[email protected](Runnable {
imageView!!.setImageBitmap(
bitmap
)
})
}
private fun createAnalyzer() {
analyzer = MLTextImageSuperResolutionAnalyzerFactory.getInstance().textImageSuperResolutionAnalyzer
}
override fun onDestroy() {
super.onDestroy()
if (srcBitmap != null) {
srcBitmap!!.recycle()
}
release()
}
}
In the activity_capture.xml we can create the UI screen.
XML:
<?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"
tools:context=".mlkit.CaptureActivity">
<LinearLayout
android:id="@+id/buttons"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="vertical"
tools:ignore="MissingConstraints">
<Button
android:id="@+id/btn_quality"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_margin="15dp"
android:gravity="center"
android:textSize="19sp"
android:text="Quality"
android:textAllCaps="false"
android:textColor="@color/Red"
tools:ignore="HardcodedText" />
<Button
android:id="@+id/btn_original"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_margin="15dp"
android:gravity="center"
android:text="Original"
android:textSize="19sp"
android:textAllCaps="false"
android:textColor="@color/Red"
tools:ignore="HardcodedText" />
</LinearLayout>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@+id/buttons"
android:layout_marginBottom="15dp">
<ImageView
android:id="@+id/bill"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_gravity="center"
tools:ignore="ObsoleteLayoutParam" />
</ScrollView>
</RelativeLayout>
Demo
Tips and Tricks
1. Make sure you are already registered as Huawei developer.
2. Set minSDK version to 19 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 learnt about Text Image Super-Resolution feature of Huawei ML Kit and its functionality. It provides better quality and visibility of old and blurred text on an image. It can zoom an image that contains the text up to three times and significantly improves the definition of the text.
Reference
ML Kit – Documentation
ML Kit – Training Video
{
"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 Rewarded Ads feature of Huawei Ads Kit into the android app. So, Rewarded ads are full-screen video ads that allow users to view in exchange for in-app rewards.
Ads Kit
Huawei Ads provides to developers a wide-ranging capabilities to deliver good quality ads content to users. This is the best way to reach the target audience easily and can measure user productivity. It is very useful when we publish a free app and want to earn some money from it.
HMS Ads Kit has 7 types of Ads kits. Now we can implement Rewarded Ads in this application.
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. 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'
9. 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 Ads Kit
implementation 'com.huawei.hms:ads-lite:13.4.51.300'
10. Now Sync the gradle.
11. Add the required permission to the AndroidManifest.xml file.
Java:
// Ads Kit
<uses-permission android:name="android.permission.INTERNET" />
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 Ads.
Java:
class MainActivity : AppCompatActivity() {
companion object {
private const val PLUS_SCORE = 1
private const val MINUS_SCORE = 5
private const val RANGE = 2
}
private var rewardedTitle: TextView? = null
private var scoreView: TextView? = null
private var reStartButton: Button? = null
private var watchAdButton: Button? = null
private var rewardedAd: RewardAd? = null
private var score = 1
private val defaultScore = 10
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = getString(R.string.reward_ad)
rewardedTitle = findViewById(R.id.text_reward)
rewardedTitle!!.setText(R.string.reward_ad_title)
// Load a rewarded ad.
loadRewardAd()
// Load a score view.
loadScoreView()
// Load the button for watching a rewarded ad.
loadWatchButton()
// Load the button for starting a game.
loadPlayButton()
}
// Load a rewarded ad.
private fun loadRewardAd() {
if (rewardedAd == null) {
rewardedAd = RewardAd([email protected], getString(R.string.ad_id_reward))
}
val rewardAdLoadListener: RewardAdLoadListener = object : RewardAdLoadListener() {
override fun onRewardAdFailedToLoad(errorCode: Int) {
showToast("onRewardAdFailedToLoad errorCode is :$errorCode");
}
override fun onRewardedLoaded() {
showToast("onRewardedLoaded")
}
}
rewardedAd!!.loadAd(AdParam.Builder().build(), rewardAdLoadListener)
}
// Display a rewarded ad.
private fun rewardAdShow() {
if (rewardedAd!!.isLoaded) {
rewardedAd!!.show([email protected], object : RewardAdStatusListener() {
override fun onRewardAdClosed() {
showToast("onRewardAdClosed")
loadRewardAd()
}
override fun onRewardAdFailedToShow(errorCode: Int) {
showToast("onRewardAdFailedToShow errorCode is :$errorCode")
}
override fun onRewardAdOpened() {
showToast("onRewardAdOpened")
}
override fun onRewarded(reward: Reward) {
// You are advised to grant a reward immediately and at the same time, check whether the reward
// takes effect on the server. If no reward information is configured, grant a reward based on the
// actual scenario.
val addScore = if (reward.amount == 0) defaultScore else reward.amount
showToast("Watch video show finished , add $addScore scores")
score += addScore
setScore(score)
loadRewardAd()
}
})
}
}
// Set a Score
private fun setScore(score: Int) {
scoreView!!.text = "Score:$score"
}
// Load the button for watching a rewarded ad
private fun loadWatchButton() {
watchAdButton = findViewById(R.id.show_video_button)
watchAdButton!!.setOnClickListener(View.OnClickListener { rewardAdShow() })
}
// Load the button for starting a game
private fun loadPlayButton() {
reStartButton = findViewById(R.id.play_button)
reStartButton!!.setOnClickListener(View.OnClickListener { play() })
}
private fun loadScoreView() {
scoreView = findViewById(R.id.score_count_text)
scoreView!!.text = "Score:$score"
}
// Used to play a game
private fun play() {
// If the score is 0, a message is displayed, asking users to watch the ad in exchange for scores.
if (score == 0) {
Toast.makeText([email protected], "Watch video ad to add score", Toast.LENGTH_SHORT).show()
return
}
// The value 0 or 1 is returned randomly. If the value is 1, the score increases by 1. If the value is 0, the
// score decreases by 5. If the score is a negative number, the score is set to 0.
val random = Random().nextInt(RANGE)
if (random == 1) {
score += PLUS_SCORE
Toast.makeText([email protected], "You win!", Toast.LENGTH_SHORT).show()
} else {
score -= MINUS_SCORE
score = if (score < 0) 0 else score
Toast.makeText([email protected], "You lose!", Toast.LENGTH_SHORT).show()
}
setScore(score)
}
private fun showToast(text: String) {
runOnUiThread {
Toast.makeText([email protected], text, Toast.LENGTH_SHORT).show()
}
}
}
In the activity_main.xml we can create the UI screen.
Java:
<?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"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_reward"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:textAlignment="center"
android:textSize="20sp"
android:text="This is rewarded ads sample"/>
<Button
android:id="@+id/play_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/text_reward"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:text="Play" />
<Button
android:id="@+id/show_video_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/play_button"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:text="Watch Video" />
<TextView
android:id="@+id/score_count_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/show_video_button"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
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 Analytics Kit and Ads 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
Ads Kit - Rewarded Ads
Ads Kit – Training Video