小程序--android调节屏幕亮度

程序界面:




这个小程序也不难,我现在看书需要调节屏幕亮度,通常需要下拉菜单,进入设置界面->显示->调节亮度,再一个个调节。想自己写一个悬浮窗的小按钮,只要一点击它,

就弹出个activity设置亮度。这里是主要代码:

添加一个悬浮窗首先要写个Application的子类:

public class MyApplication extends Application {
	
	/**
	 * 创建全局变量
	 * 全局变量一般都比较倾向于创建一个单独的数据类文件,并使用static静态变量
	 * 
	 * 这里使用了在Application中添加数据的方法实现全局变量
	 * 注意在AndroidManifest.xml中的Application节点添加android:name=".MyApplication"属性
	 * 
	 */
	private WindowManager.LayoutParams wmParams=new WindowManager.LayoutParams();
	public WindowManager.LayoutParams getMywmParams(){
		return wmParams;
	}
}


接着,我们写一个Service,然后动态生成悬浮窗:

public class FloatService extends Service{

    private WindowManager wm = null;
    private WindowManager.LayoutParams wmParams = null;
    private View view;
    private TextView tv_light_degree;
    private Handler handler = new Handler();
    private float mTouchStartX;
    private float mTouchStartY;
    private float x;
    private float y;
    private long delaytime = 2000;
    private boolean isAutoMode;
    private static final String TAG = "FloatService";
    

    @Override
    public void onCreate() {
        
        view = LayoutInflater.from(this).inflate(R.layout.float_view, null);
        tv_light_degree = (TextView)view.findViewById(R.id.tv_light_degree);
        
        try {
            isAutoMode = android.provider.Settings.System.getInt(getContentResolver(),
                    android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE) ==
                    android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC;
            Log.v(TAG, "start program screen light mode:" + isAutoMode);
        } catch (SettingNotFoundException e) {
            e.printStackTrace();
        }
        
        createView();
        super.onCreate();
        // 启动一个线程专门更新浮动窗的数据
        handler.post(task);
    }
    
    
    private Runnable task = new Runnable() {
        public void run() {
            dataRefresh();
            handler.postDelayed(this, delaytime);
            wm.updateViewLayout(view, wmParams);
        }
    };

    // 刷新悬浮窗亮度数据
    private void dataRefresh() {
        String light =
        System.getString(getContentResolver(), System.SCREEN_BRIGHTNESS);
        tv_light_degree.setText(light);
    }
    
    private void createView() {
        SharedPreferences shared = getSharedPreferences("float_flag",
                Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = shared.edit();
        editor.putInt("float", 1);
        editor.commit();
        // 获取WindowManager
        wm = (WindowManager) getApplicationContext().getSystemService("window");
        // 设置LayoutParams(全局变量)相关参数
        wmParams = ((MyApplication)getApplication()).getMywmParams();
        wmParams.type = 2002;
        wmParams.flags |= 8;
        wmParams.gravity = Gravity.LEFT | Gravity.TOP; // 调整悬浮窗口至左上角
        // 以屏幕左上角为原点,设置x、y初始值
        wmParams.x = 0;
        wmParams.y = 0;
        // 设置悬浮窗口长宽数据
        wmParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
        wmParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        wmParams.format = 1;
        
        wm.addView(view, wmParams);

        view.setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                // 获取相对屏幕的坐标,即以屏幕左上角为原点
                x = event.getRawX();
                y = event.getRawY() - 25; // 25是系统状态栏的高度
                Log.i("currP", "currX" + x + "====currY" + y);// 调试信息
                switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    // 获取相对View的坐标,即以此View左上角为原点
                    mTouchStartX = event.getX();
                    mTouchStartY = event.getY();
                    Log.i("startP", "startX" + mTouchStartX + "====startY"
                            + mTouchStartY);// 调试信息
                    Intent intent = new Intent();
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.setClass(FloatService.this, ChangeLightActivity.class);
                    startActivity(intent);
                    break;
                case MotionEvent.ACTION_MOVE:
                    updateViewPosition();
                    break;

                case MotionEvent.ACTION_UP:
                    updateViewPosition();
                    mTouchStartX = mTouchStartY = 0;
                    Intent changeLight = new Intent();
                    changeLight.setClass(FloatService.this, ChangeLightActivity.class);
                    break;
                }
                return true;
            }
        });
    }
    
    private void updateViewPosition() {
        wmParams.x = (int)(x - mTouchStartX);
        wmParams.y = (int)(y - mTouchStartY);
        wm.updateViewLayout(view, wmParams);
    }

    @Override
    public IBinder onBind(Intent arg0) {
        
        return null;
    }

    @Override
    public void onDestroy() {
        handler.removeCallbacks(task);
        wm.removeView(view);
        if(isAutoMode){
        System.putInt(getContentResolver(),
                System.SCREEN_BRIGHTNESS_MODE,
                System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
        }
        super.onDestroy();
        
    }
}

