source

장치에서 현재 언어 가져오기

nicesource 2023. 6. 3. 08:30
반응형

장치에서 현재 언어 가져오기

안드로이드 기기에서 현재 언어를 어떻게 선택할 수 있습니까?

Android 4.1.2 장치에서 로케일 방법을 확인했으며 결과는 다음과 같습니다.

Locale.getDefault().getLanguage()       ---> en      
Locale.getDefault().getISO3Language()   ---> eng 
Locale.getDefault().getCountry()        ---> US 
Locale.getDefault().getISO3Country()    ---> USA 
Locale.getDefault().getDisplayCountry() ---> United States 
Locale.getDefault().getDisplayName()    ---> English (United States) 
Locale.getDefault().toString()          ---> en_US
Locale.getDefault().getDisplayLanguage()---> English
Locale.getDefault().toLanguageTag()     ---> en-US

선택한 장치 언어를 가져오려면 다음과 같은 작업을 수행할 수 있습니다.

Locale.getDefault().getDisplayLanguage();

사용할 수 있습니다.Locale.getDefault().getLanguage(); 코드 " "를 것.

저에게 효과가 있었던 것은 다음과 같습니다.

Resources.getSystem().getConfiguration().locale;

Resources.getSystem()시스템 리소스(응용 프로그램 리소스 없음)에 대한 액세스만 제공하고 현재 화면에 대해 구성되지 않은 글로벌 공유 리소스 개체를 반환합니다(차원 단위를 사용할 수 없으며 방향에 따라 변경되지 않음).

ㅠㅠgetConfiguration.locale이제는 더 이상 사용되지 않습니다. Android Nougat에서 기본 로케일을 가져오는 선호되는 방법은 다음과 같습니다.

Resources.getSystem().getConfiguration().getLocales().get(0);

이전 Android 버전과의 호환성을 보장하기 위해 가능한 솔루션은 간단한 확인입니다.

Locale locale;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    locale = Resources.getSystem().getConfiguration().getLocales().get(0);
} else {
    //noinspection deprecation
    locale = Resources.getSystem().getConfiguration().locale;
}

갱신하다

지원 라이브러리부터 Android 버전은 이전 버전과 호환되는 편리한 방법을 제공하므로 확인할 필요가 없습니다.

간단히 전화하기:

ConfigurationCompat.getLocales(Resources.getSystem().getConfiguration());

현재 로케일에서 언어를 '추출'할 수 있습니다.표준 Java API를 통해 또는 Android 컨텍스트를 사용하여 로케일을 추출할 수 있습니다.예를 들어, 아래 두 줄은 동일합니다.

String locale = context.getResources().getConfiguration().locale.getDisplayName();
String locale = java.util.Locale.getDefault().getDisplayName();

다른 사람들의 시간 및/또는 혼란을 줄이기 위해 위의 요한 펠그림이 제안한 두 가지 대안을 시도해 보았는데, 기본 위치가 변경되었는지 여부에 관계없이 장치에서 이 두 가지 대안은 동등합니다.

따라서 내 장치의 기본 설정은 영어(United Kindom)이며, 이 상태에서는 예상대로 요한의 답변에 있는 두 문자열 모두 동일한 결과를 제공합니다.그런 다음 전화 설정에서 로케일을 변경하고(이탈리아(이탈리아)) 다시 실행하면 요한의 답변에 있는 두 문자열 모두 로케일을 이탈리아(이탈리아)로 지정합니다.

따라서 저는 요한의 원래 게시물이 정확하고 그렉의 코멘트가 부정확하다고 생각합니다.

로케일 참조에서 설명한 것처럼 언어를 얻는 가장 좋은 방법은 다음과 같습니다.

Locale.getDefault().getLanguage()

이 메서드는 ISO 639-1 표준 아트에 따라 언어 ID가 있는 문자열을 반환합니다.

이것을 사용할 수 있습니다.

boolean isLang = Locale.getDefault().getLanguage().equals("xx");

"xx"가 "en", "fr", "sp", "ar" 등의 언어 코드일 때.

API 24를 합니다.LocaleList.getDefault().get(0).getLanguage() 않으면 그외를 사용합니다.Locale.getDefault.getLanguage()

private fun getSystemLocale() = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    LocaleList.getDefault().get(0).language
} else {
    Locale.getDefault().language
}

참조: https://developer.android.com/guide/topics/resources/multilingual-support

이 해결책은 저에게 효과가 있었습니다.그러면 안드로이드 기기의 언어(앱의 로컬 언어가 아님)가 반환됩니다.

String locale = getApplicationContext().getResources().getConfiguration().locale.getLanguage();

이렇게 하면 "en", "de", "fr" 또는 장치 언어가 설정된 모든 항목이 반환됩니다.

요한 펠그림의 대답에 덧붙이자면

context.getResources().getConfiguration().locale
Locale.getDefault()

다음과 같은 이유로 동등합니다.android.text.format.DateFormat클래스는 두 가지 모두를 상호 교환적으로 사용합니다. 예를 들어,

