gpt4 book ai didi

c# - Xamarin 表格 : Check if user inactive after some time log out app

转载 作者:太空狗 更新时间:2023-10-29 20:04:14 24 4
gpt4 key购买 nike

您好,我正在尝试使用 PCL 以 xamarin 形式构建应用程序。如果应用程序空闲时间超过 10 分钟或更长时间,我将尝试从我的应用程序中注销用户。我通过应用程序即将进入休眠状态时调用的事件进行了尝试。但是,如果设备屏幕超时设置为永不超时,那么它可能永远不会进入休眠状态。那么我该如何实现呢。我是 xamarin 表单的新手。当我为所有平台构建应用程序时,我很困惑如何管理此超时?

最佳答案

现在我使用以下方法。可能需要做一些额外的测试以确保一切都按预期工作。例如,我不确定如果应用程序(iOS 或 Android)在后台长时间运行会发生什么。计时器是否仍会每秒调用一次?也许当使用到期时间足够短(~5 分钟)的计时器时,这根本不是问题?等等……

我的方法基于我在网上找到的几段代码(一些 Xamarin 代码,一些 Swift/Java 代码)——似乎没有一个很好的综合解决方案。

无论如何,一些初步测试表明这种方法工作正常。


首先,我创建了一个名为 SessionManager 的单例类。此类包含一个计时器(实际上只是一个每秒休眠的 while 循环)和启动、停止和延长计时器的方法。如果 session 到期计时器到期,它也会触发一个事件。

public sealed class SessionManager
{
static readonly Lazy<SessionManager> lazy =
new Lazy<SessionManager>(() => new SessionManager());

public static SessionManager Instance { get { return lazy.Value; } }

SessionManager() {
this.SessionDuration = TimeSpan.FromMinutes(5);
this.sessionExpirationTime = DateTime.FromFileTimeUtc(0);
}

/// <summary>
/// The duration of the session, by default this is set to 5 minutes.
/// </summary>
public TimeSpan SessionDuration;

/// <summary>
/// The OnSessionExpired event is fired when the session timer expires.
/// This event is not fired if the timer is stopped manually using
/// EndTrackSession.
/// </summary>
public EventHandler OnSessionExpired;

/// <summary>
/// The session expiration time.
/// </summary>
DateTime sessionExpirationTime;

/// <summary>
/// A boolean value indicating wheter a session is currently active.
/// Is set to true when StartTrackSessionAsync is called. Becomes false if
/// the session is expired manually or by expiration of the session
/// timer.
/// </summary>
public bool IsSessionActive { private set; get; }

/// <summary>
/// Starts the session timer.
/// </summary>
/// <returns>The track session async.</returns>
public async Task StartTrackSessionAsync() {
this.IsSessionActive = true;

ExtendSession();

await StartSessionTimerAsync();
}

/// <summary>
/// Stop tracking a session manually. The OnSessionExpired will not be
/// called.
/// </summary>
public void EndTrackSession() {
this.IsSessionActive = false;

this.sessionExpirationTime = DateTime.FromFileTimeUtc(0);
}

/// <summary>
/// If the session is active, then the session time is extended based
/// on the current time and the SessionDuration.
/// duration.
/// </summary>
public void ExtendSession()
{
if (this.IsSessionActive == false) {
return;
}

this.sessionExpirationTime = DateTime.Now.Add(this.SessionDuration);
}

/// <summary>
/// Starts the session timer. When the session is expired and still
/// active the OnSessionExpired event is fired.
/// </summary>
/// <returns>The session timer async.</returns>
async Task StartSessionTimerAsync() {
if (this.IsSessionActive == false) {
return;
}

while (DateTime.Now < this.sessionExpirationTime) {
await Task.Delay(1000);
}

if (this.IsSessionActive && this.OnSessionExpired != null) {
this.IsSessionActive = false;

this.OnSessionExpired.Invoke(this, null);
}
}
}

然后,对于 Android 应用程序,我:

  • 在 MainActivity 中配置 SessionManager 以在 session 过期时注销。

  • 覆盖 MainActivity 中的 OnUserInteraction 方法以延长用户交互的 session 计时器。

    public class MainActivity /* ... */ {
    protected override void OnCreate(Bundle bundle)
    {
    // ...

    SessionManager.Instance.SessionDuration = TimeSpan.FromSeconds(10);
    SessionManager.Instance.OnSessionExpired = HandleSessionExpired;
    }

    public override void OnUserInteraction()
    {
    base.OnUserInteraction();

    SessionManager.Instance.ExtendSession();
    }

    async void HandleSessionExpired(object sender, EventArgs e)
    {
    await App.Instance.DoLogoutAsync();
    }
    }

对于 iOS,我执行以下操作:

  • 在 AppDelegate 中配置 SessionManager 以在 session 过期时注销。

  • 将自定义手势处理程序添加到键窗口以延长用户交互的 session 计时器。

    public partial class AppDelegate /* ... */
    {
    public override bool FinishedLaunching(UIApplication app, NSDictionary options)
    {
    // ...

    var success = base.FinishedLaunching(app, options);

    if (success) {
    SessionManager.Instance.SessionDuration = TimeSpan.FromSeconds(10);
    SessionManager.Instance.OnSessionExpired += HandleSessionExpired;

    var allGesturesRecognizer = new AllGesturesRecognizer(delegate
    {
    SessionManager.Instance.ExtendSession();
    });

    this.Window.AddGestureRecognizer(allGesturesRecognizer);
    }

    return success;
    }

    async void HandleSessionExpired(object sender, EventArgs e)
    {
    await App.instance.DoLogoutAsync();
    }

    class AllGesturesRecognizer: UIGestureRecognizer {
    public delegate void OnTouchesEnded();

    private OnTouchesEnded touchesEndedDelegate;

    public AllGesturesRecognizer(OnTouchesEnded touchesEnded) {
    this.touchesEndedDelegate = touchesEnded;
    }

    public override void TouchesEnded(NSSet touches, UIEvent evt)
    {
    this.State = UIGestureRecognizerState.Failed;

    this.touchesEndedDelegate();

    base.TouchesEnded(touches, evt);
    }
    }
    }

编辑: Bolo 在下面提出了一个很好的问题,所以我将其添加到这里。一旦用户登录,就会调用 StartTrackSessionAsync。当然,当用户注销应用程序时,也应该调用 EndTrackSession。

关于c# - Xamarin 表格 : Check if user inactive after some time log out app,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41466761/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com