Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to format user-agent string in an Android WebView App?

In my android web app I want to modify my user agent so that I can identify it on my server and on google analytics.

Currently the user-agent looks like this:

Mozilla/5.0 (Linux; Android 7.0; Moto G (4) Build/NPJ25.93-14; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/56.0.2924.87 Mobile Safari/537.36

I should probably include a tag that google analytics can pick up as a web-app and another tag that mentions the version of my android app. This would be in addition to the webview version. I want google analytics to keep providing me the correct data for Mobile Device info, Android version, OS, etc. Probably only the Browser field should be changed.

I know how I can change the user agent string. I want to know what are the things I should keep in mind while creating a user-agent string.

like image 353
Vedant Agarwala Avatar asked Mar 09 '23 11:03

Vedant Agarwala


1 Answers

Thanks to this blog, I found the answer. You should append the "Browser" and "Browser version" to the WebView's existing user-agent string and google analytics will pick it up.

Code:

WebSettings webSettings = webView.getSettings();
String userAgent = String.format("%s [%s/%s]", webSettings.getUserAgentString(), "App Android", BuildConfig.VERSION_NAME);
webSettings.setUserAgentString(userAgent);

In Google Analytics the "Browser" dimension value is "App Android" and "Browser Version" is the string in your build config.

like image 141
Vedant Agarwala Avatar answered Apr 07 '23 00:04

Vedant Agarwala