Android 禁止屏幕休眠和锁屏的方法

常常我们开 发程序的时候我们不需要系统唤醒系统锁屏功能,比如我们在做xxxNowTV或XXX播放器这样的程序,用户有时候在看电视或视频的时候不希望系统的锁屏 功能启动,既不想锁频,然而系统却在我们看电视或者视频的时候出来个锁屏的界面进行锁频拉,我们还要想继续看的话还要去解锁,这样好麻烦,不是我们想要 的,那我们该怎么做呢,其实很简单,我这里只讲其中的两种

 

 :我们只要在程序中用代码实现。代码如下:  

[java]  view plain copy
  1. //方法一   
  2. getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); setContentView(R.layout.main);   
  3. //方法二   
  4.     @Override  
  5.     protected void onResume() {  
  6.         super.onResume();  
  7.         pManager = ((PowerManager) getSystemService(POWER_SERVICE));  
  8.         mWakeLock = pManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK  
  9.                 | PowerManager.ON_AFTER_RELEASE, TAG);  
  10.         mWakeLock.acquire();  
  11.     }  
  12.       
  13.     @Override  
  14.     protected void onPause() {  
  15.         super.onPause();  
  16.           
  17.         if(null != mWakeLock){  
  18.             mWakeLock.release();  
  19.         }  
  20.     }  
  21. //方法三  
  22.     public void unLock(){  
  23.         mContentResolver = getContentResolver();  
  24.         //不建议使用  
  25.         //setLockPatternEnabled(android.provider.Settings.System.LOCK_PATTERN_ENABLED,false);  
  26.           
  27.         //推荐使用  
  28.         setLockPatternEnabled(android.provider.Settings.Secure.LOCK_PATTERN_ENABLED,false);  
  29.     }  
  30.       
  31.     private void setLockPatternEnabled(String systemSettingKey, boolean enabled) {  
  32.          //不建议使用  
  33.          //android.provider.Settings.System.putInt(mContentResolver,systemSettingKey, enabled ? 1 : 0);  
  34.           
  35.          //推荐使用  
  36.          android.provider.Settings.Secure.putInt(mContentResolver, systemSettingKey,enabled ? 1 : 0);  
  37.     }  
  38.     //但注意要加权限AndroidManifest.xml文件中加入  
  39.     //<uses-permission android:name="android.permission.WRITE_SETTINGS" />  
  40.     //还要特别注意的是要加入 android:sharedUserId="android.uid.system",但有一个问题,  
  41.     //如果加入了sharedUserId后就不能使用eclipse编译了,一定要手动通过 mm -B进行编译,然后把apk install到模拟器或设备中  
  42.       

 

二:禁用系统的锁屏功能,这方法不建议使用,只有在设当的环境下适当使用既可,我们只要知道这样我们也可以达到这样的功能实现就OK。

我们知道Android系统的锁屏时间存放在Setting数据库中,字段为Settings.System.SCREEN_OFF_TIMEOUT。我们可以查看SettingsProvider源码,查看如下文件的源码如下:

~/frameworks/base/packages/SettingsProvider/src/com/android/providers/settings/DatabaseHelper.java






查看loadSystemSettings()函数的代码如下

[java]  view plain copy
  1. private void loadSystemSettings(SQLiteDatabase db) {  
  2.         SQLiteStatement stmt = db.compileStatement("INSERT OR IGNORE INTO system(name,value)"  
  3.                 + " VALUES(?,?);");  
  4.         Resources r = mContext.getResources();  
  5.         loadBooleanSetting(stmt, Settings.System.DIM_SCREEN,  
  6.                 R.bool.def_dim_screen);  
  7.         loadSetting(stmt, Settings.System.STAY_ON_WHILE_PLUGGED_IN,  
  8.                 "1".equals(SystemProperties.get("ro.kernel.qemu")) ? 1 : 0);  
  9.         loadIntegerSetting(stmt, Settings.System.SCREEN_OFF_TIMEOUT,  
  10.                 R.integer.def_screen_off_timeout);  
  11.         // Set default cdma emergency tone  
  12.         loadSetting(stmt, Settings.System.EMERGENCY_TONE, 0);  
  13.         // Set default cdma call auto retry  
  14.         loadSetting(stmt, Settings.System.CALL_AUTO_RETRY, 0);  
  15.         // Set default cdma DTMF type  
  16.         loadSetting(stmt, Settings.System.DTMF_TONE_TYPE_WHEN_DIALING, 0);  
  17.         // Set default hearing aid  
  18.         loadSetting(stmt, Settings.System.HEARING_AID, 0);  
  19.         // Set default tty mode  
  20.         loadSetting(stmt, Settings.System.TTY_MODE, 0);  
  21.         loadBooleanSetting(stmt, Settings.System.AIRPLANE_MODE_ON,  
  22.                 R.bool.def_airplane_mode_on);  
  23.         loadStringSetting(stmt, Settings.System.AIRPLANE_MODE_RADIOS,  
  24.                 R.string.def_airplane_mode_radios);  
  25.         loadStringSetting(stmt, Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS,  
  26.                 R.string.airplane_mode_toggleable_radios);  
  27.         loadBooleanSetting(stmt, Settings.System.AUTO_TIME,  
  28.                 R.bool.def_auto_time); // Sync time to NITZ  
  29.         loadIntegerSetting(stmt, Settings.System.SCREEN_BRIGHTNESS,  
  30.                 R.integer.def_screen_brightness);  
  31.         loadBooleanSetting(stmt, Settings.System.SCREEN_BRIGHTNESS_MODE,  
  32.                 R.bool.def_screen_brightness_automatic_mode);  
  33.         loadDefaultAnimationSettings(stmt);  
  34.         loadBooleanSetting(stmt, Settings.System.ACCELEROMETER_ROTATION,  
  35.                 R.bool.def_accelerometer_rotation);  
  36.         loadDefaultHapticSettings(stmt);  
  37.         stmt.close();  
  38.     }  

我们通过查看源码便知道, Settings.System.SCREEN_OFF_TIMEOUT没有初始化的话(系统首次启动,这个字段肯定是没 有初始化的),系统将会利用资源中的R.integer.def_screen_off_timeout来初始化。我们为了让系统永不锁屏,只需要把资源 R.integer.def_screen_off_timeout设为-1即可。查看文件在这里:

frameworks/base/packages/SettingsProvider/res/values/defaults.xml

可以找到R.integer.def_screen_off_timeout的定义 

[xhtml]  view plain copy
  1. <integer name="def_screen_off_timeout">60000</integer>  

发现默认值为60000ms,也就是60s。我们只需要把这个参数改为-1。然后重新编译SettingsProvider模块,就OK了。

但有时候也会有这样的情况发生,用户进入系统后,修改锁屏时间,为了这样的情况发生我们得在Setting模块中删除对锁屏时间的设置。这样Android设备就不锁屏了。

我们这里还要处理一种情况,就是让系统一启动我们就禁用锁屏的功能,很简单,我们只要把系统锁  功能的的初始默认开关给改以下就可以了,如下找到这个类:

frameworks/policies/base/phone/com/android/internal/policy/impl/KeyguardViewMediator.java

4.4 的在frameworks/base/packages/Keyguard/src/com/android/keyguard/KeyguardViewMediator.java

 该文件中有一个变量定义如下:



 
 
[java] view plain copy
  1. /** 
  2.  * External apps (like the phone app) can tell us to disable the keygaurd. 
  3.  */  
  4. private boolean mExternallyEnabled = true  
