Administrador de audio de Android con Jetpack Compose

Audio Manager el propio nombre nos dice que se utiliza para gestionar los controles de audio del dispositivo android. Audio Manager es una clase dentro de Android que se utiliza para cambiar el modo de audio de los dispositivos Android a los modos silencioso, general y de vibración. En este artículo, construiremos una aplicación simple en la que cambiaremos el modo de audio del dispositivo simplemente haciendo clic en los botones. Construiremos esta aplicación utilizando 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 y actualizar colores en el archivo Color.kt

Vaya a aplicación > java > nombre del paquete de su aplicación > carpeta ui.theme > archivo Color.kt y agréguele el siguiente código. Se agregan comentarios en el código para conocer con más 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: Agregar permiso para acceder a la política de notificación en AndroidManifest.xml

Vaya a aplicación> manifiesto> AndroidManifest.xml y agregue el siguiente permiso en la etiqueta del manifiesto.

XML

<uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY" />

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.app.NotificationManager
import android.content.Context
import android.content.Intent
import android.graphics.Typeface
import android.media.AudioManager
import android.os.Bundle
import android.provider.Settings
  
import android.speech.RecognizerIntent
import android.speech.SpeechRecognizer
import android.util.Log
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.annotation.Dimension.DP
import androidx.compose.animation.Crossfade
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Mic
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.layout.layoutId
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.dimensionResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.*
import androidx.compose.ui.viewinterop.AndroidView
import androidx.constraintlayout.compose.ConstraintSet
import androidx.constraintlayout.compose.MotionLayout
import androidx.core.content.ContextCompat.getSystemService
import androidx.core.content.ContextCompat.startActivity
import com.example.newcanaryproject.ui.theme.*
import com.github.mikephil.charting.charts.PieChart
import com.github.mikephil.charting.components.Description
import com.github.mikephil.charting.components.Legend
import com.github.mikephil.charting.data.PieData
import com.github.mikephil.charting.data.PieDataSet
import com.github.mikephil.charting.data.PieEntry
import org.intellij.lang.annotations.JdkConstants.HorizontalAlignment
import java.util.*
  
class MainActivity : ComponentActivity() {
  
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        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 = "Audio Manager Example",
                                          
                                        // 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 
                        // our audio manager ui
                        AudioManagerUI()
                    }
                }
            }
        }
    }
}
  
@OptIn(ExperimentalUnitApi::class)
@Composable
fun AudioManagerUI() {
    // on below line we are creating variable for 
    // audio manager, current audio mode and current
    // mode string to store current mode.
    lateinit var audioManager: AudioManager
    var currentAudioMode = 0
    var currentModeString = remember {
        mutableStateOf("")
    }
    // on below line we are creating a 
    // variable to get current context.
    var ctx = LocalContext.current
      
    // on below line we are initializing our audio manager.
    audioManager = ctx.getSystemService(Context.AUDIO_SERVICE) as AudioManager
      
    // on below line we are getting our current ring tone mode.
    currentAudioMode = audioManager.ringerMode;
  
    // on below line we are setting text view for the current mode.
    when (currentAudioMode) {
        // on below line we are setting text view as ringer mode for normal ringer mode.
        AudioManager.RINGER_MODE_NORMAL -> currentModeString.value = "Ringer Mode"
          
        // on the below line we are setting silent mode for the current silent mode.
        AudioManager.RINGER_MODE_SILENT -> currentModeString.value = "Silent Mode"
          
        // on the below line we are setting vibrate mode for the current vibrate mode.
        AudioManager.RINGER_MODE_VIBRATE -> currentModeString.value = "Vibrate Mode"
          
        // below code will be called when the current mode is not able to detect
        else -> currentModeString.value = "Fail to get mode"
    }
  
    // on below line we are creating a column
    Column(
        // on below line we are specifying modifier 
        // for column to fill max height and width,
        modifier = Modifier
            .fillMaxWidth()
            .fillMaxHeight(),
        // on below line we are specifying vertical 
        // and horizontal arrangement to center.
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        // on below line we are adding spacer
        Spacer(modifier = Modifier.height(20.dp))
        // on below line we are creating a simple text
        Text(
            // on below line we are specifying text 
            // as RIngtone Manager application
            text = "Ringtone Manager Application",
              
            // on below line we are setting color.
            color = greenColor,
              
            // on below line we are setting font size.
            fontSize = TextUnit(value = 18F, type = TextUnitType.Sp)
        )
        // on the below line we are adding a spacer.
        Spacer(modifier = Modifier.height(20.dp))
        // on below line we are creating a 
        // text to display current ringtone mode.
        Text(
            // on below line we are specifying
            // current mode from string
            text = currentModeString.value,
              
            // on below line we are setting text color.
            color = greenColor,
              
            // on below line we are setting font size.
            fontSize = TextUnit(value = 18F, type = TextUnitType.Sp)
        )
        // on the below line we are adding a spacer.
        Spacer(modifier = Modifier.height(20.dp))
          
        // on below line we are creating
        // a button  for vibrate mode.
        Button(
            // on below line we are adding width for the button
            modifier = Modifier.width(200.dp),
            onClick = {
                // on below line we are setting ringer mode for
                // audio manager as ringer mode vibrate
                audioManager.ringerMode = AudioManager.RINGER_MODE_VIBRATE
                  
                // on the below line we are displaying a toast message as vibrate mode activated.
                Toast.makeText(ctx, "Vibrate mode activated..", Toast.LENGTH_LONG).show()
                  
                // on below line we are updating current mode string value.
                currentModeString.value = "Vibrate Mode Activated"
            },
            // on below line we are setting color for our button
            colors = ButtonDefaults.buttonColors(backgroundColor = greenColor)
        ) {
            // on the below line we are setting text for our button as vibrate mode.
            Text(text = "Vibrate Mode", color = Color.White)
        }
        // on the below line we are adding a spacer for our button.
        Spacer(modifier = Modifier.height(20.dp))
          
        // on below line we are creating a button for silent mode.
        Button(
            modifier = Modifier.width(200.dp),
            onClick = {
                // on below line we are initializing our notification manager.
                val notificationManager: NotificationManager =
                    ctx.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
                  
                // on below line we are creating a variable for intent.
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M && !notificationManager.isNotificationPolicyAccessGranted) {
                    // if notification policy is not granted we are calling this intent on below line.
                    val intent = Intent(Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS)
                      
                    // on below line we are simply calling start activity to start the activity.
                    startActivity(ctx, intent, null)
                } else {
                    Log.e("tag", "Audio Manager not accesible..")
                      
                    // on the below line we are simply updating audio manager ringer mode to silent.
                    audioManager.ringerMode = AudioManager.RINGER_MODE_SILENT
                      
                    // on below line we are displaying a simple toast message.
                    Toast.makeText(ctx, "Silent Mode activated..", Toast.LENGTH_SHORT)
                        .show()
                      
                    // on below line we are setting current mode text as silent mode.
                    currentModeString.value = "Silent Mode Activated.."
                }
            },
            // on below line we are adding color for our button.
            colors = ButtonDefaults.buttonColors(backgroundColor = greenColor)
        ) {
            // on below line we are specifying text for our
            // button with a white color for the text
            Text(text = "Silent Mode", color = Color.White)
        }
        // on below line we are adding a spacer with height 20 dp/
        Spacer(modifier = Modifier.height(20.dp))
          
        // on the below line we are creating a button for ringer mode.
        Button(
              
            // for this button we are specifying 
            // width for button on below line.
            modifier = Modifier.width(200.dp),
            // on below line we are adding on click for our button.
            onClick = {
                // on below line we are setting ringer mode as normal ringer mode.
                audioManager.ringerMode = AudioManager.RINGER_MODE_NORMAL
                  
                // on the below line we are displaying a toast message
                // and setting current mode text view.
                Toast.makeText(ctx, "Ringer Mode activated..", Toast.LENGTH_SHORT).show()
                currentModeString.value = "Ringtone Mode Activated.."
            },
            // on below line we are adding color for our button
            colors = ButtonDefaults.buttonColors(backgroundColor = greenColor)
        ) {
            // on below line we are specifying text
            // for our button with white color.
            Text(text = "Ringer Mode", color = Color.White)
        }
  
    }
  
}

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

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *