fish potato
fish potato

Reputation: 5629

Get the language of user in android

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

It seems that navigator.language property is always "en" in webview on androids. Then, what is the best way to get the language of user? Get it in native java code and pour it into webview by javascript? or any other better way?

Upvotes: 7

Views: 10012

Answers (4)

mtotschnig
mtotschnig

Reputation: 1481

The solution I found to this problem is to set the user agent through the webview's settings:

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

In your webcontent you then retrieve it through:

var userLang = navigator.userAgent;

This should only be used for a webview displaying local content.

Upvotes: 2

wmute
wmute

Reputation: 1601

One way to solve this is to take the userAgent - navigator.userAgent, and run a regex on it looking for the language.

Example Android ua string (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, like Gecko) Version/4.0 Mobile Safari/530.17

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

If you want to be really safe, you can match for the presence of Android 2.0.1; immediately preceding the language. The regex for that would be:

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

Upvotes: 3

Paweł Dyda
Paweł Dyda

Reputation: 18662

It really depends where you need this information. If you need Android OS Locale, Locale.getDefault() would be just enough. For the server side, the best way to detect Locale is to read the contents of Accept-Language header of HTTP protocol.
In such case Locale detection depends on the server side technology used. For simple Servlet, you would just do request.getLocale(), for JSF you would read it from UIViewRoot, etc.

Upvotes: 0

BobMcboberson
BobMcboberson

Reputation: 2065

this might help:

Locale.getDefault().getDisplayLanguage();

Upvotes: 2

Related Questions