Open In App

Android AudioManager in Kotlin

Last Updated : 01 Aug, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Audio Manager is a class present in Android that helps manage the audio of the specific android device. The name of the class audio manager itself tells us that it is used to manage audio. The Audio Manager class is used to change the audio mode in different modes such as normal, silent, and vibrate mode. In this article, we will be creating a simple android application to change the audio mode of android devices. A sample video is given below to get an idea about what we are going to do in this article.

Note: If you are looking to implement the Audio Manager in the android application using Java. Check out the following article: Audio Manager in Android using Java

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. Note that select Kotlin as the programming language.

Step 2: Add permissions in the AndroidManifest.xml file

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

XML




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


Step 3: Adding icons to the drawable folder 

Navigate to the app > drawable folder > Right-click on it > New > Vector Asset > Select the icon and simply click on finish to add that icon. 

Step 4: Working with the activity_main.xml file

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail.

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
 
    <!-- Textview to display the heading of the app-->
    <TextView
        android:id="@+id/idTVHeading"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="50dp"
        android:layout_marginRight="20dp"
        android:gravity="center"
        android:padding="5dp"
        android:text="Ringtone Manager Application"
        android:textAlignment="center"
        android:textColor="@color/purple_200"
        android:textSize="20sp"
        android:textStyle="bold" />
 
    <!-- Textview to display the current mode
         of the Ringer mode-->
    <TextView
        android:id="@+id/idTVCurrentMode"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/idTVHeading"
        android:layout_marginTop="60dp"
        android:gravity="center"
        android:padding="4dp"
        android:text="Current Mode"
        android:textAlignment="center"
        android:textAllCaps="true"
        android:textColor="@color/purple_200"
        android:textSize="20sp"
        android:textStyle="bold" />
 
    <!--on below line we are creating a horizontal
         linear layout for our 3 buttons-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/idTVCurrentMode"
        android:layout_marginTop="80dp"
        android:orientation="horizontal"
        android:weightSum="3">
 
        <!--on below line we are creating
            image button for vibrate mode-->
        <ImageButton
            android:id="@+id/idIBVibrateMode"
            android:layout_width="0dp"
            android:layout_height="100dp"
            android:layout_margin="10dp"
            android:layout_weight="1"
            android:background="@color/purple_200"
            android:contentDescription="Vibrate Mode"
            android:src="@drawable/ic_vibrate"
            android:tint="@color/white" />
 
        <!--on below line we are creating image
            button for silent mode-->
        <ImageButton
            android:id="@+id/idIBSilentMode"
            android:layout_width="0dp"
            android:layout_height="100dp"
            android:layout_margin="10dp"
            android:layout_weight="1"
            android:background="@color/purple_200"
            android:contentDescription="Silent Mode"
            android:src="@drawable/ic_silent_mode"
            android:tint="@color/white" />
 
        <!--on below line we are creating
            image button for ringer mode-->
        <ImageButton
            android:id="@+id/idIBRingtoneMode"
            android:layout_width="0dp"
            android:layout_height="100dp"
            android:layout_margin="10dp"
            android:layout_weight="1"
            android:background="@color/purple_200"
            android:contentDescription="Ring Mode"
            android:src="@drawable/ic_ringtone_mode"
            android:tint="@color/white" />
    </LinearLayout>
 
</RelativeLayout>


Step 5: 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.gtappdevelopers.kotlingfgproject
 
import android.app.NotificationManager
import android.content.Context
import android.content.Intent
import android.media.AudioManager
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import android.widget.ImageButton
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
 
class MainActivity : AppCompatActivity() {
 
    // on below line we are creating variable for
    // text view, image button and audio manager.
    lateinit var currentModeTV: TextView
    lateinit var vibrateIB: ImageButton
    lateinit var silentIB: ImageButton
    lateinit var ringerIB: ImageButton
    lateinit var audioManager: AudioManager
     
    // on below line we are creating an integer
    // variable to get the current audio mode.
    var currentAudioMode = 0
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
         
        // on below line we are initializing
        // image buttons and text view.
        vibrateIB = findViewById(R.id.idIBVibrateMode)
        silentIB = findViewById(R.id.idIBSilentMode)
        ringerIB = findViewById(R.id.idIBRingtoneMode)
        currentModeTV = findViewById(R.id.idTVCurrentMode)
         
        // on below line we are initializing our audio manager.
        audioManager = 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 -> currentModeTV.setText("Ringer Mode")
             
            // on below line we are setting silent mode for current silent mode.
            AudioManager.RINGER_MODE_SILENT -> currentModeTV.setText("Silent Mode")
             
            // on below line we are setting vibrate mode for current vibrate mode.
            AudioManager.RINGER_MODE_VIBRATE -> currentModeTV.setText("Vibrate Mode")
             
            // below code will be called when the current mode is not able to detect
            else -> currentModeTV.setText("Fail to get mode")
        }
 
        // on below line we are setting on click
        // listener for our silent image button.
        silentIB.setOnClickListener {
            // on below line we are initializing our notification manager.
            val notificationManager: NotificationManager =
                getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
             
            // on below line we are creating a variable for intent.
            val 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.
                     
                      Intent(Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS)
                    // on below line we are simply calling start activity
                    // to start the activity.
                    startActivity(intent)
                } else {
                    Log.e("tag", "Audio Manager not accessible..")
                    // on 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(this@MainActivity, "Silent Mode activated..", Toast.LENGTH_SHORT)
                        .show()
                     
                    // on below line we are setting current mode text as silent mode.
                    currentModeTV.text = "Silent Mode Activated.."
                }
        }
 
        // on below line we are adding on click listener for vibrate image button.
        vibrateIB.setOnClickListener {
            // on below line we are setting ringer mode for audio manager
            // as ringer mode vibrate
            audioManager.ringerMode = AudioManager.RINGER_MODE_VIBRATE
             
            // on below line we are displaying a toast message as vibrate mode activated.
            Toast.makeText(this@MainActivity, "Vibrate Mode activated..", Toast.LENGTH_SHORT).show()
             
            // on below line we are setting current mode
            // text view to vibrate mode activated.
            currentModeTV.text = "Vibrate Mode Activated.."
        }
 
        // on below line we are adding on click listener
        // for our ringer image button.
        ringerIB.setOnClickListener {
            // on below line we are setting ringer mode as normal ringer mode.
            audioManager.ringerMode = AudioManager.RINGER_MODE_NORMAL
             
            // on below line we are displaying a toast message and
            // setting current mode text view.
            Toast.makeText(this@MainActivity, "Ringer Mode activated..", Toast.LENGTH_SHORT).show()
            currentModeTV.text = "Ringtone Mode Activated.."
        }
 
    }
}


Now run your application to see the output of it. 

Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads