Search code examples
androidxamarin.androidmvvmcrossandroid-lifecyclebackground-foreground

Android Application Lifecycle


I see a lot of answers concerning the Activity Lifecycle and that for most part is clear to me. What I'm looking for is the Application Lifecycle. I have the following case:

  1. Application starts - Invalidate PIN
  2. A PIN has to be entered if it is stale of invalid
  3. Application is backgrounded (Android Home screen is visible) - Invalidate PIN
  4. The applicatiion is foregrounded (App becomes visible again) - goto step 2

With the Activity Lifecycle it is hard if not impossible to achieve. Any suggestions?


Solution

  • Inspired by the solution Doomsknight pointed me to I constructed this solution without the Timer as proposed in the proposed answer. Here's the code from my mainapplication.cs:

        public void OnActivityPaused(Activity activity)
        {
            _lastActivity = DateTime.Now;
        }
    
        public void OnActivityResumed(Activity activity)
        {
            CrossCurrentActivity.Current.Activity = activity;
    
            DateTime now = DateTime.Now;
            TimeSpan span = now - _lastActivity;
    
            if (span.TotalMilliseconds > 2000)
            {
                Notifier.Classes.Settings.IsPinValid = false;
            }
    
            _lastActivity = now;
        }