mExternallyEnabled是用来管理是否开启屏幕锁的关键。默认值是打开屏锁,根据注释可以知道他是希望应用程序来修改这个 值,我们可以把这个值改成false就可以了。 有时候我们不想修改这个初始值,那我们看看这个类有没有提供相应的方法来供外部修改这个值的,不出我们所料,看下面这段代码就是的了:
[java] view plain copy
  1. /** 
  2.  * Same semantics as {@link WindowManagerPolicy#enableKeyguard}; provide 
  3.  * a way for external stuff to override normal keyguard behavior.  For instance 
  4.  * the phone app disables the keyguard when it receives incoming calls. 
  5.  */  
  6. public void setKeyguardEnabled(boolean enabled) {  
  7.     synchronized (this) {  
  8.         if (DEBUG) Log.d(TAG, "setKeyguardEnabled(" + enabled + ")");  
  9.   
  10.         mExternallyEnabled = enabled;  
  11.   
  12.         if (!enabled && mShowing) {  
  13.             if (mExitSecureCallback != null) {  
  14.                 if (DEBUG) Log.d(TAG, "in process of verifyUnlock request, ignoring");  
  15.                 // we're in the process of handling a request to verify the user  
  16.                 // can get past the keyguard. ignore extraneous requests to disable / reenable  
  17.                 return;  
  18.             }  
  19.   
  20.             // hiding keyguard that is showing, remember to reshow later  
  21.             if (DEBUG) Log.d(TAG, "remembering to reshow, hiding keyguard, "  
  22.                     + "disabling status bar expansion");  
  23.             mNeedToReshowWhenReenabled = true;  
  24.             hideLocked();  
  25.         } else if (enabled && mNeedToReshowWhenReenabled) {  
  26.            ...  
  27.            ...  
  28.         }  
  29.     }  
转自:http://blog.csdn.net/chenyafei617/article/details/6575621

刚毕业不久由于项目需要就接触到锁屏,从2.2到4.1都解过bug,也定制过一些功能。4.1之前的锁屏工作不难,但很费时间,因为它的逻辑,视图,资源分别分布在不同的路径下,就像散落在海边沙滩上的珠子,想串起来还是蛮费劲的。最开始时锁屏就是改个字段也要全编译生成img。后来新技能get,会针对修改的地方进行单编译,但每次编译jar,导入手机,重启看效果也是不方便的。

一年前把锁屏交出去就没有再看过了,前些日子自己的谷歌四太子升到4.4,发现锁屏有很大变化,可以左右滑页,添加删除widget,添加删除分页。简直就是一个简化版的launcher。很好奇google是怎么改变的,于是费了很大的劲拉了google的最新源码。在android 4.4中这个模块的改动简直是巨大,这里略作整理。

1.文件目录:

a,锁屏代理是在Frameworks/base/policy/src/com/android/internal/policy/impl/keyguard下:

b,整个工程应用在framework/package下,结构和功能现在都和 systemUI类似:

c,keyguard的对外接口Frameworks/base/core/java/android/app/keyguardManager.java:

android4.2前做一些第三方锁屏软件都会用到该服务接口来控制系统锁屏(比如禁止系统锁屏),现在该接口已经不建议使用了,有更好的做法:

[java] view plain copy 在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.      * @deprecated使用{@link android.view.WindowManager.LayoutParams#FLAG_DISMISS_KEYGUARD} 
  3.      * and/or {@link android.view.WindowManager.LayoutParams#FLAG_SHOW_WHEN_LOCKED} 
  4.      * 来代替; 利用该方式可以使应用达到禁用锁屏的效果而不需要额外的权限申请。this allows you to 
  5.      * Enables you to lock or unlock thekeyboard. Get an instance of this class by 
  6.      * calling {@link android.content.Context#getSystemService(java.lang.String)Context.getSystemService()}. 
  7.      * This class is wrapped by {@link android.app.KeyguardManagerKeyguardManager}. 
  8.      * @param tag A tag that informallyidentifies who you are (for debugging who 
  9.      *  is disabling he keyguard). 
  10.      * 
  11.      * @return A {@link KeyguardLock} handle to use todisable and reenable the 
  12.      *   keyguard. 
  13.      */  
  14.     @Deprecated  
  15.     public KeyguardLock newKeyguardLock(Stringtag) {  
  16.         return new KeyguardLock(tag);  
  17.     }  

Keyguard锁屏流程图

Keyguard锁屏view层次图:

 

Keyguard锁屏重要类分析:

1.PhoneWindowManager.java

这个类很厉害也很重要,它由WindowManagerService派生,处理了phone的顶层逻辑,主要有以下几块:

a)      横竖屏处理(屏幕旋转等)

[java] view plain copy 在CODE上查看代码片 派生到我的代码片
  1. publicvoidsetCurrentOrientationLw(intnewOrientation){  
  2. synchronized (mLock){  
  3. if (newOrientation != mCurrentAppOrientation) {  
  4. mCurrentAppOrientation = newOrientation;  
  5. updateOrientationListenerLp();  
  6.             }  
  7.         }  
  8.     }  

b)      是否显示状态条或者navigation_bar。

[java] view plain copy 在CODE上查看代码片 派生到我的代码片
  1. privateintupdateSystemUiVisibilityLw() {  
  2. // If there is no window focused,there will be nobody to handle the events  
  3. // anyway, so just hang on inwhatever state we're in until things settle down.  
  4. WindowState win = mFocusedWindow != null ? mFocusedWindow :mTopFullscreenOpaqueWindowState;  
  5. if (win == null){  
  6. return 0;  
  7.         }  
  8. if (win.getAttrs().type == TYPE_KEYGUARD&&mHideLockScreen == true) {  
  9. // We are updating at a pointwhere the keyguard has gotten  
  10. // focus, but we were last in astate where the top window is  
  11. // hiding it.  This is probably because the keyguardas been  
  12. // shown while the top window wasdisplayed, so we want to ignore  
  13. // it here because this is just avery transient change and it  
  14. // will quickly lose focus once itcorrectly gets hidden.  
  15. return 0;  
  16.         }  
  17.    
  18. inttmpVisibility = win.getSystemUiVisibility()  
  19. & ~mResettingSystemUiFlags  
  20. & ~mForceClearedSystemUiFlags;  
  21. if (mForcingShowNavBar&&win.getSurfaceLayer()<mForcingShowNavBarLayer) {  
  22. tmpVisibility&= ~View.SYSTEM_UI_CLEARABLE_FLAGS;  
  23.         }  
  24. finalint visibility = updateSystemBarsLw(win,mLastSystemUiFlags,tmpVisibility);  
  25. finalint diff = visibility ^ mLastSystemUiFlags;  
  26. finalbooleanneedsMenu = win.getNeedsMenuLw(mTopFullscreenOpaqueWindowState);  
  27. if (diff == 0 &&mLastFocusNeedsMenu == needsMenu  
  28. &&mFocusedApp ==win.getAppToken()) {  
  29. return 0;  
  30.         }  
  31. mLastSystemUiFlags = visibility;  
  32. mLastFocusNeedsMenu = needsMenu;  
  33. mFocusedApp = win.getAppToken();  
  34. mHandler.post(new Runnable() {  
  35. @Override  
  36. publicvoid run() {  
  37. try {  
  38. IStatusBarServicestatusbar = getStatusBarService();  
  39. if (statusbar != null) {  
  40. statusbar.setSystemUiVisibility(visibility,0xffffffff);  
  41. statusbar.topAppWindowChanged(needsMenu);  
  42.                         }  
  43.                     } catch (RemoteException e) {  
  44. // re-acquire status bar servicenext time it is needed.  
  45. mStatusBarService = null;  
  46.                     }  
  47.                 }  
  48.             });  
  49. return diff;  
  50.     }  

c)      各种按键事件的拦截和分发(比如长按home键)

Home键的事件是在phonewindow这一层就拦截的,所以一般情况应用本身无法正常拦截该事件。

[java] view plain copy 在CODE上查看代码片 派生到我的代码片
  1. privatevoidhandleLongPressOnHome() {  
  2. if (mLongPressOnHomeBehavior != LONG_PRESS_HOME_NOTHING) {  
  3. mHomeConsumed = true;  
  4. performHapticFeedbackLw(null,HapticFeedbackConstants.LONG_PRESS, false);  
  5.    
  6. if (mLongPressOnHomeBehavior == LONG_PRESS_HOME_RECENT_SYSTEM_UI) {  
  7. toggleRecentApps();  
  8.             } elseif (mLongPressOnHomeBehavior == LONG_PRESS_HOME_ASSIST){  
  9. launchAssistAction();  
  10.             }  
  11.         }  
  12.     }  

d)      锁屏事件处理和响应

[java] view plain copy 在CODE上查看代码片 派生到我的代码片
  1. publicvoidsystemReady() {  
  2. if (!mHeadless){  
  3. mKeyguardDelegate = newKeyguardServiceDelegate(mContext, null);  
  4. mKeyguardDelegate.onSystemReady();  
  5.         }  
  6. synchronized (mLock){  
  7. updateOrientationListenerLp();  
  8. mSystemReady = true;  
  9. mHandler.post(new Runnable() {  
  10. @Override  
  11. publicvoid run() {  
  12. updateSettings();  
  13.                 }  
  14.             });  
  15.         }  
  16. }  

2.KeyguardServiceDelegate.java和KeyguardServiceWrapper.java

这两个类是android 4.4新增加的,分别对KeyguardService进行了代理和包装,代理类里面有一个Scrim视图在keyguard崩溃时显示。包装类就是对keyguardService的简单包装,最终把调度都会传给keyguardService。

3.keyguardService.java

上面一再说到该类,那么它有啥出众的地方呢,其实它就是keyguard的入口,锁屏所有的往生都因它而起,这个类很简单,实例化了一个IKeyguardService.Stub供其他类bindservice时调用,需要特别注意的是整个keyguard的核心实力派KeyguardViewMediator在这里诞生了。

4.KeyguardViewMediator.java

字面上的意思是keyguard视图调度者,功能上是负责处理keyguard视图的事件,比如完成锁屏和解锁这些动作的视图响应,它作为一个位高权重的调度使当然不会亲手去做这些,它有个得力干将KeyguardviewManager,所有的大小任务都会放权给它。

