如果在 x 时间内没有用户交互(用户空闲),则导航回主页

Lea*_*oza 1 c# android timer maui .net-maui

我正在开发一个自我管理应用程序,我需要实现一个不活动计时器或类似的东西来了解用户是否空闲(在 x 时间内不与视图交互),因此当发生这种情况时,它会返回主页。

这可能吗?已检查应用程序生命周期文档,但没有找到任何相关信息。

我正在考虑为每个视图制作一个计时器,当时间到来时 x 重定向,但它似乎不太理想。有没有办法将其直接集成到应用程序中,或者我真的必须为每个视图设置一个计时器吗?

抱歉,如果我的问题不清楚。请询问,如果没有意义我可以更新。

Cfu*_*fun 5

跨平台代码(常用)

using Timer = System.Timers.Timer;
Run Code Online (Sandbox Code Playgroud)

应用程序.xaml.cs

Timer IdleTimer = new Timer( 60 * 1000);  //each 1 minute

public App()
{
    InitializeComponent();
    MainPage = new AppShell();

    IdleTimer.Elapsed += Idleimer_Elapsed;
    IdleTimer.Start();
}

async void Idleimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
    Console.WriteLine(":::Elapsed");
    if (MainThread.IsMainThread)
        await Shell.Current.Navigation.PopToRootAsync();
    else
        MainThread.BeginInvokeOnMainThread(async () => await Shell.Current.Navigation.PopToRootAsync());}

public void ResetIdleTimer()
{
    IdleTimer.Stop();
    IdleTimer.Start();
}
Run Code Online (Sandbox Code Playgroud)

安卓

要检测 Android 上的用户交互,您可以依赖OnUserInteraction()

安卓文档

MainActivity.cs

public override void OnUserInteraction()
{
    base.OnUserInteraction();
    (App.Current as App).ResetIdleTimer();
}
Run Code Online (Sandbox Code Playgroud)

iOS系统

在 ios 上,您可以在应用程序级别源监听 touche 事件 。

程序.cs

static void Main(string[] args)
{
   UIApplication.Main(args, typeof(CustomApplication), typeof(AppDelegate));
}
Run Code Online (Sandbox Code Playgroud)

自定义应用程序.cs

public class CustomApplication : UIApplication
{
    public CustomApplication() : base()
    {
    }

    public CustomApplication(IntPtr handle) : base(handle)
    {
    }

    public CustomApplication(Foundation.NSObjectFlag t) : base(t)
    {
    }
    public override void SendEvent(UIEvent uievent)
    {
        if (uievent.Type == UIEventType.Touches)
        {
            if (uievent.AllTouches.Cast<UITouch>().Any(t => t.Phase == UITouchPhase.Began))
            {
                (App.Current as App).ResetIdleTimer();
            }
        }

        base.SendEvent(uievent);
    }
Run Code Online (Sandbox Code Playgroud)

视窗

对于 Windows,您可以侦听一些本机窗口事件,例如WM_NCACTIVATE: 0x0086WM_SETCURSOR 0x0020WM_MOUSEACTIVATE

我确信有一种更有效的方法来监听鼠标光标移动事件,由于某些原因在此级别没有报告(例如WM_MOUSEMOVE)。

MauiProgram.cs

            .ConfigureLifecycleEvents(events =>
            {
#if WINDOWS
                events
                    .AddWindows(windows => windows
                        .OnPlatformMessage((window, args) =>
                        {
                            if (args.MessageId == Convert.ToUInt32("0x0086", 16) ||
                                args.MessageId == Convert.ToUInt32("0x0020", 16) ||
                                args.MessageId == Convert.ToUInt32("0x0021", 16) )
                            {
                                (App.Current as App).ResetIdleTimer();
                            }
                        }));
#endif
Run Code Online (Sandbox Code Playgroud)