Exploring CMS DEMO: Account Kit and Auth Service Samples in Android

Feyza Ürkut
Huawei Developers
Published in
9 min readSep 23, 2024
Photo by Andy Vult on Unsplash

Introduction

The Common Mobile Services (CMS) library simplifies the integration of Huawei and Google Mobile Services through a unified solution, while the CMS DEMO project offers practical examples to help developers easily integrate the CMS library into their projects.

In this article, we will explore the CMS DEMO project and focus on examples of Account Kit and Auth Service on Android.

You can check out this article for more detailed information about the CMS library:

If you would like to review our previous article, which is about Map, Location and Ads Kit examples on Android:

A Quick Overview of the CMS DEMO Project

To facilitate seamless integration, the CMS DEMO project provides a live demo showcasing the capabilities and functionalities of the Common Mobile Services library. This demo application is continually updated with new kit demos to ensure developers have access to the latest features and improvements.
In the next section, we will take a detailed look at the CMS DEMO project, focusing on examples of Account Kit and Auth Service on Android.

Account Kit: Simple, Fast and Secure Login and Authorization

AccountScreen

📌Step 1: Inject account service instance

This function provides the AccountService instance that will be used throughout the application. Marking the function with the @Singleton annotation ensures that a single instance of AccountService is used across the entire application. The @Provides annotation tells Dagger that this function is a dependency provider function.

Inside the function, an AccountService instance is created using the AccountService.Factory.create() method. While creating this instance, the application context (ApplicationContext) is passed as the context parameter. Additionally, SignInParams is required to obtain extra information like email from the user, typically by requesting permission during the sign-in process.

📌Step 2: Creating the XML Layout for AccountScreen

First, create a fragment file for the AccountScreen and define its layout in the XML file.

Use ConstraintLayout to manage the positions of the UI elements. At the top, add a TextView to display the account screen title, followed by three necessary buttons. The first of these buttons is a SignInButton, which is specifically designed to allow users to sign in and is provided by the third-party CMS library.

📌 Step 3: Implement AccountScreen Fragment

🔸Create account service instance

This line allows the AccountService instance to be injected into the class using lateinit injection with Dagger Hilt.

🔸initializeAccountService()

This function associates the signIn, getLastSignedAccount, and signOut functions with the button click events.

🔸signIn()

This function initiates a sign-in process via the accountService, receives a sign-in request, and starts it using startActivityForResult with the specified REQUEST_CODE to await an activity result.

🔸getLastSignedAccount()

This function performs a silent sign-in via the accountService, retrieving the account information of the user who last signed in. Using the ResultCallback interface, it handles different actions based on the sign-in result.

  • The onSuccess method retrieves the user’s credentials (ID, email, name) upon a successful sign-in and formats this information as text to display in the textViewAccountInfo component.
  • If the sign-in fails, the onFailure method shows the message "Please sign in first."
  • The onCancelled method displays a message indicating that the process was canceled.

🔸onActivityResult()

This function uses the onActivityResult method to process the results of the sign-in operation. If the specified requestCode matches REQUEST_CODE and the data object is not null, it calls onSignInActivityResult to handle the sign-in result via the accountService.

The result is processed using the ResultCallback interface:

  • In the case of a successful sign-in, the user’s credentials are printed on the screen.
  • If there’s an error, an error message is displayed.
  • If the process is canceled, a cancellation message is shown on the screen.

🔸signOut()

This function initiates the sign-out process via the accountService and displays an appropriate message on the screen based on whether the operation is successful, unsuccessful, or canceled.

Auth Service: One or More Authentication Modes

1- Email/Password Sign In

2- Phone Number Sign In

AuthScreen
AuthScreen

📌Step 1: Inject auth service instance

This code defines a dependency injection module using Dagger Hilt. The @Module and @InstallIn(SingletonComponent::class) annotations indicate that the module should provide dependencies that are valid throughout the application (singleton). Within the AuthServiceModule class, a function marked with @Singleton and @Provides creates the AuthService and provides this service using the Context dependency. The @ApplicationContext annotation specifies that the application-wide context will be injected.

📌Step 2: Creating XML Layout for Email Password and Phone Sign-In

First, we created a sign-up page to collect the user’s email and password information. On this page, users can enter their email and password to create an account. Next, we prepared a sign-in page for existing users to log in. On this page, users can enter their email and password to sign in. Additionally, we added a sign-out button on the same page.

1- Email/Password Sign-In

🎯 Step 1: Implement the EmailPasswordScreen Fragment

🔸 Create Auth Service Instance
This line allows the AuthService instance to be injected into the class using lateinit injection with Dagger Hilt.