[java] view plain copy 在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.  *有关锁屏请求的调度者。包括锁屏状态的查询,power management事件影响锁屏是否应该被显示或者重置,特定的回调函数来 
  3.  *通知windowmanager锁屏是什么时候显示,以及接受view视图传过来的消息表明已经成功完成解锁。 
  4.  *请注意锁屏是在灭屏后立即被调用显示的。这样当你点亮屏幕,锁屏才能第一时间显示出来。 
  5.  *例如外部事件调度锁屏视图流程: 
  6.  * 
  7.  *-灭屏动作-》重置锁屏并显示它为下次点亮屏幕做好准备。 
  8.  *-锁屏很自然流畅的打开了-》如果他不是安全的,隐藏之。 
  9.  * 
  10.  *来自于锁屏视图的事件: 
  11.  *-用户成功完成解锁条件-》隐藏锁屏视图,不再对输入事件进行拦截。 
  12.  *请再注意:第三方应用通过条用power managment实例可以屏蔽系统的锁屏。 
  13.  * 
  14.  *线程和同步: 
  15.  *该类是由WindowManagerPolicy创建并运行在它的线程里,锁屏UI也是这个类的构造函数里面产生。这个apis也可以被其他线程所调用。 
  16.  *然而,这个类的方法手势同步的,同时任何一个锁屏视图都会发消息到handle来保证它是在锁屏UI线程里面执行的。 
  17.  */  
  18.    
  19. public class KeyguardViewMediatorimplements KeyguardViewCallback,  
  20.        KeyguardUpdateMonitor.InfoCallback,KeyguardUpdateMonitor.SimStateCallback {  
  21. private static final intKEYGUARD_DISPLAY_TIMEOUT_DELAY_DEFAULT = 30000;  
  22. /** 
  23.     * This handler will be associated with the policy thread, which willalso 
  24.     * be the UI thread of the keyguard. Since the apis of the policy, and therefore 
  25.     * this class, can be called by other threads, any action that directly 
  26.     * interacts with the keyguard ui should be posted to this handler,rather 
  27.     * than called directly. 
  28.     */  
  29.    private Handler mHandler = new Handler() {  
  30.        @Override  
  31.        public void handleMessage(Message msg) {  
  32.            switch (msg.what) {  
  33.                 case TIMEOUT:  
  34.                     handleTimeout(msg.arg1);  
  35.                    return ;  
  36.                 case SHOW:  
  37.                     handleShow();  
  38.                     return ;  
  39.                 case HIDE:  
  40.                     handleHide();  
  41.                     return ;  
  42.                 case RESET:  
  43.                     handleReset();  
  44.                     return ;  
  45.                 case VERIFY_UNLOCK:  
  46.                     handleVerifyUnlock();  
  47.                     return;  
  48.                 case NOTIFY_SCREEN_OFF:  
  49.                     handleNotifyScreenOff();  
  50.                     return;  
  51.                 case NOTIFY_SCREEN_ON:  
  52.                    handleNotifyScreenOn((KeyguardViewManager.ShowListener)msg.obj);  
  53.                     return;  
  54.                 case WAKE_WHEN_READY:  
  55.                     handleWakeWhenReady(msg.arg1);  
  56.                     return;  
  57.                 case KEYGUARD_DONE:  
  58.                     handleKeyguardDone(msg.arg1!= 0);  
  59.                     return;  
  60.                 case KEYGUARD_DONE_DRAWING:  
  61.                    handleKeyguardDoneDrawing();  
  62.                     return;  
  63.                 caseKEYGUARD_DONE_AUTHENTICATING:  
  64.                     keyguardDone(true);  
  65.                     return;  
  66.                 case SET_HIDDEN:  
  67.                     handleSetHidden(msg.arg1 !=0);  
  68.                     break;  
  69.                 case KEYGUARD_TIMEOUT:  
  70.                     synchronized(KeyguardViewMediator.this) {  
  71.                         doKeyguardLocked();  
  72.                     }  
  73.                     break;  
  74.            }  
  75.        }  
  76.    };  
  77. private void adjustStatusBarLocked() {  
  78.       ......//控制是否能在锁屏界面下拉状态栏。  
  79.            }  
  80. }  

5.KeyguardViewManager.java

如果说mediator相当于总裁,那这个就是经理,而且是视图部门老大,它有一个类型为FrameLayout名叫ViewManager的内部类,用来作为keyguard的viewroot。在viewroot里添加了KeyguardHostView,我们叫它mKeyguardView。Keyguard里任何的view细节和问题都能通过它找到蛛丝马迹。

