Retrieve User-Agent programmatically

前端 未结 6 1750
天涯浪人
天涯浪人 2020-12-13 17:52

Is there a way to retrieve Browser\'s user-agent without having a WebView in activity?

I know it is possible to get it via WebView:

6条回答
  •  天涯浪人
    2020-12-13 18:24

    This is an updated solution based on previous answers that works when you compile for KitKat. Now the WebSettings class is abstract and the WebSettingsClassic class has been removed.

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    public static String getUserAgent(final Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            return WebSettings.getDefaultUserAgent(context);
        }
        else {
            try {
                final Class webSettingsClassicClass = Class.forName("android.webkit.WebSettingsClassic");
                final Constructor constructor = webSettingsClassicClass.getDeclaredConstructor(Context.class, Class.forName("android.webkit.WebViewClassic"));
                constructor.setAccessible(true);
                final Method method = webSettingsClassicClass.getMethod("getUserAgentString");
                return (String) method.invoke(constructor.newInstance(context, null));
            }
            catch (final Exception e) {
                return new WebView(context).getSettings()
                        .getUserAgentString();
            }
        }
    }
    

提交回复
热议问题