Lock android app after a certain amount of idle time

前端 未结 4 442
眼角桃花
眼角桃花 2020-12-09 23:39

My android application requires a password to be entered in the first activity. I want to be able to automatically send the application back to the password entry screen aft

4条回答
  •  失恋的感觉
    2020-12-10 00:01

    This has been a really helpful post for me. To back the concept given by @Yoni Samlan . I have implemented it this way

    public void pause() {
            // Record timeout time in case timeout service is killed    
            long time = System.currentTimeMillis();     
            SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
            SharedPreferences.Editor edit = preferences.edit();
            edit.putLong("Timeout_key", time);// start recording the current time as soon as app is asleep
            edit.apply();
        }
    
        public void resume() {       
            // Check whether the timeout has expired
            long cur_time = System.currentTimeMillis();
            SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
            long timeout_start = preferences.getLong("Timeout_key", -1);
            // The timeout never started
            if (timeout_start == -1) {
                return;
            }   
            long timeout;
            try {
                //timeout = Long.parseLong(sTimeout);
                timeout=idle_delay;
            } catch (NumberFormatException e) {
                timeout = 60000;
            }
            // We are set to never timeout
            if (timeout == -1) {
                return;
            }
            if (idle){
            long diff = cur_time - timeout_start;
            if (diff >= timeout) {  
                //Toast.makeText(act, "We have timed out", Toast.LENGTH_LONG).show(); 
                showLockDialog();
            }
            }
        } 
    

    Call pause method from onPause and resume method from onResume.

提交回复
热议问题