Last active
January 21, 2016 17:07
-
-
Save xleon/46880f6189acc02df663 to your computer and use it in GitHub Desktop.
Custom Android Application class to know when the app is in the background
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using Acr.UserDialogs; | |
using Android.App; | |
using Android.Content; | |
using Android.Content.Res; | |
using Android.OS; | |
using Android.Runtime; | |
using Android.Util; | |
using Plugin.CurrentActivity; | |
namespace Whatever | |
{ | |
[Application] | |
public class CustomAndroidApplication : Application | |
{ | |
public bool IsInBackground => _lifeCycleHandler.IsInBackground; | |
private CustomApplicationLifeCycleHandler _lifeCycleHandler; | |
public CustomAndroidApplication(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer) | |
{ | |
} | |
public override void OnCreate() | |
{ | |
base.OnCreate(); | |
_lifeCycleHandler = new CustomApplicationLifeCycleHandler(); | |
RegisterActivityLifecycleCallbacks(_lifeCycleHandler); | |
RegisterComponentCallbacks(_lifeCycleHandler); | |
} | |
public override void OnTerminate() | |
{ | |
base.OnTerminate(); | |
UnregisterActivityLifecycleCallbacks(_lifeCycleHandler); | |
UnregisterComponentCallbacks(_lifeCycleHandler); | |
} | |
} | |
internal class CustomApplicationLifeCycleHandler : Java.Lang.Object, Application.IActivityLifecycleCallbacks, IComponentCallbacks2 | |
{ | |
public bool IsInBackground { get; private set; } | |
public void OnActivityStarted(Activity activity) | |
{ | |
CrossCurrentActivity.Current.Activity = activity; | |
} | |
public void OnActivityCreated(Activity activity, Bundle savedInstanceState) | |
{ | |
CrossCurrentActivity.Current.Activity = activity; | |
} | |
public void OnActivityResumed(Activity activity) | |
{ | |
CrossCurrentActivity.Current.Activity = activity; | |
if (IsInBackground) | |
{ | |
Log.Warn(nameof(OneHourAndroidApplication), "app went to foreground"); | |
IsInBackground = false; | |
} | |
} | |
public void OnTrimMemory([GeneratedEnum] TrimMemory level) | |
{ | |
if (level == TrimMemory.UiHidden) | |
{ | |
Log.Warn(nameof(OneHourAndroidApplication), "app went to background"); | |
IsInBackground = true; | |
} | |
} | |
public void OnActivityDestroyed(Activity activity) { } | |
public void OnActivityPaused(Activity activity) { } | |
public void OnActivitySaveInstanceState(Activity activity, Bundle outState) { } | |
public void OnActivityStopped(Activity activity) { } | |
public void OnConfigurationChanged(Configuration newConfig) { } | |
public void OnLowMemory() { } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment