需求是这样的,应用在使用的过程中保持高亮的状态,假如用户不操作10秒后,亮度降低,假如用户一直不操作30秒后,直接灭屏... 实现思路:1,从高亮到亮度降低,将系统亮度降低即可;2,灭屏是改变系统灭屏时间实现的。
刚开始网上找了几个灭屏的方法,什么geToSleep啊,什么release啊,都不起作用,不知何故。
其实实现起来很简单,下面我说一下我的实现步骤:
用到的类Settings.System中putInt方法,源码如下:
/**
* Convenience function for updating a single settings value as an
* integer. This will either create a new entry in the table if the
* given name does not exist, or modify the value of the existing row
* with that name. Note that internally setting values are always
* stored as strings, so this function converts the given value to a
* string before storing it.
*
* @param cr The ContentResolver to access.
* @param name The name of the setting to modify.
* @param value The new value for the setting.
* @return true if the value was set, false on database errors
*/
public static boolean putInt(ContentResolver cr, String name, int value) {
return putIntForUser(cr, name, value, UserHandle.myUserId());
}
从高亮到亮度降低代码如下:
ContentResolver contentResolver = getContentResolver();
int value = 255; // 设置亮度最大值为255
Settings.System.putInt(contentResolver,
Settings.System.SCREEN_BRIGHTNESS, value);
mTimeHandler.removeCallbacks(r);
//10秒后执行暗屏caozu
mTimeHandler.postDelayed(r, 10*1000);
runnable代码如下:
private Runnable r = new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
//10秒一次暗屏
ContentResolver contentResolver = getContentResolver();
int value = 0; // 设置亮度值最小值为0
Settings.System.putInt(contentResolver,
Settings.System.SCREEN_BRIGHTNESS, value);
}};
可以看出代码中
Settings.System.SCREEN_BRIGHTNESS 这个字段用于设置系统亮度,范围为0-255,我在做这个需求的时候,0并非是全部灭屏,而是屏幕变的暗了一些。
这样就可以实现无操作10秒后暗屏的操作,暗屏的程度根据实际情况进行调节。
灭屏用到api这样一个字段:SCREEN_OFF_TIMEOUT。 看api的解释:The timeout before the screen turns off.屏幕关闭前的超时。这是一个可以设置系统灭屏时间的方法。
设置一次就可生效,代码如下:
ContentResolver contentResolver = getContentResolver(); Settings.System.putInt(contentResolver, Settings.System.SCREEN_OFF_TIMEOUT, 30*1000);
这样在每次启动应用的时候调用一次就可以满足无操作30秒后灭屏需求。
在AndroidManifest.xml中包含权限:
<uses-permission android:name=”android.permission.WRITE_SETTINGS” />
如上就可实现整个需求。
希望此帖可以帮助一些和我一样在网上寻找灭屏方法但是不起作用的人,因为第一次写博客,所以自己都感觉写得比较乱,还请大家见谅。