what is the Function that takes place upon reopening app

356 Views Asked by At

I created an app using Xamarin.Forms. I am trying to detect if there is a change in phone's language each time the app is reopened after being closed using the back button. Tried to Debug.WriteLine on each of onStart, onSleep and onResume to see which one occurs when I open the app again but none of them worked. This is what i tried:

App.xaml.cs

protected override void OnStart()
{
    Debug.WriteLine("onresume");

    //CultureInfo language = CultureInfo.InstalledUICulture;
    //Thread.CurrentThread.CurrentUICulture = language;
    //ApplicationResource.Culture = language;
    //Application.Current.MainPage = new NavigationPage(new MainPage());
}

protected override void OnSleep()
{
    Debug.WriteLine("onsleep");
}

protected override void OnResume()
{
    Debug.WriteLine("onresume");
}

How do I know when the app is reopened so I could try the language change code?

2

There are 2 best solutions below

0
On

If i understand your concern correctly two things can help you:

  1. On android you can have a very wierd behavour if you do not specify SingleTask for your mainactivty. Basically if you "close" the app using Back button and then click on app icon, the app is launched from start recreating App but keeps static variables and the debugger is still connected too. You can detect it setting a static variable, then checking it with a breakpoint inside App.cs constructor. So the avoid such just use LaunchMode = LaunchMode.SingleTask inside the MainActivity.cs [Activity] attribute. This way after you return to the app after the Back button + click on icon you'll get a fresh new app with OnStart invoked.

Some could say to use LaunchMode.SingleInstance but it will kill your app if you click on push notification whie app is active so better use SingleTask, it will open smoothly the running app.

  1. To store and retrieve data between app launches use local persistent storage, full docs: https://learn.microsoft.com/en-us/xamarin/essentials/preferences?tabs=android. So when you got your language store it, then at app start (App.cs constructor) check values.
0
On

I had done a simple to test your code with the Android simulator. And I use the Console.WriteLine instead of the Debug.WriteLine.

I had found that:

  1. When the app exited with the back button, it will call the OnSleep method and if you get into the app in the recent task, it will call the OnStart method.
  2. When the app go to background with the home button, it will call the OnSleep methed too, but if you get into the app in the recent task, it will call the OnResume method.

So if you add a break point in the OnStart method, when you exit with the back button and get into the app again, it will hit the break point.