Thursday, April 19, 2018

android kotlin - Set ringer volume programmatically

MainActivity.kt

package com.cfsuman.kotlinexamples

import android.app.NotificationManager
import android.content.Context
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
import android.media.AudioManager
import android.widget.Toast
import java.util.*
import android.content.Intent
import android.os.Build
import android.provider.Settings


class MainActivity : AppCompatActivity() {


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

        // 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_volume.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)

                // 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{
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
        return if (this.isNotificationPolicyAccessGranted){
            true
        }else{
            return false
        }
    }
    return true
}


// 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"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/root_layout"
    android:background="#99ab88"
    android:padding="16dp"
    android:orientation="vertical"
    >
    <Button
        android:id="@+id/button_volume"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Set Ringer Volume"
        android:layout_gravity="center_horizontal"
        android:layout_margin="10dp"
        />
</LinearLayout>
AndroidManifest.xml [Permission]

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