节省电量—手机屏幕亮度调整

手机屏幕亮度调整:有两种方法,第一种是自动调整,第二种是拉动显示

首先,获取系统管理

/***********************************************************************
 * 
 *     Copyright: 2011, BAINA Technologies Co. Ltd.
 *     Classname: SystemManager.java
 *     Author:    yuewang
 *     Description:    TODO
 *     History:
 *         1.  Date:   2011-9-21
 *             Author:    yuewang
 *             Modifycation:    create the class.       
 *
 ***********************************************************************/

package com.TestBrightness.manager;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.net.Uri;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.text.format.Formatter;
import android.view.WindowManager;

/**
 * @author yuewang
 * 
 */
public class SystemManager {

	private Context mContext;

	private static SystemManager sInstance;

	private SystemManager(final Context context) {
		mContext = context;
	}

	/**
	 * Advice to invoke init in application.
	 * 
	 * @param context
	 * @return
	 */
	public static SystemManager init(final Context context) {
		if (null == sInstance) {
			sInstance = new SystemManager(context);
		}
		return sInstance;
	}

	/**
	 * 
	 * @return
	 */
	public static SystemManager getInstance() {
		return sInstance;
	}

	/**
	 * 判断是否开启了自动亮度调节
	 * 
	 * @param aContext
	 * @return
	 */
	public boolean isAutoBrightness() {
		boolean automicBrightness = false;
		try {
			final ContentResolver resolver = mContext.getContentResolver();
			automicBrightness = Settings.System.getInt(resolver,
					Settings.System.SCREEN_BRIGHTNESS_MODE) == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC;
		} catch (final SettingNotFoundException e) {
			e.printStackTrace();
		}
		return automicBrightness;
	}

	/**
	 * 设置屏幕亮度,这会反映到真实屏幕上
	 * 
	 * @param activity
	 * @param brightness
	 */
	public void setBrightness(final Activity activity, final int brightness) {
		final WindowManager.LayoutParams lp = activity.getWindow()
				.getAttributes();
		lp.screenBrightness = Float.valueOf(brightness) * (1f / 255f);
		activity.getWindow().setAttributes(lp);
	}

	/**
	 * 保存亮度设置状态
	 * 
	 * @param resolver
	 * @param brightness
	 */
	public void saveBrightness(final int brightness) {
		final ContentResolver resolver = mContext.getContentResolver();
		final Uri uri = android.provider.Settings.System
				.getUriFor("screen_brightness");
		android.provider.Settings.System.putInt(resolver, "screen_brightness",
				brightness);
		// resolver.registerContentObserver(uri, true, myContentObserver);
		resolver.notifyChange(uri, null);
	}

	/**
	 * 开启亮度自动调节
	 * 
	 * @param activity
	 */
	public void startAutoBrightness() {
		final ContentResolver resolver = mContext.getContentResolver();
		Settings.System.putInt(resolver,
				Settings.System.SCREEN_BRIGHTNESS_MODE,
				Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
		final Uri uri = android.provider.Settings.System
				.getUriFor("screen_brightness");
		resolver.notifyChange(uri, null);
	}

	/**
	 * 停止自动亮度调节
	 * 
	 * @param activity
	 */
	public void stopAutoBrightness() {
		final ContentResolver resolver = mContext.getContentResolver();
		Settings.System.putInt(resolver,
				Settings.System.SCREEN_BRIGHTNESS_MODE,
				Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
		final Uri uri = android.provider.Settings.System
				.getUriFor("screen_brightness");
		resolver.notifyChange(uri, null);
	}

	/**
	 * 获取屏幕的亮度
	 * 
	 * @param activity
	 * @return
	 */
	public int getScreenBrightness() {
		int nowBrightnessValue = 0;
		try {
			final ContentResolver resolver = mContext.getContentResolver();
			nowBrightnessValue = android.provider.Settings.System.getInt(
					resolver, Settings.System.SCREEN_BRIGHTNESS);
		} catch (final Exception e) {
			e.printStackTrace();
		}
		return nowBrightnessValue;
	}

	/**
	 * 保存亮度的显示模式
	 * 
	 * @return
	 */
	public void setBrightnessMode(int mode) {
		Settings.System.putInt(mContext.getContentResolver(),
				Settings.System.SCREEN_BRIGHTNESS_MODE, mode);
	}

	/**
	 * 获取亮度的显示模式
	 * 
	 * @return
	 */
	public int getBrightnessMode() {
		try {
			return Settings.System.getInt(mContext.getContentResolver(),
					Settings.System.SCREEN_BRIGHTNESS_MODE);
		} catch (SettingNotFoundException e) {
			return Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC;
		}
	}

	public String formatMemorySize(final long memory) {
		return Formatter.formatFileSize(mContext, memory);
	}
}

然后通过Activity显示出来

package com.TestBrightness;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;

import com.TestBrightness.manager.SystemManager;

public class TestBrightness extends Activity implements OnClickListener {
	/** Called when the activity is first created. */
	private Button Start;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		SystemManager.init(this);
		showBrightnessSettingDialog();
		GetPhone();
	}
	private void GetPhone(){
		// 创建电话管理
		TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		// 获取手机号码
		String phoneId = tm.getLine1Number();
		Toast.makeText(this, phoneId+"", Toast.LENGTH_SHORT).show();
		System.out.println("=============" + phoneId);
	}

	@Override
	public void onClick(View v) {
		showBrightnessSettingDialog();
	}

	private int mOldBrightness;
	private int mCurrentBrightness = 0;
	private int mOldAutomatic;
	private boolean mAutomaticAvailable;
	/**
	 * Brightness value for dim backlight
	 */
	private static final int BRIGHTNESS_DIM = 20;
	/**
	 * Brightness value for fully on
	 */
	private static final int BRIGHTNESS_ON = 255;

	// Backlight range is from 0 - 255. Need to make sure that user
	// doesn't set the backlight to 0 and get stuck
	private static final int MINIMUM_BACKLIGHT = BRIGHTNESS_DIM + 10;
	private static final int MAXIMUM_BACKLIGHT = BRIGHTNESS_ON;

	private void showBrightnessSettingDialog() {
		final SystemManager systemManager = SystemManager.getInstance();
		final Builder builder = new AlertDialog.Builder(this);
		final View view = getLayoutInflater().inflate(R.layout.brightness_view,
				null);

		// set brightness seekbar
		final SeekBar brightnessBar = (SeekBar) view
				.findViewById(R.id.brightness_bar);
		brightnessBar.setMax(MAXIMUM_BACKLIGHT - MINIMUM_BACKLIGHT);
		int brightness = systemManager.getScreenBrightness();
		int process = brightness - MINIMUM_BACKLIGHT;
		if (process < 0) {
			process = 0;
			mOldBrightness = MINIMUM_BACKLIGHT;
			mCurrentBrightness = MINIMUM_BACKLIGHT;
		} else {
			mOldBrightness = brightness;
			mCurrentBrightness = brightness;
		}
		brightnessBar.setProgress(process);

		// set automatic available checkbox
		final CheckBox autoBrightness = (CheckBox) view
				.findViewById(R.id.auto_brightness);
		mOldAutomatic = systemManager.getBrightnessMode();
		mAutomaticAvailable = systemManager.isAutoBrightness();
		autoBrightness.setChecked(mAutomaticAvailable);
		if (mAutomaticAvailable) {
			brightnessBar.setVisibility(View.GONE);
		} else {
			brightnessBar.setVisibility(View.VISIBLE);
		}
		autoBrightness
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {
					@Override
					public void onCheckedChanged(
							final CompoundButton buttonView,
							final boolean isChecked) {
						mAutomaticAvailable = isChecked;
						if (isChecked) {
							brightnessBar.setVisibility(View.GONE);
							systemManager.startAutoBrightness();
							// systemManager.setBrightness(MainActivity.this,
							// systemManager.getScreenBrightness());
							int process = systemManager.getScreenBrightness()
									- MINIMUM_BACKLIGHT;
							if (process < 0) {
								process = 0;
							}// end if
							brightnessBar.setProgress(process);
						} else {
							brightnessBar.setVisibility(View.VISIBLE);
							systemManager.stopAutoBrightness();
							// systemManager.setBrightness(MainActivity.this,
							// systemManager.getScreenBrightness());
							int process = systemManager.getScreenBrightness()
									- MINIMUM_BACKLIGHT;
							if (process < 0) {
								process = 0;
							}// end if
							brightnessBar.setProgress(process);
						}
					}

				});

		brightnessBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

			@Override
			public void onStopTrackingTouch(final SeekBar seekBar) {

			}

			@Override
			public void onStartTrackingTouch(final SeekBar seekBar) {

			}

			@Override
			public void onProgressChanged(final SeekBar seekBar,
					final int progress, final boolean fromUser) {
				mCurrentBrightness = progress + MINIMUM_BACKLIGHT;
				systemManager.setBrightness(TestBrightness.this,
						mCurrentBrightness);
			}
		});

		builder.setTitle(R.string.brightness);
		builder.setView(view);
		builder.setPositiveButton(android.R.string.ok,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(final DialogInterface dialog,
							final int which) {
						// set brightness
						if (mAutomaticAvailable) {
							systemManager.saveBrightness(systemManager
									.getScreenBrightness());
						} else {
							systemManager.saveBrightness(mCurrentBrightness);
						}
					}

				});
		builder.setNegativeButton(android.R.string.cancel,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(final DialogInterface dialog,
							final int which) {
						// recover brightness
						systemManager.setBrightness(TestBrightness.this,
								mOldBrightness);
						systemManager.saveBrightness(mOldBrightness);
						// recover automatic brightness mode
						systemManager.setBrightnessMode(mOldAutomatic);
					}
				});

		builder.show();
	}
}

brightness.xml文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linearLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="20dip"
        android:src="@drawable/btn_auto_brightness_default" >
    </ImageView>

    <CheckBox
        android:id="@+id/auto_brightness"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dip"
        android:layout_marginTop="10dip"
        android:text="@string/automatic_brightness"
        android:textColor="@android:color/white" >
    </CheckBox>

    <SeekBar
        android:id="@+id/brightness_bar"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dip"
        android:layout_marginLeft="10dip"
        android:layout_marginRight="10dip"
        android:layout_marginTop="20dip" >
    </SeekBar>

</LinearLayout>

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
    <Button android:layout_width="fill_parent" 
    	android:layout_height="wrap_content"
		android:text="@string/brightness" android:onClick="onClick"/>
    
    <Button android:layout_width="fill_parent" 
    	android:layout_height="wrap_content"
		android:text="@string/brightness" android:id="@+id/Start"/>
</LinearLayout>

String.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, TestBrightness!</string>
    <string name="app_name">TestBrightness</string>
    <string name="brightness">亮度</string>
    <string name="automatic_brightness">自动亮度</string>
</resources>

相关推荐