Skip to content

Commit

Permalink
Use IActivityLifecycleCallbacks to remove static ref to Activity (#29)
Browse files Browse the repository at this point in the history
It feels a bit hairy to hold onto an `Activity` instance that could get destroyed.

This registers an `IActivityLifecycleCallbacks` listener to null out this reference.
  • Loading branch information
jonathanpeppers committed Mar 20, 2019
1 parent ff4b445 commit 967297b
Showing 1 changed file with 26 additions and 1 deletion.
27 changes: 26 additions & 1 deletion glidex.forms/Forms.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Android.App;
using Android.OS;
using System;

namespace Android.Glide
Expand All @@ -8,8 +9,9 @@ namespace Android.Glide
/// </summary>
public static class Forms
{
internal static Activity Activity { get; private set; }
internal static Activity Activity { get; set; }

static readonly ActivityLifecycle lifecycle = new ActivityLifecycle ();

/// <summary>
/// Initializes glidex.forms, put this after your `Xamarin.Forms.Forms.Init (this, bundle);` call.
Expand All @@ -30,6 +32,7 @@ public static void Init (Activity activity, bool debug = false)
{
Activity = activity;
IsDebugEnabled = debug;
activity.Application.RegisterActivityLifecycleCallbacks (lifecycle);
}

/// <summary>
Expand All @@ -52,5 +55,27 @@ internal static void Debug (string format, params object [] args)
if (IsDebugEnabled)
Util.Log.Debug (Tag, format, args);
}

class ActivityLifecycle : Java.Lang.Object, Application.IActivityLifecycleCallbacks
{
public void OnActivityCreated (Activity activity, Bundle savedInstanceState) { }

public void OnActivityDestroyed (Activity activity)
{
if (Activity == activity) {
Activity = null;
}
}

public void OnActivityPaused (Activity activity) { }

public void OnActivityResumed (Activity activity) { }

public void OnActivitySaveInstanceState (Activity activity, Bundle outState) { }

public void OnActivityStarted (Activity activity) { }

public void OnActivityStopped (Activity activity) { }
}
}
}

0 comments on commit 967297b

Please sign in to comment.