DEV Community

HMS Community
HMS Community

Posted on

Expert: Directory App MVVM Jetpack (HMS Identity Kit) in Android using Kotlin- Part-2

** 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, AuthService and Identity 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.
Hms Core Identity Service Introduction
Hms Core Identity provides an easy interface to add or edit or delete user details and enables the users to authorize apps to access their addresses through a single tap on the screen. That is, app can obtain user addresses in a more convenient way.
Prerequisite
1.Huawei Phone EMUI 3.0 or later.
2.Non-Huawei phones Android 4.4 or later (API level 19 or higher).
3.HMS Core APK 4.0.0.300 or later
4.Android Studio
5.AppGallery Account
App Gallery Integration process
1.Sign In and Create or Choose a project on AppGallery Connect portal.

2.Navigate to Project settings and download the configuration file.

3.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.
•Navigate to the Gradle scripts folder and open build.gradle (module: app).

```apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

apply plugin: 'com.huawei.agconnect'

android {

compileSdkVersion 30

buildToolsVersion "29.0.3"



buildFeatures {



    dataBinding = true

    viewBinding = true

}
Enter fullscreen mode Exit fullscreen mode


• Add following dependency for HMS Kits


Enter fullscreen mode Exit fullscreen mode

//HMS Kits

implementation 'com.huawei.agconnect:agconnect-core:1.5.0.300'
implementation 'com.huawei.hms:hwid:5.3.0.302'
implementation 'com.huawei.hms:identity:5.3.0.300'



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


Enter fullscreen mode Exit fullscreen mode

• repositories {
• google()
• jcenter()
• maven {url 'https://developer.huawei.com/repo/'}
• }
• dependencies {
• classpath "com.android.tools.build:gradle:4.0.1"
classpath 'com.huawei.agconnect:agcp:1.4.2.300'



**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.
MainActivity.kt:


```package com.hms.directory

import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProviders
import com.hms.corrierapp.R
import com.hms.corrierapp.databinding.ActivityMainBinding
import com.hms.directory.event.ActivityNavigation
import com.hms.directory.viewmodel.LoginViewModel
import com.hms.directory.viewmodel.LoginViewModelFactory

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)
    }

}
Enter fullscreen mode Exit fullscreen mode

LoginViewModel.kt:

package com.hms.directory.viewmodel


@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() {
        val intent = Intent(context, OrderActivity::class.java)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        context.startActivity(intent)

       /* 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, ContactListActivity::class.java))

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

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

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

}
Enter fullscreen mode Exit fullscreen mode

ContactActivity.kt:

public class ContactListActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contact_list);

        // Load contacts from file
        Contacts.loadData(this);

        // Set up recycler view and fill it with all the contacts
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.contact_list);
        recyclerView.setAdapter(new ContactListAdapter(this, Contacts.LIST));

    }
Enter fullscreen mode Exit fullscreen mode

Xml layout DataBinding
To include data binding in the UI, enclose all content with .
The ViewModel is introduced to the layout in the section, as shown. Ensure that the type value points to the specific folder that has the required ViewModel.
App Build Result

Uploading image
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 Identity Kit 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/consumer/en/doc/development/HMSCore-Guides/introduction-0000001050048870

Top comments (0)