🔸 signInWithEmail()
This code defines a function that performs the sign-in operation using email and password. It retrieves the email and password from the user; if these fields are empty, an error message is displayed. If the information is correct, the sign-in process is initiated using the authService. Upon a successful sign-in, the email and password fields are cleared, and a welcome message is shown to the user. If the sign-in fails, an error message is displayed on the screen.

🔸checkUser()

This code checks if there is a currently logged-in user. It retrieves the logged-in user using authService.getUser(). If a user exists, a welcome message is displayed along with the user's ID. If no user is found, a general welcome message is shown.

🔸 signOut()
This code defines a function that signs out the user. It calls authService.signOut(), and then checkUser() is invoked again to verify if there is any logged-in user.

🎯 Step 2: Implementing the SignUpScreen Fragment

🔸 signUp()
This code defines a function that registers a user using email and password. It retrieves the email and password from the user; if these fields are empty, an error message is displayed. If the information is valid, the sign-up process is initiated using authService.signUp(). Upon successful registration, two different actions are taken based on the verification type: if a verification code is required, an alert dialog is shown (showAlertDialog()); if no verification is needed, a success message is displayed, and the user is returned to the previous screen. If registration fails, an error message is shown.

🔸 showAlertDialog()
This code displays an alert dialog to prompt the user for the verification code. It uses AlertDialog.Builder to create the dialog and adds a custom view (bindingVerify.root) to it. When the user clicks the "Verify" button, the verifyCode(dialog) function is called to initiate the verification process. The created dialog is then shown (dialog.show()).

🔸 verifyCode()
This code processes the verification code entered by the user. If the verification code field is empty, an error message is displayed. If the code is not empty, the verification is performed using authService.verifyCode() with the email, password, and verification code. If verification is successful, a success message is displayed, the dialog is closed, and the user is returned to the previous screen. If verification fails, an error message is shown.

2- Phone Number Sign-In

🎯 Step 1: Implementing the PhoneSignInScreen Fragment

🔸 initUI()
This code initializes the user interface (UI) elements in an Android application and sets their visibility and functionality based on certain conditions. First, it checks which type of mobile service the device is using (GMS or HMS). If GMS (Google Mobile Services) is used, the sign-up option (tvSignUp) is made invisible, and the phone code is updated with a GMS-specific code. Then, click listeners are assigned to various buttons to allow users to sign up, log in, and log out.

🔸 signInWithPhone()
This code performs the sign-in operation using a phone number. It retrieves the phone number and password from the user; if these fields are empty, an error message is displayed. If they are not empty, a verification code is sent to the specified phone number. If the verification code is successfully sent, an alert dialog is displayed for the user to enter the code. If sending the code fails, an error message is shown.

🔸 showAlertDialog()
This code displays an alert dialog for the user to enter the verification code in an Android application. It uses AlertDialog.Builder to create a dialog and ensures it has a view for entering the verification code (bindingVerify.root). When the user clicks the "Verify" button, the verifyCode function is called to process the entered verification code. After creating and showing the dialog, the user can proceed with the verification.

🔸 verifyCode()
This code uses the verification code entered by the user to perform the phone sign-in. If the entered code is empty, an error message is displayed. If the code is not empty, sign-in is attempted using the phone number, password, and verification code. Upon a successful sign-in, a success message is shown, the dialog is closed, and the UI is updated (input fields cleared, welcome message displayed). If sign-in fails, an error message is shown.

🔸 checkUser() signOut()
This code checks the user’s sign-in status and manages sign-in/sign-out operations. The checkUser function retrieves the phone number if the user is signed in and displays a "Welcome" message; if not signed in, it shows a general welcome message. The signOut function logs out the user and calls checkUser to verify the updated sign-in status.

🎯 Step 2: Implementing the PhoneSignUpScreen Fragment

🔸 signUpWithPhone()
This code initiates the registration process using a phone number. It retrieves the phone number and password from the user; if these fields are empty, an error message is displayed. If not empty, a verification code is sent to the specified phone number. Upon successful sending of the code, a dialog is shown for the user to enter the code. If sending fails, an error message is displayed.

🔸 showAlertDialog() & verifyCode()
This code displays an alert dialog for the user to enter the verification code. It uses AlertDialog.Builder to create the dialog and includes the verification screen (bindingVerify.root). When the user clicks the "Verify" button, the verifyCode function is called to process the entered code. This code performs the phone registration using the verification code provided by the user. If the verification code is empty, an error message is shown. If not empty, registration is attempted using the phone number, password, and verification code. Upon successful registration, a success message is displayed, the dialog is closed, and the user is returned to the previous screen. If registration fails, an error message is displayed.

Conclusion

In this article, we explored the integration of Account and Authentication (Auth) services into an Android application using the CMS DEMO project. By following these examples, you can effectively implement user authentication and account management in your projects, enhancing both security and user experience.

Feel free to delve deeper into CMS DEMO and share your feedback on how it can benefit your projects! 😊

References

--

--