App crashes after throwing an error ' Window was already created'

Manickam, Suraj 320 Reputation points
2024-05-29T09:32:36.64+00:00

Platform : Android

Version : MAUI 8

Description :

I was trying to invoke platform specific code by implementing broadcast Receiver for android, When I tried to register the receiver onResume( ) , app crashed with an error "Window was already created" . The same code works fine in Xamarin though.

  protected override void OnResume()
  {
      base.OnResume();
      if (null != _broadcastReceiver)
      {
          // Register the broadcast receiver
          IntentFilter filter = new IntentFilter(DataWedgeReceiver.IntentAction);
          filter.AddCategory(DataWedgeReceiver.IntentCategory);
          Android.App.Application.Context.RegisterReceiver(_broadcastReceiver, filter);
      }
  }
.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
3,232 questions
{count} votes

Accepted answer
  1. Leon Lu (Shanghai Wicresoft Co,.Ltd.) 72,336 Reputation points Microsoft Vendor
    2024-05-30T09:20:41.15+00:00

    Hello,

    You can move MainActivity.cs code to the App.xaml.cs.

    Base on this Cross-platform lifecycle events.

    Window.Create corresponds to the Android platform's OnPostCreate Window.Activated corresponds to the Android platform's OnResume Window.Deactivated corresponds to the Android platform's OnPause

    Here is my edited code in the App.xaml.cs.

    #if ANDROID
    using Android.App;
    using Android.Content;
    using Android.Content.PM;
    using Android.OS;
     
    using CommunityToolkit.Mvvm.Messaging;
    using CommunityToolkit.Mvvm.Messaging.Messages;
    using MauiApp5.Platforms.Android;
    #endif
     
    namespace MauiApp5
    {
        public partial class App : Microsoft.Maui.Controls.Application
        {
            public App()
            {
                InitializeComponent();
     
              MainPage =new AppShell();
            }
            protected override Window CreateWindow(IActivationState? activationState)
            {
     
                Window window = base.CreateWindow(activationState);
    #if ANDROID
                window.Created += (s, e) =>
                {
                    // Custom logic
     
                    RegisterReceivers();
                    _broadcastReceiver = new DataWedgeReceiver();
                    LaserScanModel helpermodel = LaserScanModel.GetInstance();
     
     
                    _broadcastReceiver.scanDataReceived += (s, scanData) =>
                    {
                        WeakReferenceMessenger.Default.Send(new ItemMessage(scanData), "LaserScan");
                    };
                    CreateProfile();
     
                };
                window.Activated += (s, e) =>
                {
                    if (null != _broadcastReceiver)
                    {
                        // Register the broadcast receiver
                        IntentFilter filter = new IntentFilter(DataWedgeReceiver.IntentAction);
                        filter.AddCategory(DataWedgeReceiver.IntentCategory);
                       Platform.AppContext.RegisterReceiver(_broadcastReceiver, filter);
                    }
     
                };
     
                window.Deactivated += (s, e) =>
                {
     
                    if (null != _broadcastReceiver)
                    {
                        // Unregister the broadcast receiver
                        Platform.AppContext.UnregisterReceiver(_broadcastReceiver);
                    }
     
                };
     
    #endif
                return window;
            }
     
    #if ANDROID
     
            private static string ACTION_DATAWEDGE_FROM_6_2 = "com.symbol.datawedge.api.ACTION";
            private static string EXTRA_CREATE_PROFILE = "com.symbol.datawedge.api.CREATE_PROFILE";
            private static string EXTRA_SET_CONFIG = "com.symbol.datawedge.api.SET_CONFIG";
            private static string EXTRA_PROFILE_NAME = "Inventory DEMO";
            public static DataWedgeReceiver _broadcastReceiver = null;
     
            void RegisterReceivers()
            {
                IntentFilter filter = new IntentFilter();
                filter.AddCategory("android.intent.category.DEFAULT");
                filter.AddAction("com.ndzl.DW");
     
                Intent regres = Platform.CurrentActivity.RegisterReceiver(new DataWedgeReceiver(), filter);
            }
     
     
            void CreateProfile()
            {
                string profileName = EXTRA_PROFILE_NAME;
                SendDataWedgeIntentWithExtra(ACTION_DATAWEDGE_FROM_6_2, EXTRA_CREATE_PROFILE, profileName);
     
                //  Now configure that created profile to apply to our application
                Bundle profileConfig = new Bundle();
                profileConfig.PutString("PROFILE_NAME", profileName);
                profileConfig.PutString("PROFILE_ENABLED", "true"); //  Seems these are all strings
                profileConfig.PutString("CONFIG_MODE", "UPDATE");
                Bundle appConfig = new Bundle();
                appConfig.PutString("PACKAGE_NAME", Android.App.Application.Context.PackageName);      //  Associate the profile with this app
                appConfig.PutStringArray("ACTIVITY_LIST", new string[] { "*" });
                profileConfig.PutParcelableArray("APP_LIST", new Bundle[] { appConfig });
     
                //BARCODE READER
                Bundle barcodeProps = new Bundle();
                barcodeProps.PutString("barcode_trigger_mode", "1");
                Bundle barcodeConfig = new Bundle();
                barcodeConfig.PutString("PLUGIN_NAME", "BARCODE");
                barcodeConfig.PutString("RESET_CONFIG", "true"); //  This is the default but never hurts to specify
                barcodeConfig.PutBundle("PARAM_LIST", barcodeProps);
     
                //INTENT
                Bundle intentProps = new Bundle();
                intentProps.PutString("intent_output_enabled", "true");
                intentProps.PutString("intent_action", DataWedgeReceiver.IntentAction);
                intentProps.PutString("intent_delivery", "2");
                Bundle intentConfig = new Bundle();
                intentConfig.PutString("PLUGIN_NAME", "INTENT");
                intentConfig.PutString("RESET_CONFIG", "true");
                intentConfig.PutBundle("PARAM_LIST", intentProps);
     
                // Add configurations into a collection
                profileConfig.PutParcelableArray("PLUGIN_CONFIG", new Bundle[] { barcodeConfig, intentConfig });
                SendDataWedgeIntentWithExtra(ACTION_DATAWEDGE_FROM_6_2, EXTRA_SET_CONFIG, profileConfig);
            }
            void SendDataWedgeIntentWithExtra(String action, String extraKey, Bundle extras)
            {
                Intent dwIntent = new Intent();
                dwIntent.SetAction(action);
                dwIntent.PutExtra(extraKey, extras);
                Platform.AppContext.SendBroadcast(dwIntent);
            }
            void SendDataWedgeIntentWithExtra(String action, String extraKey, String extraValue)
            {
                Intent dwIntent = new Intent();
                dwIntent.SetAction(action);
                dwIntent.PutExtra(extraKey, extraValue);
                Platform.AppContext.SendBroadcast(dwIntent);
            }
     
    #endif
        }
    }
    

    As note: please keep the MainActivity.cs to the empty like following code.

    [Activity(Theme = "@style/Maui.SplashTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize | ConfigChanges.Density)]
    public class MainActivity : MauiAppCompatActivity
    {
    
     
        
    }
    

    Best Regards,

    Leon Lu


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful