package com.samples.window.setscreenbright;

import android.app.Activity;
import android.os.Bundle;
import android.provider.Settings.SettingNotFoundException;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

public class ScreenBrightessActivity extends Activity 
implements OnClickListener, OnSeekBarChangeListener {
	
    private SeekBar seek;
    private Button bSetBright; 
    private TextView text;
    
	private int brightness = 128;

	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.main);
	   	  
	    seek = (SeekBar)findViewById(R.id.seek);
	    text = (TextView)findViewById(R.id.text);
	    bSetBright = (Button)findViewById(R.id.bSetBright); 
	    
	    try {
	    	brightness = android.provider.Settings.System.getInt(
	      	    getContentResolver(), 
	      	    android.provider.Settings.System.SCREEN_BRIGHTNESS);
	    } 
	    catch (SettingNotFoundException e) {
	      	e.printStackTrace();
	    }
	    
	    int percBrigh = brightness * 100 / 255;
	    seek.setProgress(percBrigh);
	    text.setText(percBrigh + "%");
	    
	    bSetBright.setOnClickListener(this); 
	    seek.setOnSeekBarChangeListener(this);	  
	}

	@Override
	public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
		text.setText(arg1 + "%");
			  
		WindowManager.LayoutParams params = getWindow().getAttributes();
		params.screenBrightness = (float)arg1 / 100;
		getWindow().setAttributes(params);
		brightness = arg1 * 255 / 100;
	}

	@Override
	public void onStartTrackingTouch(SeekBar arg0) { }

	@Override
	public void onStopTrackingTouch(SeekBar arg0) { }

	@Override
	public void onClick(View arg0) { 
	    android.provider.Settings.System.putInt(getContentResolver(),
			android.provider.Settings.System.SCREEN_BRIGHTNESS, brightness);
	}
}