最近在开发一个有关相机的项目,有需求是根据光线的强度自动开启夜市(红外)的功能,但开发中发现如果熄屏后,则无法监听到光线强度变化。
下面是我的解决办法,
1、首先监听关屏的广播,如果正在录像的话,持有锁,使屏幕处于显示状态,不让其黑屏休眠,然后将屏幕亮度调整为0,相当于假熄屏,然后重写Activity的dispatchTouchEvent()方法,判断如果当前是假熄屏,则return true,不往下分发事件,防止用户误操作。
public class ScreenStatusReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (Intent.ACTION_SCREEN_OFF.equals(action)) { // 关屏
if(sta.IsRecording){
sta.mIsScreenOff = true;
Log.e("ACTION_SCREEN", "ACTION_SCREEN_OFF");
if (mTurnBackOn == null){
mTurnBackOn = mPwrMgr.newWakeLock(
PowerManager.SCREEN_DIM_WAKE_LOCK
| PowerManager.ACQUIRE_CAUSES_WAKEUP,
"AccelOn");
}
mTurnBackOn.acquire();
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
WindowManager.LayoutParams lp = ((MainActivity) mContext).getWindow()
.getAttributes();
lp.screenBrightness = 0f;
((MainActivity) mContext).getWindow().setAttributes(lp);
}
},200);
}
}
}
}
2、监听按键onKeyDown()事件,将屏幕亮度调整为原来的亮度,
((MainActivity) mContext).getWindow().setAttributes(mLayoutParams);
然后释放锁mWakeLock.release();