'what is the Function that takes place upon reopening app
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?
Solution 1:[1]
If i understand your concern correctly two things can help you:
- On android you can have a very wierd behavour if you do not specify
SingleTaskfor your mainactivty. Basically if you "close" the app using Back button and then click on app icon, the app is launched from start recreatingAppbut keeps static variables and the debugger is still connected too. You can detect it setting a static variable, then checking it with a breakpoint insideApp.csconstructor. So the avoid such just useLaunchMode = LaunchMode.SingleTaskinside theMainActivity.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 withOnStartinvoked.
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.
- To store and retrieve data between app launches use local persistent storage, full docs: https://docs.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.
Solution 2:[2]
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:
- 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.
- 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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Liyun Zhang - MSFT |