[java] view plain copy 在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.  * Manages creating, showing, hiding andresetting the keyguard.  Callsback 
  3.  * via {@link KeyguardViewMediator.ViewMediatorCallback} to poke 
  4.  * the wake lock and report that the keyguardis done, which is in turn, 
  5.  * reported to this class by the current {@link KeyguardViewBase}. 
  6.  */  
  7. public class KeyguardViewManager {  
  8.     private final static boolean DEBUG = KeyguardViewMediator.DEBUG;  
  9.     private static String TAG = "KeyguardViewManager";  
  10.     public static boolean USE_UPPER_CASE = true;  
  11.     public final static String IS_SWITCHING_USER = "is_switching_user";  
  12.    
  13.     // Timeoutused for keypresses  
  14.     static final int DIGIT_PRESS_WAKE_MILLIS = 5000;  
  15.    
  16.     private final Context mContext;  
  17.     private final ViewManager mViewManager;  
  18.     private final KeyguardViewMediator.ViewMediatorCallbackmViewMediatorCallback;  
  19.    
  20.     private WindowManager.LayoutParams mWindowLayoutParams;  
  21.     private boolean mNeedsInput = false;  
  22.    
  23.     private ViewManagerHost mKeyguardHost;  
  24.     private KeyguardHostView mKeyguardView;  

6.KeyguardHostVIew.java

这里完成keyguardView布局,实例化。分析一个自定义的viewgroup,重点需要分析的是它的构造方法和onFinishInflate()方法:

[java] view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public KeyguardHostView(Context context, AttributeSet attrs) {  
  2.         super(context, attrs);  
  3.    
  4.         if (DEBUG) Log.e(TAG, "KeyguardHostView()");  
  5.    
  6.         mLockPatternUtils = newLockPatternUtils(context);  
  7.    
  8.         // Note: This depends on KeyguardHostView getting reconstructed every timethe  
  9.         // user switches, since mUserId will be used for the entire session.  
  10.         // Once created, keyguard should *never* re-use this instance withanother user.  
  11.         // In other words, mUserId should never change - hence it's marked final.  
  12.         mUserId = mLockPatternUtils.getCurrentUser();  
  13.    
  14.         DevicePolicyManager dpm =  
  15.                 (DevicePolicyManager) mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);  
  16.         if (dpm != null) {  
  17.             mDisabledFeatures =getDisabledFeatures(dpm);  
  18.             mCameraDisabled =dpm.getCameraDisabled(null);  
  19.         }  
  20.    
  21.         mSafeModeEnabled= LockPatternUtils.isSafeModeEnabled();  
  22.    
  23.         // These need to be created with the user context...  
  24.         Context userContext = null;  
  25.         try {  
  26.             final String packageName = "system";  
  27.             userContext = mContext.createPackageContextAsUser(packageName,0,  
  28.                     new UserHandle(mUserId));  
  29.    
  30.         } catch (NameNotFoundException e) {  
  31.             e.printStackTrace();  
  32.             // This should never happen, but it's better to have no widgets than tocrash.  
  33.             userContext = context;  
  34.         }  
  35.    
  36.         mAppWidgetHost = new AppWidgetHost(userContext, APPWIDGET_HOST_ID, mOnClickHandler,  
  37.                 Looper.myLooper());  
  38.    
  39.         mAppWidgetManager =AppWidgetManager.getInstance(userContext);  
  40.    
  41.         mSecurityModel = new KeyguardSecurityModel(context);  
  42.    
  43.         mViewStateManager = newKeyguardViewStateManager(this);  
  44.    
  45.     }  
  46.    
  47.     @Override  
  48.     protected void onFinishInflate() {  
  49.         // Grab instances of and make any necessary changes to the main layouts.Create  
  50.         // view state manager and wire up necessary listeners / callbacks.  
  51.         View deleteDropTarget = findViewById(R.id.keyguard_widget_pager_delete_target);  
  52.         mAppWidgetContainer =(KeyguardWidgetPager) findViewById(R.id.app_widget_container);  
  53.         mAppWidgetContainer.setVisibility(VISIBLE);  
  54.         mAppWidgetContainer.setCallbacks(mWidgetCallbacks);  
  55.         mAppWidgetContainer.setDeleteDropTarget(deleteDropTarget);  
  56.         mAppWidgetContainer.setMinScale(0.5f);  
  57.    
  58.         mSlidingChallengeLayout =(SlidingChallengeLayout) findViewById(R.id.sliding_layout);  
  59.         if (mSlidingChallengeLayout != null) {  
  60.            mSlidingChallengeLayout.setOnChallengeScrolledListener(mViewStateManager);  
  61.         }  
  62.         mAppWidgetContainer.setViewStateManager(mViewStateManager);  
  63.         mAppWidgetContainer.setLockPatternUtils(mLockPatternUtils);  
  64.    
  65.         mMultiPaneChallengeLayout =  
  66.                 (MultiPaneChallengeLayout)findViewById(R.id.multi_pane_challenge);  
  67.         ChallengeLayout challenge =mSlidingChallengeLayout != null ? mSlidingChallengeLayout :  
  68.                 mMultiPaneChallengeLayout;  
  69.        challenge.setOnBouncerStateChangedListener(mViewStateManager);  
  70.         mAppWidgetContainer.setBouncerAnimationDuration(challenge.getBouncerAnimationDuration());  
  71.         mViewStateManager.setPagedView(mAppWidgetContainer);  
  72.         mViewStateManager.setChallengeLayout(challenge);  
  73.         mSecurityViewContainer = (KeyguardSecurityViewFlipper)findViewById(R.id.view_flipper);  
  74.         mKeyguardSelectorView =(KeyguardSelectorView) findViewById(R.id.keyguard_selector_view);  
  75.         mViewStateManager.setSecurityViewContainer(mSecurityViewContainer);  
  76.    
  77.         setBackButtonEnabled(false);  
  78.    
  79.         if (KeyguardUpdateMonitor.getInstance(mContext).hasBootCompleted()){  
  80.             updateAndAddWidgets();  
  81.         } else {  
  82.             // We can't add widgets until after boot completes because AppWidgetHostmay try  
  83.             // to contact the providers.  Do itlater.  
  84.             mPostBootCompletedRunnable = new Runnable() {  
  85.                 @Override  
  86.                 public void run() {  
  87.                     updateAndAddWidgets();  
  88.                 }  
  89.             };  
  90.         }  
  91.    
  92.         showPrimarySecurityScreen(false);  
  93.         updateSecurityViews();  
  94.         enableUserSelectorIfNecessary();  
  95.     }  

