开发者

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

开发者 https://www.devze.com 2023-02-24 21:36 出处:网络
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

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 instantia开发者_如何学Cte 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


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).


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)


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.


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();
}   
0

精彩评论

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