android中webview接收favicon總是擷取為null解決方案

來源:互聯網
上載者:User

在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的方法,我這裡沒有用,直接用的自訂方法.

最後來看看成果吧


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.