基于ContentObserver来动态打消或添加屏幕超时任务
前面也说了,ContentObserver可以来监控数据库里某一项数据的变革,虽然也可以同时监控多个数据项的变革。笔者在项目中需要修改到屏幕超时的需求,好比在车载业务中,倒车事件产生的时候,是不需要屏幕超时变黑的,相当于这个计时timer要Reset一下,同样在蓝牙电话也要Reset一下,最好就是在这种非凡任务的时候,这个屏幕超时计时任务就不要跑起来,这样是最好的,那怎么实现呢?
笔者通过研究phonewindowsmanger.cpp中发明,最终都是驱动一个mScreenLockTimeout,它怎么来的呢?见如下代码:
<span style="font-size:18px;"> ScreenLockTimeout mScreenLockTimeout = new ScreenLockTimeout(); class ScreenLockTimeout implements Runnable { Bundle options; @Override public void run() { synchronized (this) { if (localLOGV) Log.v(TAG, "mScreenLockTimeout activating keyguard"); if (mKeyguardDelegate != null) { mKeyguardDelegate.doKeyguardTimeout(options); } mLockScreenTimerActive = false; options = null; } } public void setLockOptions(Bundle options) { this.options = options; } }</span>
Runnable 是重点啊!
归根结底照旧驱动一个runnable。那怎么节制呢?看到内里的源码,也有大量操纵这个mScreenLockTimeout,可以动态的remove,再动态的启动起来。笔者就想起了用contentobserver来做历程间通讯了,好比写一个值代表打消这个任务,写别的一个值就添加这个任务。笔者或许代码如下:
private final class CalcScnTimeoutObserver extends ContentObserver { public CalcScnTimeoutObserver(Handler handler) { super(handler); } @Override public void onChange(boolean selfChange) { ContentResolver resolver = mContext.getContentResolver(); mCalcScnTimeoutValue = Settings.System.getIntForUser(resolver, Settings.System.SCREEN_TIMEOUT_CALC_INFO, 0, UserHandle.USER_CURRENT); Slog.d(TAG,"##CalcScnTimeoutObserver: " + mCalcScnTimeoutValue); if(1 == mCalcScnTimeoutValue){ synchronized (mScreenLockTimeout) { if (mLockScreenTimerActive) { // reset the timer mHandler.removeCallbacks(mScreenLockTimeout); //mHandler.postDelayed(mScreenLockTimeout, mLockScreenTimeout); mLockScreenTimerActive = false; } } } else if(2 == mCalcScnTimeoutValue){ synchronized (mScreenLockTimeout) { if (mLockScreenTimerActive) { // reset the timer mHandler.removeCallbacks(mScreenLockTimeout); mHandler.postDelayed(mScreenLockTimeout, mLockScreenTimeout); } else { mHandler.postDelayed(mScreenLockTimeout, mLockScreenTimeout); mLockScreenTimerActive = true; } } }else { Slog.e(TAG,"default novalid value "); } } void observe() { // Observe all users' changes ContentResolver resolver = mContext.getContentResolver(); resolver.registerContentObserver(Settings.System.getUriFor( Settings.System.SCREEN_TIMEOUT_CALC_INFO), false, this, UserHandle.USER_ALL); } }
通过这样已处理惩罚,就能到达动态节制这个任务的浸染,还长短常简朴实用的。源码里照旧有许多英华代码及处理惩罚要领,要害是我们要去熟悉、相识、把握、机动运用!android之大,驾御了就是美,驾御不了就是魔!继承尽力!
作者:csdn博客 sundesheng125