这里为了便于理解还是全部贴出了demo的源码,demo中当网页加载完成之后注入上面的js代码获取touch icon信息,然后返回给java的回调方法中。如果不清楚Java代码如何实现改进方案的,可以点击Java代码编写的Android应用如何实现安全
package com.example.obtaintouchicon;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends Activity {
protected String LOGTAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WebView webView = new WebView(this);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
final String touchIconJsCode = getTouchIconJsCode();
Log.i(LOGTAG , "onPageFinished url = " + url + ";touchIconJsCode=" + touchIconJsCode);
view.loadUrl("javascript:" + touchIconJsCode);
}
});
webView.addJavascriptInterface(new JsObject(), "app_native");
webView.loadUrl("http://192.168.1.5:8000/html/touchicon.html");
}
private class JsObject {
@JavascriptInterface
public void onReceivedTouchIcons(String url, String json) {
Log.i(LOGTAG, "onReceivedTouchIcons url=" + url + ";json=" + json);
}
}
private String getTouchIconJsCode() {
StringBuilder total = new StringBuilder();
InputStream inputStream = null;
BufferedReader bufferReader = null;
try {
inputStream = getAssets().open("touchicon.js");
bufferReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = bufferReader.readLine()) != null) {
total.append(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != inputStream) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return total.toString();
}
}
返回的JSON数据
[
{
"sizes":"72x72",
"rel":"apple-touch-icon-precomposed",
"href":"https://www.linuxidc.com/20130423143600/fix/H5-72x72.png"
},
{
"sizes":"114x114",
"rel":"apple-touch-icon-precomposed",
"href":"https://www.linuxidc.com/20130423143600/fix/H5-114x114.png"
},
{
"sizes":"57x57",
"rel":"apple-touch-icon-precomposed",
"href":"https://www.linuxidc.com/20130423143600/fix/H5-57x57.png"
},
{
"sizes":"",
"rel":"apple-touch-icon-precomposed",
"href":"https://www.linuxidc.com/20130423143600/fix/H5-0x0.png"
}
]
我们可以对得到的JSON数据按照需要处理。
Google会改进么
答案是会,而且已经改进,但Google修改的不是onReceivedTouchIconUrl这个方法,而是Google正在推行自己的一套规则。
在Chrome上,Google增加了这样一个元素,这是Google提供的为网页程序定义元数据的方法。
<span><link href="https://www.linuxidc.com/manifest.json"></span>