Know when to show a passcode lock

家住魔仙堡 提交于 2019-11-30 05:22:21

In onStop() of each activity, update a static data member with the time you left the activity. In onStart() of each activity, check that time, and if it exceeds some timeout threshold, display your authentication activity. Allow the user to set the timeout value, so that if they don't want to be bothered every few seconds, they can control that.

I liked the time based approach, I've been struggling for a while getting this to work in a nice way. The time based approach works well. I made a class for easier usage.

public class PinCodeCheck {

    private static long INIT_TIME           = 0;
    private static PinCodeCheck ref         = null;
    private static SharedPreferences values = null;

    private PinCodeCheck(Context context){
        values = context.getSharedPreferences("com.example.xxx", 0); //use your preferences file name key!
    }//end constructor

    public static synchronized PinCodeCheck getInstance(Context context) {
        if (ref == null){
            ref = new PinCodeCheck(context);
        } 
        return ref;
    }//end method 

    public void init(){
        PinCodeCheck.INIT_TIME = System.currentTimeMillis();    
    }//end method   

    public void forceLock(){
        PinCodeCheck.INIT_TIME = 0;     
    }//end method   

    public boolean isLocked(){
        long currentTime    = System.currentTimeMillis();
        long threshold      = values.getLong(Keys.PASSWORD_PROTECT_TIMEOUT, 30000); // check here, might change in between calls
        if (currentTime - PinCodeCheck.INIT_TIME > threshold){
            return true;
        }
        return false;       
    }//end method   
}//end class

USAGE

private static PinCodeCheck check   = PinCodeCheck.getInstance(context);

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

    if (check.isLocked()) { 
        showDialog();               
    }
}//end method 

@Override
public void onPause() {          
    super.onPause();

    check.init();
}//end method 
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!