Skip to content

Instantly share code, notes, and snippets.

@peterfoot
Created February 10, 2023 13:40
Show Gist options
  • Save peterfoot/d4cdbba77a4c2ca13c27fb94ad175405 to your computer and use it in GitHub Desktop.
Save peterfoot/d4cdbba77a4c2ca13c27fb94ad175405 to your computer and use it in GitHub Desktop.
Get current Android Activity for a cross-platform .NET library
public static bool TryGetCurrentActivity(out Activity activity)
{
activity = null;
#if NET6_0_OR_GREATER
// check for Uno without taking a hard dependency
var t = Type.GetType("Uno.UI.ContextHelper, Uno, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null", false, true);
if (t != null)
{
activity = (Activity)t.GetProperty("Current", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public).GetValue(null);
}
else
{
// try Maui Essentials if not
t = Type.GetType("Microsoft.Maui.ApplicationModel.Platform, Microsoft.Maui.Essentials, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", false, true);
if (t != null)
{
activity = (Activity)t.GetProperty("CurrentActivity", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public).GetValue(null);
}
}
#else
// check for Xamarin.Essentials without taking a hard dependency
var t = Type.GetType("Xamarin.Essentials.Platform, Xamarin.Essentials, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", false, true);
if (t != null)
{
activity = (Activity)t.GetProperty("CurrentActivity", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public).GetValue(null);
}
#endif
return activity != null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment