Lai*_*jus 36 user-agent android webview android-webview
有没有办法在没有WebView
in活动的情况下检索浏览器的用户代理?
我知道有可能通过WebView
以下方式获得:
WebView view = (WebView) findViewById(R.id.someview);
String ua = view.getSettings().getUserAgentString() ;
Run Code Online (Sandbox Code Playgroud)
但在我的情况下,我没有/需要一个webview对象,我不想只是为了检索用户代理字符串而创建它.
DeR*_*gan 54
如果你不有一个你可以尝试把它像这样
String ua=new WebView(this).getSettings().getUserAgentString();
Run Code Online (Sandbox Code Playgroud)
编辑-
getUserAgentString()
说的文件
返回WebView的用户代理字符串.
所以除非你申报一个,否则我认为你不能得到它.如果我错了,有人会纠正我
Cra*_*ell 53
如果您使用的是Android 2.1或更高版本,则有一种更简单的方法.当然,这不是webview将返回的完全相同的用户代理字符串,但可能足以满足您的需要.
作为从Web视图中提取的另一个优点,您可以从任何线程(而不仅仅是UI线程)中使用它.
有一个名为http.agent的系统属性,可用于检索User-Agent字符串.
String userAgent = System.getProperty("http.agent");
Run Code Online (Sandbox Code Playgroud)
有关详细信息,请参阅以编程方式获取User-Agent字符串.
Ido*_*lon 35
我曾经使用过DeRagan提出的解决方案.但事实证明,创建单个WebView
实例会启动一个"WebViewCoreThread"线程,该线程将保留在后台,直到系统终止应用程序.也许它不会消耗太多资源,但我还是不喜欢它.所以我现在使用稍微不同的方法,试图避免创建WebViewCoreThread:
// You may uncomment next line if using Android Annotations library, otherwise just be sure to run it in on the UI thread
// @UiThread
public static String getDefaultUserAgentString(Context context) {
if (Build.VERSION.SDK_INT >= 17) {
return NewApiWrapper.getDefaultUserAgent(context);
}
try {
Constructor<WebSettings> constructor = WebSettings.class.getDeclaredConstructor(Context.class, WebView.class);
constructor.setAccessible(true);
try {
WebSettings settings = constructor.newInstance(context, null);
return settings.getUserAgentString();
} finally {
constructor.setAccessible(false);
}
} catch (Exception e) {
return new WebView(context).getSettings().getUserAgentString();
}
}
@TargetApi(17)
static class NewApiWrapper {
static String getDefaultUserAgent(Context context) {
return WebSettings.getDefaultUserAgent(context);
}
}
Run Code Online (Sandbox Code Playgroud)
它WebSettings
使用包可见的构造函数直接创建实例,如果由于某些原因(例如由于未来Android版本中的API更改)而无法使用 - 则默默地回退到"类似WebView"的解决方案.
UPDATE
正如@ Skywalker5446所指出的,从Android 4.2/API 17开始,有一个公共静态方法来获取默认的用户代理值.我已经更新了我的代码,以便在支持的平台上使用该方法.
Jac*_*1re 10
从Android 2.1开始,你应该使用System.getProperty("http.agent");
您也不需要首先创建WebView,这就是优势,您可以在非uithread中使用它.
问候史蒂夫
归档时间: |
|
查看次数: |
33476 次 |
最近记录: |