MainActivity.kt
package com.cfsuman.kotlintutorials
import android.app.Activity
import android.content.Context
import android.media.AudioManager
import android.os.Bundle
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
// Click listener for button widget
button.setOnClickListener {
// Get the maximum media/music volume
val maxVolume = audioManager.mediaMaxVolume
// 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 media/music volume programmatically
//audioManager.setMediaVolume(maxVolume)
audioManager.setMediaVolume(randomIndex)
// Show volume index in a toast message
toast("Max: $maxVolume / Current: " +
"${audioManager.mediaCurrentVolume}")
}
}
}
// Extension function to change media volume programmatically
fun AudioManager.setMediaVolume(volumeIndex:Int) {
// Set media volume level
this.setStreamVolume(
AudioManager.STREAM_MUSIC, // Stream type
volumeIndex, // Volume index
AudioManager.FLAG_SHOW_UI// Flags
)
}
// Extension property to get media maximum volume index
val AudioManager.mediaMaxVolume:Int
get() = this.getStreamMaxVolume(AudioManager.STREAM_MUSIC)
// Extension property to get media/music current volume index
val AudioManager.mediaCurrentVolume:Int
get() = this.getStreamVolume(AudioManager.STREAM_MUSIC)
// 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 Media 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>