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

前端 未结 4 668
梦毁少年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:26

    Tweaked @Wolfgang version

    public sealed class SessionManager
    {
        static readonly Lazy lazy =
            new Lazy(() => new SessionManager());
    
        public static SessionManager Instance { get { return lazy.Value; } }
        private Stopwatch StopWatch = new Stopwatch();
    
        SessionManager()
        {
            SessionDuration = TimeSpan.FromMinutes(5);
        }
    
        public TimeSpan SessionDuration;
    
        public void EndTrackSession()
        {
            if (StopWatch.IsRunning)
            {
                StopWatch.Stop();
            }
        }
    
        public void ExtendSession()
        {
            if (StopWatch.IsRunning)
            {
                StopWatch.Restart();
            }
        }
    
        public void StartTrackSessionAsync()
        {
            if (!StopWatch.IsRunning)
            {
                StopWatch.Restart();
            }
    
            Xamarin.Forms.Device.StartTimer(new TimeSpan(0, 0, 2), () =>
            {
                if (StopWatch.IsRunning && StopWatch.Elapsed.Minutes >= SessionDuration.Minutes)
                {
                    Xamarin.Forms.Device.BeginInvokeOnMainThread(async () =>
                    {
                        await Prism.PrismApplicationBase.Current.Container.Resolve().NavigateAsync("/Index/Navigation/LoginPage");
                    });
    
                    StopWatch.Stop();
                }
    
                return true;
            });
    
        }
    
    }
    

    Under main activity added the below

        public override void OnUserInteraction()
        {
            base.OnUserInteraction();
            SessionManager.Instance.ExtendSession();
        }
    

提交回复
热议问题