Get user language in android

http://web.archiveorange.com/archive/v/fwvde0wN3xcViMtADw6x

It seems that the navigator.language property is always "en" in webview on androids. Then what is the best way to get the user language? Get it in your own Java code and pour it into webview using javascript? or any other better way?

+6
source share
4 answers

The solution I found for this problem is to install the user agent through the webview settings:

WebSettings settings = wv.getSettings(); settings.setJavaScriptEnabled(true); settings.setUserAgentString(Locale.getDefault().getLanguage()); 

In your web content, you will receive it through:

 var userLang = navigator.userAgent; 

This should only be used for web browsing that displays local content.

+2
source

One way to solve this problem is to take userAgent - navigator.userAgent and run the regular expression when searching for the language.

Example ua string for Android (from http://www.gtrifonov.com/2011/04/15/google-android-user-agent-strings-2/ ):

Mozilla / 5.0 (Linux, U, Android 2.0.1, en-us; Droid Build / ESD56) AppleWebKit / 530.17 (KHTML, e.g. Gecko) Version /4.0 Mobile Safari / 530.17

so just map the language: navigator.userAgent.match(/[az]{2}-[az]{2}/) , which returns en-us

If you want to be truly secure, you can match the presence of Android 2.0.1; immediately preceding language. A regular expression for this would be as follows:

navigator.userAgent.match(/Android \d+(?:\.\d+){1,2}; [az]{2}-[az]{2}/).toString().match(/[az]{2}-[az]{2}/)

+3
source

this can help:

 Locale.getDefault().getDisplayLanguage(); 
+2
source

It really depends on where you need this information. If you need Android OS Locale, Locale.getDefault() will be enough. For the server side, the best way to locate Locale is to read the contents of the Accept-Language header of the HTTP protocol.
In this case, Locale discovery depends on the server-side technology used. For a simple servlet, you simply execute request.getLocale() , for JSF you will read it from UIViewRoot, etc.

0
source

Source: https://habr.com/ru/post/891813/


All Articles