Xamarin forms: Check if user inactive after some time log out app

前端 未结 4 675
梦毁少年i
梦毁少年i 2021-01-12 01:39

Hi I am trying to build an application in xamarin forms using PCL. I am trying to logout user from my app if the app is idle more than 10minute or more. I tried it by events

4条回答
  •  梦谈多话
    2021-01-12 02:24

    I was able to use the Device.StartTimer in Xamarin Forms to create an expiration. For my app the user switched screens fairly often so I would cause inactivity to be reset between screen transitions. It was a little less obnoxious then tying the method to each button press and screen tap. The class that houses the logic looks something like this:

    public class InactivityService
    {  
        public ActivityMonitorService( )
        { 
        }
    
        public DateTime LastClick { get; private set; }
        public TimeSpan MaxLength { get; private set; }
    
        public void Start(TimeSpan maxDuration, Action expirationCallback = null)
        {
            MaxLength = maxDuration;
            Notify();
            _expirationCallBack = expirationCallback;
            ResetTimer();
        }
    
        public void Notify()
        { 
            LastClick = DateTime.Now;
        }
    
        public void Stop()
        {
        }
    
        public TimeSpan TimeSinceLastNotification()
        {
            var now = DateTime.Now;
            var timeSinceLastClick = now - LastClick;
            return timeSinceLastClick;
        }
    
        public TimeSpan GetNewTimerSpan()
        {
            var newDuration = MaxLength - TimeSinceLastNotification();
            return newDuration;
        }
    
        public bool IsExpired(DateTime time)
        {
            return time - LastClick > MaxLength;
        }
    
        private bool CallBack()
        {
            if (IsExpired(DateTime.Now))
            {
                Expire();
            }
            else
            {
                ResetTimer();
            }
    
            return false;
        }
    
        public async void Expire()
        {
            if (_expirationCallBack != null)
                _expirationCallBack.Invoke();
            Stop(); 
            //Notify user of logout
            //Do logout navigation
        }
    
        private void ResetTimer()
        {
            Device.StartTimer(GetNewTimerSpan(), CallBack);
        }
    }
    

提交回复
热议问题