Integration of Huawei Account Kit in Book Reading Android app (Kotlin) - Part 1
Published: 2022-02-04 04:53:09


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rr6hgwzqccrbnfhhtv1z.jpg)
## **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**

- First register as Huawei developer and complete identity verification in Huawei developers website, refer to register a [Huawei ID](https://developer.huawei.com/consumer/en/doc/start/registration-and-verification-0000001053628148).
- Create a project in android studio, refer [Creating an Android Studio Project](https://developer.huawei.com/consumer/en/codelab/HMSPreparation/index.html#1).
- Generate a **SHA-256 certificate fingerprint**.
- 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.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rlsp69x3eohuilb3jaso.png)
- [Create an App in AppGallery Connect](https://developer.huawei.com/consumer/en/codelab/HMSPreparation/index.html#0).
- Download the **agconnect-services.json** file from **App information**, copy and paste in android **Project **under **app **directory, as follows.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/row6epkn1g959j0z3uos.png)
- Enter **SHA-256 certificate fingerprint** and click **Save **button, as follows.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/abirkw50zgoeivhuspez.png)
- Click **Manage APIs** tab and enable **Account Kit**.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0dz2wugp8pgk6ao1hc10.jpg)
- Add the below maven URL in **build.gradle(Project)** file under the repositories of **buildscript**, **dependencies and allprojects**, refer [Add Configuration](https://developer.huawei.com/consumer/en/codelab/HMSPreparation/index.html#6).
`maven { url 'http://developer.huawei.com/repo/' }
classpath 'com.huawei.agconnect:agcp:1.6.0.300'`
- Add the below plugin and dependencies in **build.gradle(Module)** file.
`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'`
- Now Sync the gradle.
- Add the required permission to the **AndroidManifest.xml** file.
`<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.

`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(this@MainActivity, 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(this@MainActivity, 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.

`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.

`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.

`<?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.

`<?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.

`<?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**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3ahgz4hbe4ioegnre6lz.jpg)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/47rwpgkfdea3km8dfonk.jpg)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pa9ubqm8z8s2ltkfijl4.jpg)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r48xc2l3glmivut7x0ei.jpg)

## **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](https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/introduction-0000001050048870)