在webview中,我们需要获取网站的favicon.ico图标,但是默认状态下,WebChromeClient中的onReceivedIcon方法获取到的icon总是为null;

webview.getFavicon();获得到的还是null,这个就奇怪了,于是

经过一番google,发现老外也遇到了这个问题.

=======================================================

http://stackoverflow.com/questions/3462582/display-the-android-webviews-favicon

I'd like to display the favicon of the website I am accessing via the android.webkit.WebView. I've tried two ways to get it:

1) WebViewClient.onPageStarted() method has a favicon parameter that is always null.

2) WebChromeClient.onReceivedIcon() method is never called.

3) Called WebView.getFavicon() in onPageStarted() andonPageFinished() but it always returns null.

I haven't been able to find an example online that shows how to access the favicon. Any hints would be greatly appreciated.

其中有个回答解决了这个问题.

For the WebView icon methods and listeners to work, you need to first open the WebIconDatabase manually. You would typically do this in theonCreate() method of your Activity.

Try adding the following line to onCreate():

WebIconDatabase.getInstance().open(getDir("icons", MODE_PRIVATE).getPath()); 

Once you've done this, you should start getting onReceivedIcon() callbacks for any WebView in this Activity, and thegetFavicon() method should also start returning a valid object rather than null whenever icons are available.

========================================================================

即在使用webview中的getFavicon()方法之前,需要在onCreate()方法中先调用

(WebIconDatabase 即图标数据库管理对象,所有的WebView均请求相同的图标数据库对象。)

WebIconDatabase.getInstance().open("存放icon的目录");

这个存放icon的目录自定义.一般会放到对应项目的data/data/包名/cache/目录.

本人开发的快捷的浏览器,为自己练手的应用 飞速浏览器http://www.ifeisu.com

此项目的位置就是

/data/data/com.ifeisu.browser/cache/icons/


onCreate()中的代码:

WebIconDatabase.getInstance().open(Util.getDirs(getCacheDir().getAbsolutePath()+"/icons/"));

创建目录的代码:

public static String getDirs(String path)
{
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
return path;
}

前提是你的这个icons目录是必须提前创建好的,不然会报错.

老外回答里面的

getDir("icons", MODE_PRIVATE).getPath()

是Context的方法,我这里没有用,直接用的自定义方法.

最后来看看成果吧


更多相关文章

  1. Android(安卓)编译时注解 —— 语法详解
  2. flutter中实现仿Android端的onResume和onPause方法
  3. Android(安卓)Native性能测试方法
  4. apk安装:adb push && adb install
  5. Android(安卓)- webview原生和JavaScript(js)交互传值的几种方式
  6. Download https://downloads.gradle.org/distributions/gradle-4
  7. 转:Android(安卓)sdcard.img
  8. touch事件处理
  9. Activity的生命周期方法

随机推荐

  1. Android Context
  2. android 图片溢出问题2...[geoway]
  3. Android List divider显示不出来的问题
  4. Android中状态栏的隐藏
  5. Android 中OpenGL的使用
  6. Android开发--Intent-filter属性详解
  7. MAC环境Android(安卓)SDK环境变量配置201
  8. Android Animation 动画介绍与详解
  9. Android源代码下载
  10. 2018-10-11【Android代码重构使用技巧】