How to get current device language if it's been changed after app start?

Viewed 773

When you start the app there are a lot of ways to get current device language:

  • CultureInfo.CurrentCulture
  • CultureInfo.CurrentUICulture
  • CultureInfo.DefaultThreadCurrentCulture
  • CultureInfo.DefaultThreadCurrentUICulture
  • Thread.CurrentThread.CurrentCulture
  • Thread.CurrentThread.CurrentCulture

But if I change device language while app is running, none of those values will be updated.

Is there a universal way to get current device language, or do I need to write code for each platform independently?

  • Android: CultureInfo.GetCultureInfo(Locale.Default.ToString().Replace('_', '-'))
  • iOS: CultureInfo.GetCultureInfo(NSLocale.CurrentLocale.LocaleIdentifier.Replace('_', '-'));
  • UWP: CultureInfo.GetCultureInfo(GlobalizationPreferences.Languages[0].ToString())
2 Answers

Each platform should provide a notification whenever the user changes the device's location or language. For example, iOS sends out a NSCurrentLocaleDidChangeNotification (Objective-C version) or currentLocaleDidChangeNotification (Swift version) that includes a language property.

You'll need to register for and observe the platform notifications using Xamarin.Forms local notifications procedure, which notes (bolding and italics added):

Each platform handles the creation, display, and consumption of local notifications differently. This article explains how to create a cross-platform abstraction to send, schedule, and receive local notifications with Xamarin.Forms.

There are a number of tutorials on how to do this. Search on xamarin forms local notification consume tutorial to find some. Note the term local. You're not wanting push notifications - that's something else.

To perform this task more simply, you might be able to use a plugin, such as edsnider/localnotificationsplugin on GitHub. You might find more by replacing the terms consume tutorial with plugin in your search.

Clarification:

  • local notifications occur intra-device, ie, the device or apps send notifications internally to be consumed by apps on the device.
  • push notifications occur when a request is made to an external service, such as Azure. That service would then broadcast a corresponding notification to the appropriate device(s).

Please try

Java.Util.Locale currentLanguage = this.Resources.Configuration.Locales.Get (0);

I am using this call in Xamarin Android and it works fine for me. "this" is in class Android.App.Activity.

Related