Open In App

Android AudioManager using Jetpack Compose

Improve
Improve
Like Article
Like
Save
Share
Report

Audio Manager the name itself tells us that it is used to manage the audio controls of the android device. Audio Manager is a class within the android that is used to change the mode audio mode of the android devices into silent, general, and vibrate modes. In this article, we will be building a simple application in which we will be changing the audio mode of the device by simply clicking on the buttons. We will be building this application using Jetpack Compose

Step by Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. While choosing the template, select Empty Compose Activity. If you do not find this template, try upgrading the Android Studio to the latest version. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.

Step 2: Adding and updating colors in the Color.kt file

Navigate to app > java > your app’s package name > ui.theme folder > Color.kt file and add the below code to it. Comments are added in the code to get to know in more detail. 

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)


Step 3: Adding permission for accessing notification policy in AndroidManifest.xml

Navigate to app> manifest > AndroidManifest.xml and add the below permission in the manifest tag.

XML




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


Step 4: Working with the MainActivity.kt file

Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.

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 title 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 accessible..")
                     
                    // 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)
        }
 
    }
 
}


Now run your application to see the output of it. 

Output: 



Last Updated : 06 Jan, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads