I have a .Net Maui application that runs on iOS, Android and Windows and receives push notifications.
On Windows, when I click a notification nothing happens.
I would like to "raise" the active instance that is opened, something like window.Focus() when a notification is clicked.
The way it was made in Xamarin Forms:
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
Frame rootFrame = Window.Current.Content as Frame;
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active.
if (rootFrame == null)
{
// Create a Frame to act as the navigation context and navigate to the first page.
rootFrame = new Frame();
rootFrame.NavigationFailed += OnNavigationFailed;
if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
//TODO: Load state from previously suspended application.
}
// Place the frame in the current Window.
Window.Current.Content = rootFrame;
}
if (rootFrame.Content == null)
{
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter.
rootFrame.Navigate(typeof(MainPage), e.Arguments);
}
// Ensure the current window is active.
Window.Current.Activate();
}
I found examples but in all of them the App class inherits from Application which is not the case on Maui since it inherits from MauiWinUIApplication.
My App.xamls.cs:
public partial class App : MauiWinUIApplication
{
/// <summary>
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
///
private readonly SingleInstanceDesktopApp _singleInstanceApp;
LaunchActivatedEventArgs incomeArgs;
public App()
{
this.InitializeComponent();
_singleInstanceApp = new SingleInstanceDesktopApp("GIKI");
_singleInstanceApp.Launched += OnSingleInstanceLaunched;
}
protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp();
protected override async void OnLaunched(LaunchActivatedEventArgs args)
{
incomeArgs = args;
_singleInstanceApp.Launch(args.Arguments);
}
private void OnSingleInstanceLaunched(object? sender, SingleInstanceLaunchEventArgs e)
{
try
{
if (e.IsFirstLaunch)
{
base.OnLaunched(incomeArgs);
}
else
{
}
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex}");
}
}
void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
{
throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
}
private void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
//TODO: Save application state and stop any background activity
deferral.Complete();
}
}
The OnSingleINstanceLauched method is working. What next, on "else" to show the window in case it is in background, for example?
base.OnLaunched,this.Applicationwill have value. And there is a api namedAppInstance.GetCurrent();, you may can use it do something.