c# - 如何使用 Xamarin 应用程序开发自动注销
问题描述
我必须在 App.xaml.cs 上添加功能才能使其正常工作。我在 OnStart 上添加了功能,但现在它会间歇性地一次又一次地让我退出应用程序。根据下面的代码,我需要做什么才能让它停止这样做。还是我的代码有问题。这是我的最新代码:
namespace MyApp
{
public partial class App : Application
{
DateTime _sessionStart;
public App()
{
InitializeComponent();
DatabaseManager = new DatabaseManager(new DatabaseService());
HttpManager = new HttpManager(new HTTPService());
MainPage = new NavigationPage(new LoginPage());
}
protected override void OnStart()
{
// Handle when your app starts
_sessionStart = DateTime.Now;
Device.StartTimer(TimeSpan.FromSeconds(60), () =>
{
// Check if 24 hours has elapsed
if (DateTime.Now > _sessionStart.AddHours(24))
{
//logout
MainPage = new NavigationPage(new LoginPage());
}
return true; // True = Repeat again, False = Stop the timer
});
}
protected override void OnSleep()
{
// Handle when your app sleeps
}
protected override void OnResume()
{
// Handle when your app resumes
}
}
解决方案
尝试通过在 Main 上注册自定义应用程序来跟踪空闲时间(应用程序中没有触摸的时间)。请参阅下面的示例
将TimeoutInSeconds
值设置为所需的时间间隔(例如 24 小时)
public class Application
{
// This is the main entry point of the application.
static void Main (string[] args)
{
UIApplication.Main (args, "MYCUSTOMAPP", "AppDelegate");
}
}
[Register ("MYCUSTOMAPP")]
public class MYCUSTOMAPP : UIApplication
{
const int TimeoutInSeconds = 1800; // 30 minutes
NSTimer idleTimer;
public override void SendEvent (UIEvent uievent)
{
base.SendEvent (uievent);
if (idleTimer == null)
ResetTimer ();
var allTouches = uievent.AllTouches;
if (allTouches != null && allTouches.Count > 0 && ((UITouch)allTouches.First ()).Phase == UITouchPhase.Began)
ResetTimer ();
}
void ResetTimer ()
{
if (idleTimer != null)
idleTimer.Invalidate ();
idleTimer = NSTimer.CreateScheduledTimer (new TimeSpan (0, 0, TimeoutInSeconds), (t) => TimerExceeded());
}
void TimerExceeded ()
{
NSNotificationCenter.DefaultCenter.PostNotificationName ("TimeoutNotification", null);
}
}
将观察者添加到您的视图控制器以将其注销
public override void ViewDidLoad()
{
base.ViewDidLoad();
NSNotificationCenter.DefaultCenter.AddObserver(new NSString("TimeoutNotification"), handleInactivityNotification);
}
public void handleInactivityNotification(NSNotification notification)
{
//Return to login page (Root view controller)
this.NavigationController.PopToRootViewController(true);
}
推荐阅读
- reactjs - 为什么扩展样式表不呈现?
- java - java如何知道lambda参数的类型?
- solr - Hybris/Solr 多词同义词在 solr admin ui 中工作,但 hybris 查询似乎是问题所在
- mysql - 为什么我的 Spring Batch Task 使用相同的 JOB_INSTANCE_ID 启动多个作业执行?
- javascript - 如何在反应 stepzilla 的某些步骤中隐藏导航按钮
- c# - 构建配置后如何更新 IOptions?
- r - 识别单个列的几个相邻行中的特定模式 - R
- python - 如何绘制形状点列表
- c++ - 使用 ESP8266/8285 将字符串从 Web 服务器转换为字节数组
- django - 在视图中使用表单集更新 3 个表单