Saturday, August 5, 2017

android - Set ringer volume programmatically

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    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:id="@+id/root_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    android:orientation="vertical"
    android:background="#f44061"
    >
    <TextView
        android:id="@+id/tv_stats"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="22sp"
        android:padding="10dp"
        />
    <Button
        android:id="@+id/btn_ringer_volume"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Set Ringer Volume"
        />
</LinearLayout>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.app.Activity;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Build;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Random;


public class MainActivity extends AppCompatActivity {
    private Context mContext;
    private Activity mActivity;

    private LinearLayout mRootLayout;
    private Button mBtnRingerVolume;
    private TextView mTVStats;

    Random mRandom = new Random();

    private NotificationManager mNotificationManager;
    private AudioManager mAudioManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Get the application context
        mContext = getApplicationContext();
        mActivity = MainActivity.this;

        // Get the widget reference from xml layout
        mRootLayout = findViewById(R.id.root_layout);
        mTVStats = findViewById(R.id.tv_stats);
        mBtnRingerVolume = findViewById(R.id.btn_ringer_volume);

        // Get the notification manager instance
        mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        // Get the audio manager instance
        mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);

        mBtnRingerVolume.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // If do not disturb mode on, then off it first
                turnOffDoNotDisturbMode();

                // Get the ringer current volume level
                int current_volume_level = mAudioManager.getStreamVolume(AudioManager.STREAM_RING);

                // Get the ringer maximum volume
                int max_volume_level = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_RING);

                // Get a random volume level in specified range
                int random_volume = mRandom.nextInt(((max_volume_level-0)+1)+0);

                // Set the ringer volume
                mAudioManager.setStreamVolume(
                        AudioManager.STREAM_RING,
                        random_volume,
                        AudioManager.FLAG_SHOW_UI
                );

                // Display the updated status on text view
                mTVStats.setText("Ringer Current Volume : " + current_volume_level);
                mTVStats.append("\nRinger Max Volume : " + max_volume_level);
                mTVStats.append("\nRinger new volume : " + random_volume);
            }
        });
    }

    // Custom method to turn off do not disturb mode programmatically
    protected void turnOffDoNotDisturbMode(){
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){ // If api level minimum 23
            // If notification policy access granted for this package
            if(mNotificationManager.isNotificationPolicyAccessGranted()){{
                if(mAudioManager.getStreamVolume(AudioManager.STREAM_RING)== 0){
                    // If do not disturb mode on, then off it
                    // Set the interruption filter to all, allow all notification
                    mNotificationManager.setInterruptionFilter(mNotificationManager.INTERRUPTION_FILTER_NONE);
                    // Show a toast
                    Toast.makeText(mContext,"Turn OFF Do Not Disturb Mode",Toast.LENGTH_SHORT).show();
                }
            }
            }else {
                // Show a toast
                Toast.makeText(mContext,"Going to get grant access",Toast.LENGTH_SHORT).show();

                // If notification policy access not granted for this package
                Intent intent = new Intent(Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);
                startActivity(intent);
            }
        }
    }
}
AndroidManifest.xml [Permission]

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