开发者

Get the language of user in android

开发者 https://www.devze.com 2023-03-16 21:59 出处:网络
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 lan

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?


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.


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


this might help:

Locale.getDefault().getDisplayLanguage();


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消