La gestión de sesiones es una de las funciones más importantes que se utilizarán en la aplicación de Android cuando integre la función de inicio de sesión en Android. En su aplicación de Android, si está utilizando una función de inicio de sesión, debe guardar el estado si el usuario ha iniciado sesión por primera vez. Luego, cuando el usuario cierra su aplicación y la vuelve a abrir, debe redirigir a nuestra pantalla de inicio, en lugar de abrir una pantalla de inicio de sesión. Usaremos preferencias compartidas para administrar la sesión del usuario dentro de la aplicación de Android. En este artículo, implementaremos la administración de sesiones en la aplicación de Android usando Jetpack Compose .
Implementación paso a paso
Paso 1: crea un nuevo proyecto en Android Studio
Para crear un nuevo proyecto en Android Studio, consulte Cómo crear/iniciar un nuevo proyecto en Android Studio . Al elegir la plantilla, seleccione Actividad de composición vacía . Si no encuentra esta plantilla, intente actualizar Android Studio a la última versión. Demostramos la aplicación en Kotlin, así que asegúrese de seleccionar Kotlin como idioma principal al crear un nuevo proyecto.
Paso 2: Agregar un nuevo color en el archivo Color.kt
Vaya a aplicación > java > nombre del paquete de su aplicación > ui.theme > archivo Color.kt y agréguele el siguiente código. Se agregan comentarios en el código para conocer en detalle.
Kotlin
package com.example.newcanaryproject.ui.theme import androidx.compose.ui.graphics.Color val Purple200 = Color(0xFF0F9D58) val Purple500 = Color(0xFF0F9D58) val Purple700 = Color(0xFF3700B3) val Teal200 = Color(0xFF03DAC5) // on below line we are adding different colors val greenColor = Color(0xFF0F9D58)
Paso 3: Crear una nueva MainActivity2
Vaya a la aplicación > java > el nombre del paquete de su aplicación > haga clic con el botón derecho en él > Nuevo > Actividad > Galería > Seleccione Vaciar la actividad de redacción y asigne a la actividad el nombre de archivo MainActivity2.kt.
Paso 4: trabajar con el archivo MainActivity.kt
Vaya al archivo MainActivity.kt y consulte el siguiente código. A continuación se muestra el código del archivo MainActivity.kt . Se agregan comentarios dentro del código para comprender el código con más detalle.
Kotlin
package com.example.newcanaryproject import android.app.Activity import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.os.Bundle import android.util.Log import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.* import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Email import androidx.compose.material.icons.filled.Password import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.text.input.TextFieldValue import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.* import com.example.newcanaryproject.ui.theme.* class MainActivity : ComponentActivity() { // on below line we are creating // a variable for shared preferences. lateinit var sharedPreferences: SharedPreferences // on below line we are creating a variable // for prefs key and email key and pwd key. var PREFS_KEY = "prefs" var EMAIL_KEY = "email" var PWD_KEY = "pwd" // on below line we are creating variable // for email as e and password as p. var e = "" var p = "" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { // on below line we are initializing our shared preferences. sharedPreferences = getSharedPreferences(PREFS_KEY, Context.MODE_PRIVATE) // on below line we are creating // variable for email and password. val email = remember { mutableStateOf("") } val pwd = remember { mutableStateOf("") } // on below line we are initializing values for both email and password. email.value = sharedPreferences.getString(EMAIL_KEY, "").toString() pwd.value = sharedPreferences.getString(PWD_KEY, "").toString() // on below line we are setting value // from email and password to e and p e = email.value p = pwd.value NewCanaryProjectTheme { // on below line we are specifying background // color for our application Surface( // on below line we are specifying // modifier and color for our app modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background ) { // on below line we are specifying theme as scaffold. Scaffold( // in scaffold we are specifying top bar. topBar = { // inside top bar we are specifying background color. TopAppBar(backgroundColor = greenColor, // along with that we are specifying title // for our top bar. title = { // in the top bar we are specifying tile as a text Text( // on below line we are specifying text to display in top app bar. text = "Session Management in Android", // on below line we are specifying modifier to fill max width. modifier = Modifier.fillMaxWidth(), // on below line we are specifying text alignment. textAlign = TextAlign.Center, // on below line we are specifying color for our text. color = Color.White ) } ) } ) { // on below line we are calling session management // method and passing shared preferences to it. sessionManagement(sharedPreferences) } } } } } // on below line we are calling on start method. override fun onStart() { super.onStart() // on below line we are creating a variable for activity. val activity = (this as? Activity) // on below line we are initializing our shared preferences. sharedPreferences = getSharedPreferences(PREFS_KEY, Context.MODE_PRIVATE) // on below line we are initializing our email and pwd // variable setting values from shared preferences. val email = sharedPreferences.getString(EMAIL_KEY, "").toString() val pwd = sharedPreferences.getString(PWD_KEY, "").toString() // on below line we are checking if email and pwd are empty or not. if (email != "" && pwd != "") { // if email and pwd are not empty we are opening // a new activity on below line. val i = Intent(this, MainActivity2::class.java) // on below line we are starting our new activity // and finishing our current activity. startActivity(i) activity?.finish() } } } // on below line we are creating a function for session management @Composable fun sessionManagement(sharedPreferences: SharedPreferences) { // on below line we are creating a variable for // context and activity and initializing it. val ctx = LocalContext.current val activity = (LocalContext.current as? Activity) // on below line we are creating and // initializing email value and pwd value val emailValue = remember { mutableStateOf(TextFieldValue()) } val pwdValue = remember { mutableStateOf(TextFieldValue()) } // on the below line we are creating a column. Column( // on below line we are adding a modifier to it // and setting max size, max height and max width modifier = Modifier .fillMaxSize() .fillMaxHeight() .fillMaxWidth(), // on below line we are adding vertical // arrangement and horizontal alignment. verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { // on below line we are creating a text Text( // on below line we are specifying text as // Session Management in Android. text = "Session Management in Android", // on below line we are specifying text color. color = greenColor, // on below line we are specifying font family fontFamily = FontFamily.Default, // on below line we are adding font weight // and alignment for our text fontWeight = FontWeight.Bold, textAlign = TextAlign.Center ) // on below line we are creating a text field for our email. TextField( // on below line we are specifying value for our email text field. value = emailValue.value, // on below line we are adding on value change for text field. onValueChange = { emailValue.value = it }, // on below line we are adding place holder as text as "Enter your email" placeholder = { Text(text = "Enter your email") }, // on below line we are adding modifier to it // and adding padding to it and filling max width modifier = Modifier .padding(16.dp) .fillMaxWidth(), // on below line we are adding text style // specifying color and font size to it. textStyle = TextStyle(color = Color.Black, fontSize = 15.sp), // on below line we are adding single line to it. singleLine = true, // on below line we are specifying leading icon as email leadingIcon = { Icon(imageVector = Icons.Default.Email, contentDescription = "Email") } ) // on below line we are creating a text field for password. TextField( // on below line we are specifying value for our password as pwdValue. value = pwdValue.value, // on below line we are specifying on value change for it. onValueChange = { pwdValue.value = it }, // on below line we are adding place holder to it as enter your password. placeholder = { Text(text = "Enter your password") }, // on below line we are adding modifier to it and padding to it. modifier = Modifier .padding(16.dp) .fillMaxWidth(), // on below line we are adding text style for our text and font size. textStyle = TextStyle(color = Color.Black, fontSize = 15.sp), // on below line we are adding single line to it. singleLine = true, // on below line we are adding visual // transformation it obscure the password. visualTransformation = PasswordVisualTransformation(), // on below line we are adding leading icon to it. leadingIcon = { Icon(imageVector = Icons.Default.Password, contentDescription = "Email") } ) // on the below line we are adding a button for login. Button( // on below line we are adding modifier to // it for adding padding and max width. modifier = Modifier .fillMaxWidth() .padding(16.dp), // on below line we are adding on click to this button. onClick = { // on below line we are calling save data method // to save data to shared preferences. saveData(emailValue.value.text, pwdValue.value.text, sharedPreferences, ctx) // on the below line we are calling finish to close the current activity. activity?.finish() }, // on below line we are adding color to our button. colors = ButtonDefaults.buttonColors( backgroundColor = greenColor, ) ) // on the below line we are adding text as login. { Text(text = "Login") } } } // on below line we are creating a function as save data // to save data in our shared preferences. fun saveData(email: String, pwd: String, sharedPreferences: SharedPreferences, context: Context) { // on below line we are creating an editor and initializing // it with shared preferences. val editor: SharedPreferences.Editor = sharedPreferences.edit() // on below line we are setting email and pwd value with key. editor.putString("email", email) editor.putString("pwd", pwd) // on the below line we are applying // changes to our shared prefs. editor.apply() // on below line we are opening a new intent. val i = Intent(context, MainActivity2::class.java) context.startActivity(i) }
Paso 5: trabajar con el archivo MainActivity2.kt
Vaya al archivo MainActivity2.kt y consulte el siguiente código. A continuación se muestra el código del archivo MainActivity2.kt . Se agregan comentarios dentro del código para comprender el código con más detalle.
Kotlin
package com.example.newcanaryproject import android.app.Activity import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.* import androidx.compose.material.* import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.newcanaryproject.ui.theme.NewCanaryProjectTheme import com.example.newcanaryproject.ui.theme.greenColor class MainActivity2 : ComponentActivity() { // on below line we are creating a variable for our shared preferences. lateinit var sharedPreferences: SharedPreferences // on below line we are creating a variable // for prefs key and email key and pwd key. var PREFS_KEY = "prefs" var EMAIL_KEY = "email" // on below line we are creating a variable for email var email = "" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // on below line we are initializing our shared preferences. sharedPreferences = getSharedPreferences(PREFS_KEY, Context.MODE_PRIVATE) // on below line we are initializing our email from shared preferences. email = sharedPreferences.getString(EMAIL_KEY, "").toString() setContent { NewCanaryProjectTheme { // on below line we are specifying // background color for our application Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background ) { // on below line we are specifying theme as scaffold. Scaffold( // in scaffold we are specifying top bar. topBar = { // inside top bar we are specifying background color. TopAppBar(backgroundColor = greenColor, // along with that we are specifying title for our top bar. title = { // in the top bar we are specifying tile as a text Text( // on below line we are specifying text to display in top app bar. text = "Session Management in Android", // on below line we are specifying modifier to fill max width. modifier = Modifier.fillMaxWidth(), // on below line we are specifying text alignment. textAlign = TextAlign.Center, // on below line we are specifying color for our text. color = Color.White ) } ) } ) { // on below line we are calling get data and passing email and shared preferences to it. getData(email, sharedPreferences) } } } } } } // on below line we are creating a get data method. @Composable fun getData(email: String, sharedPreferences: SharedPreferences) { // on below line we are creating and initializing // our context variable and activity. val ctx = LocalContext.current val activity = (LocalContext.current as? Activity) // on below line we are creating a column Column( // inside the column we are adding modifier // and specifying max height, max width and max size. modifier = Modifier .fillMaxWidth() .fillMaxHeight() .fillMaxSize(), // on below line we are specifying // vertical arrangement for our column. verticalArrangement = Arrangement.Center, // on below line we are specifying horizontal alignment for our column. horizontalAlignment = Alignment.CenterHorizontally ) { // on below line we are creating a text for displaying user name Text( // on below line we are specifying text in our text text = "Welcome \n" + email, // on below line we are specifying font weight for our text fontWeight = FontWeight.Bold, // on below line we are adding green color to it. color = greenColor, // on below line we are specifying font size to it. fontSize = 20.sp, // on below line we are adding alignment for our text textAlign = TextAlign.Center ) // on below line we are adding spacer between text and button. Spacer(modifier = Modifier.height(50.dp)) // on below line we are adding button. Button( // on below line we are adding modifier to // fill max width and adding padding to it. modifier = Modifier .fillMaxWidth() .padding(16.dp), // on below line we are adding on click for our button. onClick = { // on below line we are creating a variable for our editor. val editor: SharedPreferences.Editor = sharedPreferences.edit() // on below line we are passing email and pwd with empty values. editor.putString("email", "") editor.putString("pwd", "") // on below line we are applying changes which are updated. editor.apply() // on below line we are opening our main activity. val i = Intent(ctx, MainActivity::class.java) ctx.startActivity(i) activity?.finish() }, // on below line we are adding color for out button colors = ButtonDefaults.buttonColors( backgroundColor = greenColor, ) ) { // on below line we are adding text for our button. Text(text = "Log Out") } } }
Ahora ejecute su aplicación para ver el resultado.
Producción:
Publicación traducida automáticamente
Artículo escrito por chaitanyamunje y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA