User Registration and Login

Last Updated on : 2024-01-26 10:06:14download

This topic describes the splash screen, user registration, and user login.

Splash screen

Check if the user is already logged in.

  • If the user is already logged in, open the app’s homepage.
  • If the user is not logged in, redirect them to the login or registration page.
  1. Right-click on your project. Choose New > Activity > Empty Activity and set the Activity Name to SplashActivity. Open /app/src/main/res/layout/activity_splash.xml and replace the existing UI code with the following.

    <?xml version="1.0" encoding="utf-8"?>
    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="match_parent"
      android:layout_height="match_parent">
    
    <TextView
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:textSize="20dp"
       android:layout_marginTop="50dp"
       android:layout_marginLeft="20dp"
       android:text="@string/user_guide_title" />
    
    <LinearLayout
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:orientation="vertical"
       android:paddingLeft="20dp"
       android:paddingRight="20dp"
       android:layout_gravity="bottom"
       android:layout_marginBottom="40dp"
       android:paddingBottom="20dp">
    
       <Button
           android:id="@+id/btnLogin"
           android:layout_width="match_parent"
           android:layout_height="48dp"
           android:text="@string/user_login" />
    
       <Button
           android:id="@+id/btnRegister"
           android:layout_width="match_parent"
           android:layout_height="48dp"
           android:text="@string/user_register" />
    </LinearLayout>
    </FrameLayout>
    
  2. Replace the code in SplashActivity.kt with the following.

    class SplashActivity : AppCompatActivity(), View.OnClickListener {
     override fun onCreate(savedInstanceState: Bundle?) {
       super.onCreate(savedInstanceState)
    
       // If login, then navigate to MainSampleList
       if (ThingHomeSdk.getUserInstance().isLogin) {
           startActivity(Intent(this, MainActivity::class.java))
           finish()
       }
       setContentView(R.layout.activity_splash)
    
       findViewById<Button>(R.id.btnRegister).setOnClickListener(this)
       findViewById<Button>(R.id.btnLogin).setOnClickListener(this)
    
    }
    
    override fun onClick(v: View?) {
       v?.id?.let {
           if (it == R.id.btnRegister) {
               // Register
               startActivity(Intent(this, UserRegisterActivity::class.java))
           } else if (it == R.id.btnLogin) {
               // Login
               startActivity(Intent(this, UserLoginActivity::class.java))
           }
       }
    }
    }
    
  3. In /app/src/main/AndroidManifest.xml, specify the page to display when SplashActivity is not launched. Here is the example code for AndroidManifest.xml.

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:name=".BaseApplication"
        android:theme="@style/Theme.MaterialComponents.Light.NoActionBar"
        tools:replace="android:allowBackup,android:supportsRtl">
        <activity
            android:name=".MainActivity"
            android:exported="false"
            android:screenOrientation="portrait" />
        <activity
            android:name=".SplashActivity"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".UserRegisterActivity"
            android:exported="false"
            android:screenOrientation="portrait" />
        <activity
            android:name=".UserLoginActivity"
            android:exported="false"
            android:screenOrientation="portrait" />
    
    </application>
    

