android kotlin - Set ringer volume programmatically

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.app.Activity
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.widget.*
import kotlin.random.Random


class MainActivity : Activity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // get the widgets reference from XML layout
        val button = findViewById<Button>(R.id.button)


        // Get the audio manager system service
        val audioManager: AudioManager =
            getSystemService(AUDIO_SERVICE) as AudioManager


        // get the notification manager system service
        val notificationManager =
            getSystemService(NOTIFICATION_SERVICE) as NotificationManager


        // Click listener for button widget
        button.setOnClickListener {
            if (notificationManager.isDoNotDisturbAccessGranted()){
                //toast("Notification policy access granted.")

                // Get the maximum ringer volume
                val maxVolume = audioManager.ringerMaxVolume

                // Get a random volume index in a range
                //val randomIndex = Random.nextInt(((maxVolume - 0) + 1) + 0)
                val randomIndex = Random.nextInt(0,maxVolume+1)

                // Set the ringer volume programmatically
                //audioManager.setRingerVolume(maxVolume)
                audioManager.setRingerVolume(randomIndex)

                // Show volume index in a toast message
                toast("Max: $maxVolume / Current: " +
                        "${audioManager.ringerCurrentVolume}")
            }else{
                toast("You need to grant notification policy access.")
                // If notification policy access not granted for this package
                val intent = Intent(
                    Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS)
                startActivity(intent)
            }
        }
    }
}



// Extension function to check notification
// policy access permission status
private fun NotificationManager
        .isDoNotDisturbAccessGranted():Boolean =
    this.isNotificationPolicyAccessGranted



// Extension function to change ringer volume programmatically
fun AudioManager.setRingerVolume(volumeIndex:Int) {
    // Set ringer volume level
    this.setStreamVolume(
        AudioManager.STREAM_RING, // Stream type
        volumeIndex, // Volume index
        AudioManager.FLAG_SHOW_UI// Flags
    )
}



// Extension property to get ringer maximum volume index
val AudioManager.ringerMaxVolume:Int
    get() = this.getStreamMaxVolume(AudioManager.STREAM_RING)



// Extension property to get ringer current volume index
val AudioManager.ringerCurrentVolume:Int
    get() = this.getStreamVolume(AudioManager.STREAM_RING)



// Extension function to show toast message
fun Context.toast(message: String) {
    Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#DCDCDC"
    android:padding="24dp">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Set Ringer Volume"
        android:textAllCaps="false"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
AndroidManifest.xml [Permission]

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