Sunday 25 May 2014

Change Volume and Brightness using Seekbar

Seekbar:


The SeekBar is an interactive slider widget that allows the user to select one value from a range of values (from 0-max). As the user moves the slider left or right, the value of the SeekBar will change.
OR
A SeekBar is an extension of ProgressBar that adds a draggable thumb. The user can touch the thumb and drag left or right to set the current progress level or use the arrow keys. Placing focusable widgets to the left or right of a SeekBar is discouraged.

Seekbar is the best control for this kind of functions, where you will let user to select a value from your described range like I am going to use in this tutorial for volume and device screen brightness control.

Seekbar has a nested Interface called OnSeekBarChangeListener, It is a callback that notifies user when the progress level has been changed. This includes changes that were initiated by the user through a touch gesture or arrow key/trackball as well as changes that were initiated programmatically.

OnSeekBarChangeListener has three methods that can be used to get current progress value from seekbar at three states:

onProgressChanged: It notifies that progress level has changed, it is really helpful in this post.

onStartTrackingTouch: It notifies that the user has started touch gesture.

onStopTrackingTouch: It notifies that the user has finished touch gesture.


OutPut:
Change Volume and Brightness using Seekbar outputChange Volume and Brightness using Seekbar outputs
Create new Android Project
Project Name: Sound Brightness Settings
//tested from 2.3.3 to current android sdk 
Build Target: Android 2.3.3   //or greater than that
Application Name: SeekBarDemo
Package Name: com.shaikhhamadali.blogspot.soundbrightnesssettings
Create Layout file: activity_main

1. code of Layout:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >
 
    <TextView
        android:id="@+id/tVBrightness"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="180dp"
        android:text="Brightness: " />

  <TextView
      android:id="@+id/tVVolume"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="130dp"
      android:text="Volume: " />

    <SeekBar
        android:id="@+id/sbVolume"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="150dp" />
    
    <SeekBar
        android:id="@+id/sbBrightness"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="200dp"
        >
    </SeekBar>
 
</RelativeLayout>

2. code of activity:

package com.shaikhhamadali.blogspot.soundbrightnesssettings;

import android.media.AudioManager;
import android.os.Bundle;
import android.provider.Settings.SettingNotFoundException;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.util.Log;
import android.view.Menu;
import android.view.Window;
import android.view.WindowManager.LayoutParams;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.provider.Settings.System;

public class MainActivity extends Activity {
 //TextViews to show details of volume and brightness
 private TextView tVBrightness,tVVolume;
 //SeekBars to set volume and brightness
 private SeekBar sbVolume,sbBrightness;
 //AudioManager object, that will get and set volume
 private AudioManager audioManager;
 //Variable to store brightness value
 private int brightness;
 //Content resolver used as a handle to the system's settings
 private ContentResolver cResolver;
 //Window object, that will store a reference to the current window
 private Window window;
 int maxVolume=1;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  //Suggests an audio stream whose volume should be changed by the hardware volume controls. 
  setVolumeControlStream(AudioManager.STREAM_MUSIC);
  initializeControls();
 }


 private void initializeControls() {
  //get reference of the UI Controls
  sbVolume = (SeekBar) findViewById(R.id.sbVolume);
  sbBrightness = (SeekBar) findViewById(R.id.sbBrightness);
  tVVolume=(TextView)findViewById(R.id.tVVolume);
  tVBrightness = (TextView) findViewById(R.id.tVBrightness);

  try {

   audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
   //set max progress according to volume
   sbVolume.setMax(audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
   //get current volume
   sbVolume.setProgress(audioManager.getStreamVolume(AudioManager.STREAM_MUSIC));
   //Set the seek bar progress to 1
   sbVolume.setKeyProgressIncrement(1);
   //get max volume
   maxVolume=sbVolume.getMax();
   sbVolume.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {}

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {}

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress,
      boolean fromUser) {
     audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, progress, 0);
     //Calculate the brightness percentage
     float perc = (progress /(float)maxVolume)*100;
     //Set the brightness percentage 
     tVVolume.setText("Volume: "+(int)perc +" %");
    }
   });

  } catch (Exception e) {

  }


  //Get the content resolver
  cResolver = getContentResolver();

  //Get the current window
  window = getWindow();

  //Set the seekbar range between 0 and 255
  sbBrightness.setMax(255);
  //Set the seek bar progress to 1
  sbBrightness.setKeyProgressIncrement(1);

  try
  {
   //Get the current system brightness
   brightness = System.getInt(cResolver, System.SCREEN_BRIGHTNESS);
  } 
  catch (SettingNotFoundException e) 
  {
   //Throw an error case it couldn't be retrieved
   Log.e("Error", "Cannot access system brightness");
   e.printStackTrace();
  }

  //Set the progress of the seek bar based on the system's brightness
  sbBrightness.setProgress(brightness);

  //Register OnSeekBarChangeListener, so it can actually change values
  sbBrightness.setOnSeekBarChangeListener(new OnSeekBarChangeListener() 
  {
   public void onStopTrackingTouch(SeekBar seekBar) 
   {
    //Set the system brightness using the brightness variable value
    System.putInt(cResolver, System.SCREEN_BRIGHTNESS, brightness);
    //Get the current window attributes
    LayoutParams layoutpars = window.getAttributes();
    //Set the brightness of this window
    layoutpars.screenBrightness = brightness / (float)255;
    //Apply attribute changes to this window
    window.setAttributes(layoutpars);
   }

   public void onStartTrackingTouch(SeekBar seekBar) 
   {
    //Nothing handled here
   }

   public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) 
   {
    //Set the minimal brightness level
    //if seek bar is 20 or any value below
    if(progress<=20)
    {
     //Set the brightness to 20
     brightness=20;
    }
    else //brightness is greater than 20
    {
     //Set brightness variable based on the progress bar 
     brightness = progress;
    }
    //Calculate the brightness percentage
    float perc = (brightness /(float)255)*100;
    //Set the brightness percentage 
    tVBrightness.setText("Brightness: "+(int)perc +" %");
   }
  });        
 }



}

Manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.shaikhhamadali.blogspot.soundbrightnesssettings"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="9"
        android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.WRITE_SETTINGS"></uses-permission>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.shaikhhamadali.blogspot.soundbrightnesssettings.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

3. note that:

  • Good practice is to always get the current values of sound and brightness and their max values from settings to let seekbar work accordingly.
  • Above I have used two methods onProgressChanged and onStopTrackingTouch, but you can use three of them according to your need project needs.
  • Before running this, must add WRITE_SETTINGS permission in manifest.
  • you may be interested in these post on playing with settings, ENABLE/DISABLE MOBILE DATA,BLUETOOTH,AIRPLANE MODE, Change Ringer mode etc.

4. conclusion:

  • Some information about SeekBar and its usage.
  • Some information about how to set volume using Seekbar.
  • Some information about how to set Screen brightness using Seekbar.
  • Know how to use seekbar control and how to get progress values of seekbar.

    5. About the post:

    • The code seems to explain itself due to comments, but if you have any questions you can freely ask too!
    •  Don’t mind to write a comment whatever you like to ask, to know,to suggest or recommend.
    •  Hope you enjoy it!
        6. Source Code:
                you can download the source code from: GoogleDriveGithub

        Cheers,
        Hamad Ali Shaikh