private static String zeroPad(int inValue, int inMinDigits) {
    return String.format(Locale.getDefault(), "%0" + inMinDigits + "d", inValue);
}

그리고.

public static boolean is24HourFormat(Context context) {
    String value = Settings.System.getString(context.getContentResolver(),
            Settings.System.TIME_12_24);

    if (value == null) {
        Locale locale = context.getResources().getConfiguration().locale;

    // ... snip the rest ...
}

시스템 리소스에서 로케일을 가져올 수 있습니다.

PackageManager packageManager = context.getPackageManager();
Resources resources = packageManager.getResourcesForApplication("android");
String language = resources.getConfiguration().locale.getLanguage();

현재 언어를 확인하려면 @Sarpe(@Thorbear)의 답변을 사용합니다.

val language = ConfigurationCompat.getLocales(Resources.getSystem().configuration)?.get(0)?.language
// Check here the language.
val format = if (language == "ru") "d MMMM yyyy г." else "d MMMM yyyy"
val longDateFormat = SimpleDateFormat(format, Locale.getDefault())
public void GetDefaultLanguage( ) {
    try {
        String langue = Locale.getDefault().toString(); //        ---> en_US
        /*
        Log.i("TAG", Locale.getDefault().getLanguage() ); //       ---> en
        Log.i("TAG", Locale.getDefault().getISO3Language()  ); //  ---> eng
        Log.i("TAG", Locale.getDefault().getCountry()  ); //       ---> US
        Log.i("TAG", Locale.getDefault().getISO3Country()  ); //   ---> USA
        Log.i("TAG", Locale.getDefault().getDisplayCountry() ); // ---> United States
        Log.i("TAG", Locale.getDefault().getDisplayName() ); //    ---> English (United States)
        Log.i("TAG", Locale.getDefault().toString()   ); //        ---> en_US
        Log.i("TAG", Locale.getDefault().getDisplayLanguage() ); //---> English 
        */

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            langue = Locale.getDefault().toLanguageTag(); //     ---> en-US
            url_Api = getUrlMicrosoftLearn(langue);
            Log.i("TAG", url_Api );
            Log.i("TAG", langue );
        }else{
            langue = langue.replace("_","-"); //     ---> en-US
            url_Api = getUrlMicrosoftLearn(langue);
            Log.i("TAG", url_Api );
            Log.i("TAG", langue );
        }
    }catch (Exception ex) {
        Log.i("TAG", "Exception:GetDefaultLanguage()", ex);
    }
}

public String getUrlMicrosoftLearn(String langue) {
    return "https://learn.microsoft.com/"+langue+"/learn";
}

위의 답변은 단순한 중국어와 전통적인 중국어를 구별하지 못합니다. Locale.getDefault().toString()" " "."zh_CN", "zh_TW", "en_US" 등을는작업하.

참조: https://developer.android.com/reference/java/util/Locale.html, ISO 639-1은 OLD입니다.

다른 사람들은 장치 언어에 대해 좋은 답변을 해주었습니다.

만약 당신이 앱 언어를 원한다면 그것을 하는 가장 쉬운 방법은 추가하는 것입니다.app_lang의 열신쇠의 strings.xml파일을 지정하고 각 언어에 대한 언어도 지정합니다.

이렇게 하면 앱의 기본 언어가 장치 언어와 다를 경우 해당 언어를 서비스에 대한 매개 변수로 보내도록 선택할 수 있습니다.

이 코드를 사용하여 키보드의 현재 상태를 확인할 수 있습니다.

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
InputMethodSubtype ims = imm.getCurrentInputMethodSubtype();
String locale = ims.getLocale();

입력할 수 없는 언어를 선택한 경우 이 그리스어가 도움이 될 수 있습니다.

getDisplayLanguage().toString() = English
getLanguage().toString() = en 
getISO3Language().toString() = eng
getDisplayLanguage()) = English
getLanguage() = en
getISO3Language() = eng

이제 그리스어로 해보세요.

getDisplayLanguage().toString() = Ελληνικά
getLanguage().toString() = el
getISO3Language().toString() = ell
getDisplayLanguage()) = Ελληνικά
getLanguage() = el
getISO3Language() = ell
public class LocalUtils {

    private static final String LANGUAGE_CODE_ENGLISH = "en";


    // returns application language eg: en || fa ...
    public static String getAppLanguage() {
        return Locale.getDefault().getLanguage();
    }

    // returns device language eg: en || fa ...
    public static String getDeviceLanguage() {
        return ConfigurationCompat.getLocales(Resources.getSystem().getConfiguration()).get(0).getLanguage();
    }

    public static boolean isDeviceEnglish() {
        return getDeviceLanguage().equals(new Locale(LANGUAGE_CODE_ENGLISH).getLanguage());
    }

    public static boolean isAppEnglish() {
        return getAppLanguage().equals(new Locale(LANGUAGE_CODE_ENGLISH).getLanguage());
    }


}

