Houcine
Houcine

Reputation: 24181

Get User Agent in my app which doesn't contain a webview

I can ask WebView.getWebSettings().getUserAgentString() to get the user agent, but this doesn't work all that well for my app as I need to instantiate a WebView first even though I don't need.

Is there another way to get to the User Agent without using a WebView.getSetting, because in my application, I don't need a webView?

Help me please

Upvotes: 1

Views: 2770

Answers (4)

Prakash Nadar
Prakash Nadar

Reputation: 2711

From android Source code.

public static String getDefaultUserAgent() {
    StringBuilder result = new StringBuilder(64);
    result.append("Dalvik/");
    result.append(System.getProperty("java.vm.version")); // such as 1.1.0
    result.append(" (Linux; U; Android ");

    String version = Build.VERSION.RELEASE; // "1.0" or "3.4b5"
    result.append(version.length() > 0 ? version : "1.0");

    // add the model for the release build
    if ("REL".equals(Build.VERSION.CODENAME)) {
        String model = Build.MODEL;
        if (model.length() > 0) {
            result.append("; ");
            result.append(model);
        }
    }
    String id = Build.ID; // "MASTER" or "M4-rc20"
    if (id.length() > 0) {
        result.append(" Build/");
        result.append(id);
    }
    result.append(")");
    return result.toString();
}   

Upvotes: 1

shihpeng
shihpeng

Reputation: 5381

The information of user agent is obtained from the HTTP headers, which depends on what browser is used to initiate the WebView object. Therefore, it doesn't make sense if you only want to get the user agent string without creating a WebView.

A better way might be create a WebView and set its visibility to GONE. After getting the user agent string, destroy it.

Upvotes: 1

Lou Franco
Lou Franco

Reputation: 89152

You can see how it's determined by looking at the source

http://www.google.com/codesearch/p?hl=en#uX1GffpyOZk/core/java/android/webkit/WebSettings.java&q=getCurrentUserAgent&sa=N&cd=1&ct=rc&l=370

According to the documentation, you can't get a WebSettings object without a WebView.

Do you need it to be exactly the one that the phone would send? If not, just pick up a standard Android User Agent (not build/version specific)

Upvotes: 1

tacone
tacone

Reputation: 11441

You either initialize a Webview and then destroy it, or just hardcode the user agent as a string (and replace at run-time language etc).

Upvotes: 2

Related Questions