Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 770
fish potato Avatar asked Jul 01 '11 11:07

fish potato


People also ask

What is Locale default Android?

The default Locale is constructed statically at runtime for your application process from the system property settings, so it will represent the Locale selected on that device when the application was launched.


2 Answers

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.

like image 117
mtotschnig Avatar answered Oct 13 '22 00:10

mtotschnig


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}/)

like image 30
wmute Avatar answered Oct 13 '22 01:10

wmute