关于屏幕锁定和解锁

时间:2012-02-16 08:00:28

标签: android

我正在做一个锁定和解锁屏幕的应用程序。我正在使用disableKeygaurd和reeanbleKeygaurd来锁定和解锁。以下用于解锁的代码:

if(mKeyguardLock ==  null){
  mKeyGuardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
  mKeyguardLock = mKeyGuardManager.newKeyguardLock("****");
  mKeyguardLock.disableKeyguard();  
}

和锁定:

if(mKeyguardLock != null){
 mKeyguardLock.reenableKeyguard();
 mKeyguardLock = null;
}

工作正常。但问题是当用户通过拖动keygaurd(不使用我的应用程序)意外解锁屏幕时,我的应用程序将不会锁定屏幕下次..我想在用户使用解锁时通过拖动keygaur来工作我的应用程序。我应该怎么做? 提前致谢

1 个答案:

答案 0 :(得分:0)

Try This:

private KeyguardManager mKeyguardManager;
private KeyguardManager.KeyguardLock mKeyguardLock;
private static final String TAG = "ALERTLock";

public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);

     int flags = getFlagsForVersion();        
        getWindow().addFlags(flags);
        mKeyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);   
}

 private int getFlagsForVersion() {
        final String possibleFlags[] = new String[] {
            "FLAG_SHOW_WHEN_LOCKED",
            "FLAG_DISMISS_KEYGUARD",
            "FLAG_TURN_SCREEN_ON"
        };

        int flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
        for(String flag:possibleFlags) {
            try {
                Field field = WindowManager.LayoutParams.class.getField(flag);
                int value = field.getInt(null);
                flags |= value;
            }
            catch(NoSuchFieldException e) { }
            catch(IllegalAccessException e) { }
        }

        return flags;
    }

    private synchronized void enableKeyguard() {
        if (mKeyguardLock != null) {
            mKeyguardLock.reenableKeyguard();
            mKeyguardLock = null;
        }
    }

    private synchronized void disableKeyguard() {
        if (mKeyguardLock == null) {
            mKeyguardLock = mKeyguardManager.newKeyguardLock(TAG);
            mKeyguardLock.disableKeyguard();
        }
    }    
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        disableKeyguard();
    }

    @Override
    public void onResume() {
        super.onResume();
        disableKeyguard();
    }