项目中需要做一个桌面小工具,会悬浮在桌面(类似360等的清理内存悬浮框),点击后又手电筒、wifi、屏幕亮度等开关,因为需要在app退出后也能够运行,所以需要由Service实现。
其中的设置屏幕亮度的方法如下:
Settings.System.putInt(mContext.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, brightness);
如果当开启自动调节功能的时候,我们进行调节好像是没有一点作用的,只有进行判断,看是否开启了屏幕亮度的自动调节功能。
/**
*
* @return 1:表示是自动亮度
*/
private int getScreenMode(){
int screenMode=0;
try{
screenMode = Settings.System.getInt(mContext.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE);
}
catch (Exception localException){
}
return screenMode;
}
关闭自动亮度
private void stopAutoBrightness(){
Settings.System.putInt(mContext.getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS_MODE,
Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
}
至此,应该说操作亮度的基本都差不多了,在4.4的虚拟机和小米手机上运行正常。
但是悲剧的是,测试提出bug,在三星的手机上调节亮度无效,于是拿机器过来一看是4.1.2,查了相关知识才知道,在Android低版本调用putInt后需要刷新一下才能使调节
屏幕亮度生效,锁屏一下再次打开,果然生效了。。但是不可能让用户每次来修改亮度时还需要再锁屏一下吧。
WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
layoutParams.screenBrightness=brightness;//设置屏幕的亮度
getWindow().setAttributes(layoutParams);
上面的方法也有效,但是getWindow只能在Activity中调用,而我们是Service,于是这个方法也行不通。
还有其他的方法
Uri uri = android.provider.Settings.System
.getUriFor("screen_brightness");
mContext.getContentResolver().notifyChange(uri, null);
经过测试也是无效的,还是不能立刻刷新当前的屏幕亮度。
没办法只能继续找答案了。
是不是可以打开一个透明的Activity,然后利用它的Window来设置屏幕亮度完了后结束它,这样也不行,打开一个Activity时也会启动我们的app,这样不是用Service来实现的。
由于我们都是使用WindowManager在桌面创建的View,查了下WindowManager,发现它的LayoutParams有一个screenBrightness的属性,这个属性应该能改变桌面的亮度。应该可以用WindowManager创建一个全屏的透明View,在addView时设置LayoutParams的screenBrightness为修改的亮度值brightness。然后再删除这个view。
private static void setScreenBrightness(int brightness){
if(mWindowManager == null){
mWindowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
}
int screenWidth = mWindowManager.getDefaultDisplay().getWidth();
int screenHeight = mWindowManager.getDefaultDisplay().getHeight();
if (mScreenLayout == null) {
mScreenLayout = new LinearLayout(mContext);
if (mScreenLayoutParmas == null) {
mScreenLayoutParmas = new WindowManager.LayoutParams();
mScreenLayoutParmas.x = 0;
mScreenLayoutParmas.y = 0;
mScreenLayoutParmas.type = WindowManager.LayoutParams.TYPE_PHONE;
mScreenLayoutParmas.format = PixelFormat.RGBA_8888;
mScreenLayoutParmas.width = screenWidth;
mScreenLayoutParmas.height = screenHeight;
//brightness 是Settings.System.putInt()中对应的int,转换成WindowManager.LayoutParams中的float
mScreenLayoutParmas.screenBrightness = brightness / 255.0f;
}
mWindowManager.addView(mScreenLayout, mScreenLayoutParmas);
mWindowManager.removeView(mScreenLayout);
mScreenLayout = null;
mScreenLayoutParmas = null;
}
}
在三星手机(4.1.2)上测试正常,真的能修改屏幕的亮度了。。好神奇。。于是赶紧记录下来。