安卓的浏览器和iOS一样,是基于webkit的,应用里有内嵌WebView来实现特定的功能或者减少开发量。
WebView的主要注意点如下:
WebView web = (WebView)findViewById(R.id.web);
web.setBackgroundColor(Color.TRANSPARENT); //背景透明
WebSettings settings = web.getSettings()
settings.setJavaScriptEnabled(true);
settings.setDomStorageEnabled(true);
settings.setDefaultTextEncodingName("UTF-8");
settings.setAllowFileAccess(true); //能存取本地的资源,指assets和本地文件
settings.setLoadsImagesAutomatically(true);
settings.setCacheMode(WebSettings.LOAD_NO_CACHE); //关闭cache
settings.setSupportZoom(true);
settings.setUserAgentString(settings.getUserAgentString() + " XXX/xxx);
内嵌的WebView在加载页面时有很多的回调,可以做些特定的处理。
web.setWebViewClient(new WebViewClient() {
//这里是加载url前的回调
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return super.shouldOverrideUrlLoading(view, url);
}
//开始时,可以显示自己的进度条
public void onPageStarted(WebView view, String url, Bitmap favicon) {
}
//开始时,可以关闭自己的进度条
public void onPageFinished(WebView view, String url) {
}
//出错时的回调
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl){
}
}
如果链接是可以下载的资源,可以简单按下面处理:
web.setDownloadListener(new DownloadListener() {
@Override
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype, long contentLength) {
Intent intent = new Intent();
intent.setData(Uri.parse(url));
intent.setAction(Intent.ACTION_VIEW);
startActivity(intent);
}
});
想在JAVA代码里,调用js的某个函数,比较简单,如下:
web.loadUrl("javascript: r = your_function('hello, android!');");
反过来,JS里想要调用JAVA代码就稍微麻烦点,需要注册一个接口对象给JS,如下:
class JavaScriptInterface {
public void demo(String word) {
...
}
};
web.addJavascriptInterface(new JavaScriptInterface(), "rockwithandroid");
//JS里调用时如下
window.rockwithandroid.demo("hello");
如果想得到页面里的信息,或者执行页面里的JS函数得到返回值到JAVA里的话,就是两者结合起来:
web.loadUrl("javascript: r = your_function('hello, android!');window.rockwithandroid.demo(r)");
对于前端工程师,其实还可以使用HTML5技术构建WebApp,也是一个选择。基本一套代码适用iOS和安卓平台,也有类似PhoneGap这样的开源工具,有兴趣的同学可以试试。豆瓣音乐人就是拿PhoneGap开发的 : )