[Huawei Developers] HMS Community:
Overview

In this article, I will create a Directory android application using Kotlin in which I will integrate HMS Core kits such as HMS Account and AuthService Kit.

App will make use of android MVVM clean architecture using Jetpack components such as DataBinding, AndroidViewModel, Observer, LiveData and much more.

In this article we are going to implement DataBinding using Observable pattern.

Huawei ID Service Introduction

Huawei ID login 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.

Prerequisite

Huawei Phone EMUI 3.0 or later.

Non-Huawei phones Android 4.4 or later (API level 19 or higher).

HMS Core APK 4.0.0.300 or later

Android Studio

AppGallery Account

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.

App Development

Add Required Dependencies:

Launch Android studio and create a new project. Once the project is ready.

Add following dependency for HMS Kits

Navigate to the Gradle scripts folder and open build.gradle (project: app).

dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
//noinspection GradleDependency
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.6.0'
implementation 'androidx.appcompat:appcompat:1.4.1'
implementation 'androidx.annotation:annotation:1.3.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
implementation 'androidx.navigation:navigation-fragment-ktx:2.4.1'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

Code Implementation

Created following package model, event, viewmodel.

ViewModel: The ViewModel makes it easy to update data changes on the UI.Create a package named viewmodel in your main folder.Then create a new file and name it LoginViewModel.kt along with their FactoryViewModelProviders.

LoginViewModel.kt:

package com.hms.directoryapp

import android.annotation.SuppressLint
import android.app.Activity
import android.app.Application
import android.content.Intent
import android.util.Log
import androidx.databinding.Observable
import androidx.lifecycle.AndroidViewModel
import com.hms.directoryapp.event.ActivityNavigation
import com.hms.directoryapp.event.LiveMessageEvent

const val HMS_SIGN_IN: Int = 9001

@SuppressLint("StaticFieldLeak")
class LoginViewModel(application: Application) : AndroidViewModel(application), Observable {

private val context = getApplication<Application>().applicationContext
private var mAuthManager: AccountAuthService? = null
private var mAuthParam: AccountAuthParams? = null

val startActivityForResultEvent = LiveMessageEvent<ActivityNavigation>()

fun login() {

mAuthParam = AccountAuthParamsHelper(AccountAuthParams.DEFAULT_AUTH_REQUEST_PARAM)
.setIdToken()
.setAccessToken()
.createParams()
mAuthManager = AccountAuthManager.getService(Activity(), mAuthParam)
startActivityForResultEvent.sendEvent {
startActivityForResult(
mAuthManager?.signInIntent,
HMS_SIGN_IN
)
}
}

fun onResultFromActivity(requestCode: Int, data: Intent?) {
when (requestCode) {
HMS_SIGN_IN -> {
val authAccountTask = AccountAuthManager.parseAuthResultFromIntent(data)
onCompleteLogin(authAccountTask)
}
}
}

private fun onCompleteLogin(doneTask: Task<AuthAccount>) {
if (doneTask.isSuccessful) {
val authAccount = doneTask.result
Log.d("LoginViewModel", "SigIn Success")
context.startActivity(Intent(context, OrderActivity::class.java))

} else {
Log.d("LoginViewModel", "SigIn Error")
}
}

override fun addOnPropertyChangedCallback(callback: Observable.OnPropertyChangedCallback?) {
}

override fun removeOnPropertyChangedCallback(callback: Observable.OnPropertyChangedCallback?) {
}

}

Xml layout DataBinding

To include data binding in the UI, enclose all content with <layout></layout>.

The ViewModel is introduced to the layout in the <data></data> section, as shown. Ensure that the type value points to the specific folder that has the required ViewModel.

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white">

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="6dp"
android:text="Directory App "
android:textAlignment="center"
android:textColor="@color/white"
android:background="@color/purple_500"
android:textSize="34sp"
android:textStyle="bold" />

<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:gravity="center">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="SigIn / SignUp "
android:textAlignment="center"
android:textColor="@color/black"
android:textSize="34sp"
android:textStyle="bold" />

<Button
android:id="@+id/btn_sign"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginBottom="5dp"
android:background="@color/cardview_dark_background"
android:text="Login With Huawei Id"
android:textColor="@color/white"
android:textStyle="bold" />
</LinearLayout>

</ScrollView>

</RelativeLayout>
</layout>

MainActivity.kt:

package com.hms.directoryapp

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProviders
import com.hms.directoryapp.databinding.ActivityMainBinding
import com.hms.directoryapp.event.ActivityNavigation

class MainActivity : AppCompatActivity(), ActivityNavigation {

private lateinit var viewModel: LoginViewModel
private lateinit var dataBinding: ActivityMainBinding

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_main)

val viewModel: LoginViewModel by lazy {
val activity = requireNotNull(this) {}
ViewModelProviders.of(this, LoginViewModelFactory(activity.application))
.get(LoginViewModel::class.java)
}

dataBinding.loginViewModel = viewModel
dataBinding.lifecycleOwner = this
viewModel.startActivityForResultEvent.setEventReceiver(this, this)
}

public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
viewModel.onResultFromActivity(requestCode, data)
super.onActivityResult(requestCode, resultCode, data)
}

}

App Build Result

View attachment 5618739

Tips and Tricks

Identity Kit displays the HUAWEI ID registration or sign-in page first. The user can use the functions provided by Identity Kit only after signing in using a registered HUAWEI ID.

Conclusion

In this article, we have learned how to integrate Huawei ID in Android application. After completely read this article user can easily implement Huawei ID in the Directory App android application using Kotlin.

Thanks for reading this article. Be sure to like and comment to this article, if you found it helpful. It means a lot to me.

References

HMS Docs:

https://developer.huawei.com/consum.../HMSCore-Guides/introduction-0000001050048870