User registration

  1. Create a new Activity named UserRegisterActivity. Here is the example code for the user registration UI.

     <?xml version="1.0" encoding="utf-8"?>
    <androidx.coordinatorlayout.widget.CoordinatorLayout 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="match_parent">
    
    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    
        <com.google.android.material.appbar.MaterialToolbar
            android:id="@+id/topAppBar"
            style="@style/Widget.MaterialComponents.Toolbar.Primary"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:navigationIcon="?attr/homeAsUpIndicator"
            app:title="@string/user_register" />
    
    </com.google.android.material.appbar.AppBarLayout>
    
    <androidx.core.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">
    
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:paddingLeft="20dp"
            android:paddingRight="20dp"
            android:paddingBottom="20dp">
    
            <com.google.android.material.textfield.TextInputLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="4dp"
                android:layout_marginTop="20dp"
                android:hint="@string/user_country_code"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toTopOf="parent">
    
                <com.google.android.material.textfield.TextInputEditText
                    android:id="@+id/etCountryCode"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content" />
            </com.google.android.material.textfield.TextInputLayout>
    
            <com.google.android.material.textfield.TextInputLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="4dp"
                android:hint="@string/user_account_tips"
                app:endIconMode="clear_text"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toTopOf="parent">
    
                <com.google.android.material.textfield.TextInputEditText
                    android:id="@+id/etAccount"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content" />
            </com.google.android.material.textfield.TextInputLayout>
    
            <com.google.android.material.textfield.TextInputLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="4dp"
                android:hint="@string/user_password"
                app:endIconMode="clear_text"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toTopOf="parent">
    
                <com.google.android.material.textfield.TextInputEditText
                    android:id="@+id/etPassword"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content" />
            </com.google.android.material.textfield.TextInputLayout>
    
            <com.google.android.material.textfield.TextInputLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="4dp"
                android:hint="@string/user_verification_code"
                app:endIconMode="clear_text"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toTopOf="parent">
    
                <com.google.android.material.textfield.TextInputEditText
                    android:id="@+id/etCode"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content" />
            </com.google.android.material.textfield.TextInputLayout>
    
            <Button
                android:id="@+id/btnCode"
                android:layout_width="match_parent"
                android:layout_height="48dp"
                android:text="@string/user_send_code" />
    
            <Button
                android:id="@+id/btnRegister"
                android:layout_width="match_parent"
                android:layout_height="48dp"
                android:text="@string/user_register" />
        </LinearLayout>
    
    </androidx.core.widget.NestedScrollView>
    
    </androidx.coordinatorlayout.widget.CoordinatorLayout>
    
  2. Implement the user registration logic.

    The user registration method requires the countryCode parameter to specify the country code, enabling the selection of the nearest data center based on the users’ location. Users can register using either an email address or a mobile phone number.

    To enable verification with mobile phone SMS messages, you must subscribe to and configure the service Verify with Mobile Phone SMS. After this service is enabled, users can register and log in with an app account or reset the password using their mobile phone number. They can also bind their mobile phone number with the app. For more information, see Subscribe to and Configure SMS Verification.

    Example code for user registration:

    class UserRegisterActivity : AppCompatActivity(), View.OnClickListener {
    private val check =
        "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$"
    private val regex: Pattern = Pattern.compile(check)
    private val mRegisterType = 1
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.user_activity_register)
    
        val toolbar: Toolbar = findViewById<View>(R.id.topAppBar) as Toolbar
        toolbar.setNavigationOnClickListener {
            finish()
        }
    
        findViewById<Button>(R.id.btnRegister).setOnClickListener(this)
        findViewById<Button>(R.id.btnCode).setOnClickListener(this)
    }
    
    override fun onClick(v: View?) {
        val strAccount = findViewById<EditText>(R.id.etAccount).text.toString()
        val strCountryCode = findViewById<EditText>(R.id.etCountryCode).text.toString()
        val strPassword = findViewById<EditText>(R.id.etPassword).text.toString()
        val strCode = findViewById<EditText>(R.id.etCode).text.toString()
    
        val matcher: Matcher = regex.matcher(strAccount)
        val isEmail: Boolean = matcher.matches()
    
        v?.id?.let {
            if (it == R.id.btnRegister) {
                val callback = object : IRegisterCallback {
                    override fun onSuccess(user: User?) {
                        Toast.makeText(
                            this@UserRegisterActivity,
                            "Register success",
                            Toast.LENGTH_LONG
                        ).show()
                    }
    
                    override fun onError(code: String?, error: String?) {
                        Toast.makeText(
                            this@UserRegisterActivity,
                            "Register error->$error",
                            Toast.LENGTH_LONG
                        ).show()
                    }
                }
    
                if (isEmail) {
                    // Register by email
                    ThingHomeSdk.getUserInstance().registerAccountWithEmail(
                        strCountryCode,
                        strAccount,
                        strPassword,
                        strCode,
                        callback
                    )
                } else {
                    // Register by phone
                    ThingHomeSdk.getUserInstance().registerAccountWithPhone(
                        strCountryCode,
                        strAccount,
                        strPassword,
                        strCode,
                        callback
                    )
                }
    
            } else if (it == R.id.btnCode) {
                // Get verification code code
                ThingHomeSdk.getUserInstance().sendVerifyCodeWithUserName(
                    strAccount,
                    "",
                    strCountryCode,
                    mRegisterType,
                    object : IResultCallback {
                        override fun onSuccess() {
                            Toast.makeText(
                                this@UserRegisterActivity,
                                "Got validateCode",
                                Toast.LENGTH_LONG
                            ).show()
                        }
    
                        override fun onError(code: String?, error: String?) {
                            Toast.makeText(
                                this@UserRegisterActivity,
                                "getValidateCode error->$error",
                                Toast.LENGTH_LONG
                            ).show()
                        }
    
                    })
            }
        }
      }
    }
    

    Preview:

    User Registration and Login

