简体   繁体   中英

.Net MAUI WinUI push notification opening new instance

Every click on a push notification received opens a new instance of the app.

The documentation and many other samples that I found use the following code:

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();
    }

But this is not working for me. The following line is causing a NullReferenceException on Window.Current.Content .

Frame rootFrame = Window.Current.Content as Frame;

I also noticed that my App class is inheriting from MauiWinUIApplication, and I think this is the point. Maybe this MauiWinUIApplication has a different way to deal with this problem but I can't find:

public partial class App : MauiWinUIApplication

How to prevent opening new instance every time a push notification is clicked?

I'm using: Visual Studio Community 2022 17.4.0, Maui.Net 6

Thanks!

The default behavior of WinUI in .Net Maui is to allow multiple instances of your app to run which will give us a lot of problems for various reasons such as a SQLite database, or deep linking etc. And this is known issue that's being tracked in Simplify and make more robust the process for Single-instance WinUI apps .

As an alternative workaround, you can refer to Making the app single-instanced on how to make the app single-instanced which will prevent opening new instance every time a push notification is clicked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM