在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的方法,我這裡沒有用,直接用的自訂方法.
最後來看看成果吧