7.KeyguardUpdateMonitor.java

说明:监听系统状态值的改变如时间、SIM卡状态、电池电量等,状态值的改变会回调监听了该状态信息的对象实例。如果只是关注功能的话只需要看hadle里面的每个消息调用的方法即可。

[java] view plain copy 在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.  *Watches for updates that may be interesting to the keyguard, and provides 
  3.  *the up to date information as well as a registration for callbacks that care 
  4.  * tobe updated. 
  5.  * 
  6.  *Note: under time crunch, this has been extended to include some stuff that 
  7.  *doesn't really belong here.  see {@link#handleBatteryUpdate} where it shutdowns 
  8.  *the device, and {@link #getFailedAttempts()}, {@link #reportFailedAttempt()} 
  9.  *and {@link #clearFailedAttempts()}. Maybe we should rename this 'KeyguardContext'... 
  10.  */  
  11. public class KeyguardUpdateMonitor {  
  12.    private Handler mHandler;  
  13.    private ContentObserver mContentObserver;  
  14.    private int mRingMode;  
  15.    private int mPhoneState;  
  16. ......  
  17.    
  18.    /** 
  19.     * SIM卡状态改变捕获赋值。 
  20.     * the intent and provide a {@link SimCard.State} result. 
  21.     */  
  22.    private static class SimArgs {  
  23.    
  24.        public final IccCard.State simState;  
  25.    
  26.        private SimArgs(Intent intent) {  
  27.            if(!TelephonyIntents.ACTION_SIM_STATE_CHANGED.equals(intent.getAction())) {  
  28.                 throw newIllegalArgumentException("only handles intentACTION_SIM_STATE_CHANGED");  
  29.            }  
  30.            String stateExtra = intent.getStringExtra(IccCard.INTENT_KEY_ICC_STATE);  
  31.            if (IccCard.INTENT_VALUE_ICC_ABSENT.equals(stateExtra)) {  
  32.                 final String absentReason =intent  
  33.                    .getStringExtra(IccCard.INTENT_KEY_LOCKED_REASON);  
  34.    
  35.                 if(IccCard.INTENT_VALUE_ABSENT_ON_PERM_DISABLED.equals(  
  36.                         absentReason)) {  
  37.                    this.simState =IccCard.State.PERM_DISABLED;  
  38.                 } else {  
  39.                     this.simState =IccCard.State.ABSENT;  
  40.                 }  
  41.            } else if (IccCard.INTENT_VALUE_ICC_READY.equals(stateExtra)) {  
  42.                 this.simState =IccCard.State.READY;  
  43.            } else if (IccCard.INTENT_VALUE_ICC_LOCKED.equals(stateExtra)) {  
  44.                 final String lockedReason =intent  
  45.                        .getStringExtra(IccCard.INTENT_KEY_LOCKED_REASON);  
  46.                 if (IccCard.INTENT_VALUE_LOCKED_ON_PIN.equals(lockedReason)){  
  47.                     this.simState =IccCard.State.PIN_REQUIRED;  
  48.                 } else if(IccCard.INTENT_VALUE_LOCKED_ON_PUK.equals(lockedReason)) {  
  49.                     this.simState = IccCard.State.PUK_REQUIRED;  
  50.                 } else {  
  51.                     this.simState =IccCard.State.UNKNOWN;  
  52.                 }  
  53.            } else if (IccCard.INTENT_VALUE_LOCKED_NETWORK.equals(stateExtra)) {  
  54.                 this.simState =IccCard.State.NETWORK_LOCKED;  
  55.            } else {  
  56.                 this.simState =IccCard.State.UNKNOWN;  
  57.            }  
  58.        }  
  59.    
  60.        public String toString() {  
  61.            return simState.toString();  
  62.        }  
  63.     }  
  64.    
  65.    public KeyguardUpdateMonitor(Context context) {  
  66.        mContext = context;  
  67.    
  68.        mHandler = new Handler() {  
  69.            @Override  
  70.            public void handleMessage(Message msg) {  
  71.                 switch (msg.what) {  
  72.                     case MSG_TIME_UPDATE:  
  73.                         handleTimeUpdate();  
  74.                         break;  
  75.                     case MSG_BATTERY_UPDATE:  
  76.                        handleBatteryUpdate(msg.arg1, msg.arg2);  
  77.                         break;  
  78.                     caseMSG_CARRIER_INFO_UPDATE:  
  79.                         handleCarrierInfoUpdate();  
  80.                         break;  
  81.                     case MSG_SIM_STATE_CHANGE:  
  82.                        handleSimStateChange((SimArgs) msg.obj);  
  83.                         break;  
  84.                     caseMSG_RINGER_MODE_CHANGED:  
  85.                        handleRingerModeChange(msg.arg1);  
  86.                         break;  
  87.                     caseMSG_PHONE_STATE_CHANGED:  
  88.                        handlePhoneStateChanged((String)msg.obj);  
  89.                         break;  
  90.                     caseMSG_CLOCK_VISIBILITY_CHANGED:  
  91.                        handleClockVisibilityChanged();  
  92.                         break;  
  93.                     caseMSG_DEVICE_PROVISIONED:  
  94.                        handleDeviceProvisioned();  
  95.                         break;  
  96.                 }  
  97.            }  
  98.        };  

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用 System.Windows.Forms.Application.SetSuspendState 方法来防止屏幕锁屏。这个方法有两个参数,第一个参数是一个枚举类型,用于指定要执行的操作(关机、休眠或者睡眠),第二个参数是一个布尔值,用于指定是否禁止屏幕锁屏。如果第二个参数设置为 true,那么在操作执行期间,屏幕将不会锁定。 以下是一个示例代码: ```csharp using System; using System.Windows.Forms; using System.Runtime.InteropServices; public partial class Form1 : Form { [DllImport("user32.dll", SetLastError = true)] static extern bool SystemParametersInfo(uint uiAction, uint uiParam, ref bool pvParam, uint fWinIni); private const uint SPI_SETSCREENSAVERACTIVE = 0x0011; private const uint SPIF_SENDWININICHANGE = 0x0002; private const uint SPIF_UPDATEINIFILE = 0x0001; public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { bool preventScreenSaver = true; SystemParametersInfo(SPI_SETSCREENSAVERACTIVE, 0, ref preventScreenSaver, SPIF_SENDWININICHANGE | SPIF_UPDATEINIFILE); //执行操作 System.Windows.Forms.Application.SetSuspendState(PowerState.Hibernate, true, false); } } ``` 在上面的示例代码中,我们将 preventScreenSaver 参数设置为 true,以便禁用屏幕保护程序。接下来,我们调用 System.Windows.Forms.Application.SetSuspendState 方法来执行操作(这里我们使用 Hibernate 操作),并将第二个参数设置为 true,以便在操作期间禁用屏幕锁定。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值