Log.i("AppLanguage: ",     LocalUtils.getAppLanguage());
Log.i("DeviceLanguage: ",  LocalUtils.getDeviceLanguage());
Log.i("isDeviceEnglish: ", String.valueOf(LocalUtils.isDeviceEnglish()));
Log.i("isAppEnglish: ",    String.valueOf(LocalUtils.isAppEnglish()));

기본적인 코틀린의 대답:

Locale.getDefault().language

여기에 있는 대부분의 답변은 응용 프로그램의 언어를 제공하므로 주의하십시오.이 응용 프로그램이 장치와 다른 언어를 사용하거나 설정할 수 있는 경우가 있습니다.

실제 장치 언어를 가져오려면(예, 설정에 여러 언어가 추가된 경우 모든 언어가 반환됩니다!)

코틀린:

// Will return something like ["en_US", "de_DE"]
val deviceLanguages: LocaleListCompat = ConfigurationCompat.getLocales(Resources.getSystem().configuration)
// Will return the actual language in use, like "en" or "de". The first language in the above code will be the default language
val currentActiveDeviceLanguage = languages.get(0).language 

Locale.getDefault().getLanguage()는 VM 언어입니다.

Locale.getDefault().getLanguage()

앱을 실행 중인 현재 VM 인스턴스의 언어입니다.DateFormat 등의 Java 클래스에서 사용됩니다.특정 Java 클래스를 사용하는 경우 앱 로케일을 변경할 때 이를 수정해야 할 수 있습니다.앱 로케일을 변경하는 동안 수정한 경우 안드로이드 언어와 다릅니다.

context.getConfiguration().locale.getLanguage()는 활동 언어입니다.

context.getConfiguration().locale.getLanguage()

활동에 설정된 언어입니다.최신 SDK 버전에서는 다음을 선호합니다.

context.getConfiguration().getLocales().get(0).getLanguage()

자원.getSystem().getConfiguration().getLocales()는 사용자가 시스템 수준에서 추가한 모든 로케일을 제공합니다.

사용자가 시스템 수준에서 설정한 첫 번째 로케일이 제공됩니다.

Resources.getSystem().getConfiguration().getLocales().get(0).getLanguage()

많은 사용자가 다국어를 사용하므로 로케일을 반복 사용할 수 있습니다.

두 개의 언어가 있습니다.

OS의 기본 언어:

Locale.getDefault().getDisplayLanguage();

현재 응용 프로그램 언어:

getResources().getConfiguration().locale.getDisplayLanguage();//return string
Locale.getDefault().getDisplayLanguage()

당신에게 줄 것입니다Written예를 들어 언어의 이름,English, Dutch, French

Locale.getDefault().getLanguage()

당신에게 줄 것입니다language code예를 들어:en, nl, fr

두 메서드 모두 String을 반환합니다.

장치의 언어를 올바르게 가져오는 방법은 다음과 같습니다.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    return context.getResources().getConfiguration().getLocales().get(0);
} else {
    return context.getResources().getConfiguration().locale;
}

도움이 되길 바랍니다.

나의 해결책은 이렇습니다.

@SuppressWarnings("deprecation")
public String getCurrentLocale2() {
    return Resources.getSystem().getConfiguration().locale.getLanguage();
}

@TargetApi(Build.VERSION_CODES.N)
public Locale getCurrentLocale() {
    getResources();
    return Resources.getSystem().getConfiguration().getLocales().get(0);
}

그리고 나서.

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                Log.e("Locale", getCurrentLocale().getLanguage());
            } else {
                Log.e("Locale", getCurrentLocale2().toString());
            }

표시 ---> en

여기 장치 국가를 가져오는 코드가 있습니다.모든 버전의 Android eveno와 호환됩니다.

해결책: 사용자가 get country 이상의 SIM 카드를 가지고 있지 않은 경우 전화 설정 또는 현재 언어 선택 중에 사용됩니다.

public static String getDeviceCountry(Context context) {
    String deviceCountryCode = null;

    final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

        if(tm != null) {
            deviceCountryCode = tm.getNetworkCountryIso();
        }

    if (deviceCountryCode != null && deviceCountryCode.length() <=3) {
        deviceCountryCode = deviceCountryCode.toUpperCase();
    }
    else {
        deviceCountryCode = ConfigurationCompat.getLocales(Resources.getSystem().getConfiguration()).get(0).getCountry().toUpperCase();
    }

  //  Log.d("countryCode","  : " + deviceCountryCode );
    return deviceCountryCode;
}

제트팩 합성을 사용하는 경우

컴포저블 기능의 내부

Context.applicationContext.resources.configuration.locales.get(0).language 

.setLanguage(로컬)를 사용할 수 있습니다.LanguageTag(Locale.getDefault().getLanguage()))의 경우 양호합니다.

아래 코드는 미국과 같은 국가 코드를 반환합니다.

Locale.getDefault().getCountry()
if(Locale.getDefault().getDisplayName().equals("हिन्दी (भारत)")){
    // your code here
}

언급URL : https://stackoverflow.com/questions/4212320/get-the-current-language-in-device

반응형