User login

  1. Create a new Activity named UserLoginActivity.

     <?xml version="1.0" encoding="utf-8"?>
     <androidx.coordinatorlayout.widget.CoordinatorLayout
        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="match_parent">
    
    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    
        <com.google.android.material.appbar.MaterialToolbar
            android:id="@+id/topAppBar"
            style="@style/Widget.MaterialComponents.Toolbar.Primary"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:navigationIcon="?attr/homeAsUpIndicator"
            app:title="@string/user_login" />
    
    </com.google.android.material.appbar.AppBarLayout>
    
    <androidx.core.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">
    
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:padding="20dp">
    
            <com.google.android.material.textfield.TextInputLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="4dp"
                android:layout_marginTop="20dp"
                android:hint="@string/user_country_code"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toTopOf="parent">
    
                <com.google.android.material.textfield.TextInputEditText
                    android:id="@+id/etCountryCode"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content" />
            </com.google.android.material.textfield.TextInputLayout>
    
            <com.google.android.material.textfield.TextInputLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="4dp"
                android:hint="@string/user_account_tips"
                app:endIconMode="clear_text"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toTopOf="parent">
    
                <com.google.android.material.textfield.TextInputEditText
                    android:id="@+id/etAccount"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content" />
            </com.google.android.material.textfield.TextInputLayout>
    
            <com.google.android.material.textfield.TextInputLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="4dp"
                android:hint="@string/user_password"
                app:endIconMode="clear_text"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toTopOf="parent">
    
                <com.google.android.material.textfield.TextInputEditText
                    android:id="@+id/etPassword"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content" />
            </com.google.android.material.textfield.TextInputLayout>
    
            <Button
                android:id="@+id/btnLogin"
                android:layout_width="match_parent"
                android:layout_height="48dp"
                android:layout_marginTop="10dp"
                android:text="@string/user_login" />
        </LinearLayout>
    
    </androidx.core.widget.NestedScrollView>
    </androidx.coordinatorlayout.widget.CoordinatorLayout>
    
    
  2. After registration, go back to the splash screen and open the login page. Here is the example code for the user login logic:

    class UserLoginActivity : AppCompatActivity(), View.OnClickListener {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.user_activity_login)
    
        val toolbar: Toolbar = findViewById<View>(R.id.topAppBar) as Toolbar
        toolbar.setNavigationOnClickListener {
            finish()
        }
    
        findViewById<Button>(R.id.btnLogin).setOnClickListener(this)
    }
    
    override fun onClick(v: View?) {
        val strAccount = findViewById<EditText>(R.id.etAccount).text.toString()
        val strCountryCode = findViewById<EditText>(R.id.etCountryCode).text.toString()
        val strPassword = findViewById<EditText>(R.id.etPassword).text.toString()
    
        v?.id?.let {
            if (it == R.id.btnLogin) {
                // Login with phone
              val callback =  object : ILoginCallback {
                    override fun onSuccess(user: User?) {
                        Toast.makeText(
                            this@UserLoginActivity,
                            "Login success",
                            Toast.LENGTH_LONG
                        ).show()
    
                        startActivity(
                            Intent(
                                this@UserLoginActivity,
                                MainActivity::class.java
                            )
                        )
                    }
    
                    override fun onError(code: String?, error: String?) {
                        Toast.makeText(
                            this@UserLoginActivity,
                            "login error->$error",
                            Toast.LENGTH_LONG
                        ).show()
                    }
                }
                if (ValidatorUtil.isEmail(strAccount)) {
                    ThingHomeSdk.getUserInstance()
                        .loginWithEmail(strCountryCode, strAccount, strPassword, callback)
                } else {
                    ThingHomeSdk.getUserInstance()
                        .loginWithPhonePassword(strCountryCode, strAccount, strPassword, callback)
                }
            }
        }
     }
    }
    

    Preview:

    User Registration and Login