Android AudioManager using Jetpack Compose
Last Updated :
06 Jan, 2023
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:
Similar Reads
Play Audio in Android using Jetpack Compose
In Android, a MediaPlayer is used to play media files like audio and video files in the application. The MediaPlayer Class uses the MediaPlayer API for performing various functions like creating a Media Player, playing, pausing, starting, and stopping the media. In this article, we will show you how
3 min read
Button in Android using Jetpack Compose
Jetpack Compose is a new toolkit provided by Google. This is useful for designing beautiful UI designs. A Button is a UI component in Android which is used to navigate between different screens. With the help of a button, the user can interact with your app and perform multiple actions inside your a
3 min read
Building UI Using Jetpack Compose in Android
Jetpack Compose is a modern UI toolkit that is designed to simplify UI development in Android. It consists of a reactive programming model with conciseness and ease of Kotlin programming language. It is fully declarative so that you can describe your UI by calling some series of functions that will
7 min read
Change Button Size in Android Jetpack Compose
In Android, Button is a very common UI element that is used to call a function or perform a task when clicked by the user. A Button by default occupies specific space depending upon the text that it displays. If the Button text is longer or has a larger font size, the Button width, and height increa
3 min read
Pie Chart in Android using Jetpack Compose
Pie Charts are used in many Android applications to display a huge quantity of data in a simple and easy format. This is seen in applications where a huge quantity of data is to be handled. In this article, we will take a look at How to Create a Pie Chart in Android using Jetpack Compose. A sample v
7 min read
Android Jetpack Compose - Manage Audio Focus
Audio focus is important to manage while building an application that plays an audio file within the application. With the help of this, we can again play the audio file from where it was paused originally. In this article, we will take a look at How to manage audio focus in android applications usi
3 min read
Switch Button in Android using Jetpack Compose
A Switch or a Switch Button in Android is a UI element that is used to switch between two states upon click. It can be assumed as a Boolean button with two different values. Some states where you may find a Switch in your Android device can be WIFI ON and OFF, Bluetooth ON and OFF, Dark Mode and Lig
2 min read
Checkbox in Android using Jetpack Compose
The checkbox is a composable function that is used to represent two states of any item in Android. It is used to differentiate an item from the list of items. In this article, we will take a look at the implementation of Simple Checkbox in Android using Jetpack Compose. Attributes of CheckboxAttribu
2 min read
Animating Circle Drawing in Android using Jetpack Compose
In Android, we can create animations of our choice for displaying an entry, in-transit, or exit of an element or a view. The most commonly inbuilt animation is of Circular ProgressBar, where an animator sweeps out a circle indicating the progress of the executed task. A sample video is given below t
2 min read
Color Picker in Android using Jetpack Compose
Color Picker is seen in many paint applications and is used for drawing some components and coloring them. In these applications, we can get to see different color pickers which are used to pick the color and paint that specific component. In this article, we will take a look at How to implement Col
5 min read