Get device's locale info(country and language). - Android Hardware

Android examples for Hardware:Device Feature

Description

Get device's locale info(country and language).

Demo Code


import java.util.Locale;

import android.content.Context;
import android.content.res.Configuration;
import android.provider.Settings;
import android.text.TextUtils;

public class Main {
  /**/* w ww  . j  a va  2  s . c o  m*/
   * Get device's locale info(country and language).
   *
   * @param context
   *          The context of the application.
   * @return result[0] for country, result[1] for language.
   */
  public static String[] getLocaleInfo(Context context) {
    String[] result = new String[2];

    try {
      Locale locale = getLocale(context);
      if (locale != null) {
        result[0] = locale.getCountry();
        result[1] = locale.getLanguage();
      }
    } catch (Exception e) {

    }

    if (TextUtils.isEmpty(result[0])) {
      result[0] = "";
    }
    if (TextUtils.isEmpty(result[1])) {
      result[1] = "";
    }

    return result;
  }

  /**
   * Get user config locale. Use default locale if failed.
   */
  private static Locale getLocale(Context context) {
    Locale locale = null;
    try {
      Configuration configuration = new Configuration();
      configuration.setToDefaults();
      Settings.System.getConfiguration(context.getContentResolver(), configuration);
      if (configuration != null) {
        locale = configuration.locale;
      }
    } catch (Exception e) {

    }

    if (locale == null) {
      locale = Locale.getDefault();
    }

    return locale;
  }
}

Related Tutorials