弹出一个activity:
布局是:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
	android:id="@+id/out_frame"
	android:layout_width="fill_parent"
	android:layout_height="fill_parent"
	xmlns:android="http://schemas.android.com/apk/res/android">
	
    <TextView
        android:id="@+id/tv_label"
        android:layout_centerHorizontal="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#009900"
        android:text="@string/move_and_adjust"/>
    
    <com.superhardware.component.VerticalSeekBar
        android:id="@+id/seekBar_light"
        android:layout_below="@+id/tv_label"
        android:layout_centerHorizontal="true"
        android:layout_width="wrap_content"
        android:layout_height="200dp"
        android:scrollbars="horizontal" />
    
    <TextView
        android:id="@+id/mTextView_light"
        android:layout_below="@+id/seekBar_light"
        android:layout_centerHorizontal="true"
        android:textIsSelectable="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#009900"/>
	
</RelativeLayout>

代码:
		super.onCreate(savedInstanceState);
		setContentView(R.layout.judge_screen_lightness);
		mTextView_light = (TextView)findViewById(R.id.mTextView_light);
		vsb = (VerticalSeekBar)findViewById(R.id.seekBar_light);
		int real_degree = 0;
		 try {
			 real_degree = android.provider.Settings.System.getInt(getContentResolver(),
			         android.provider.Settings.System.SCREEN_BRIGHTNESS);
		} catch (SettingNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		mTextView_light.setText(""+real_degree);
		
		// 设置垂直滑动条的监听事件
		vsb.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
			
			@Override
			public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
				
				int real_degree = (int)(arg1*255/100);
				
				if(real_degree == 0){
		        	real_degree = 1;
		        }
				WindowManager.LayoutParams layoutParams = getWindow().getAttributes(); 
		        layoutParams.screenBrightness = real_degree/255.0f;// b是亮度        
		        
		        getWindow().setAttributes(layoutParams);
				
		        //保存为系统亮度方法1
                android.provider.Settings.System.putInt(getContentResolver(),
                                  android.provider.Settings.System.SCREEN_BRIGHTNESS,
                                  real_degree);
               
              //保存为系统亮度方法2
//            Uri uri = android.provider.Settings.System.getUriFor("screen_brightness");  
//            android.provider.Settings.System.putInt(getContentResolver(), "screen_brightness", brightness);   
//            // resolver.registerContentObserver(uri, true, myContentObserver);  
//            getContentResolver().notifyChange(uri, null);
              //更改亮度文本显示
               mTextView_light.setText(""+real_degree);


有一个自定义的垂直滑动条,自定义代码如下:
public class VerticalSeekBar extends SeekBar {
	
		public VerticalSeekBar(Context context) {
			super(context);
		}
	 
	   public VerticalSeekBar(Context context, AttributeSet attrs, int defStyle) {
		   super(context, attrs, defStyle);
	    }
	   
	   public VerticalSeekBar(Context context,AttributeSet attrs){
		   super(context, attrs);
	   }
	 
	   protected void onSizeChanged(int w, int h, int oldw, int oldh) {
	       super.onSizeChanged(h, w, oldh, oldw);
	    }
	 
	   protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
	       super.onMeasure(heightMeasureSpec, widthMeasureSpec);
	       setMeasuredDimension(getMeasuredHeight(), getMeasuredWidth());
	    }
	 
	   protected void onDraw(Canvas c) {
	       c.rotate(-90);
	       c.translate(-getHeight(),0);
	 
	       super.onDraw(c);
	    }
	 
	   @Override
	   public boolean onTouchEvent(MotionEvent event) {
	       if (!isEnabled()) {
	           return false;
	       }
	 
	       switch (event.getAction()) {
	           case MotionEvent.ACTION_DOWN:
	           case MotionEvent.ACTION_MOVE:
	           case MotionEvent.ACTION_UP:
	                    int i=0;
	                    i=getMax() - (int)(getMax() * event.getY() / getHeight());
	                setProgress(i);
	               Log.i("Progress",getProgress()+"");
	                onSizeChanged(getWidth(),getHeight(), 0, 0);
	                break;
	 
	           case MotionEvent.ACTION_CANCEL:
	                break;
	       }
	       return true;
	  }
	   
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值