前言
发现
使用Twitter时发现它的webview
全都是用chrome
打开的,而且是单独的一个tab,并且写着由Chrome提供支持
,如图:
从Chrome官网了解到这个叫做Chrome Custom Tabs
,它和Chrome App以及WebView的加载速度对比图如下:
用法
首先需要在你的项目里添加Custom Tabs Support Library
。打开build.gradle
并在dependency
中添加依赖库,dependencies {
...
compile 'com.android.support:customtabs:24.1.0'
}
打开一个Chrome Custom Tab
String url = ¨https://paul.kinlan.me/¨; |
设置Toolbar的颜色
builder.setToolbarColor(colorInt); |
更多用法请参考以下链接
适配
试验后发现如果手机中没有安装Chrome浏览器是无法使用Chrome Custom Tab的,会跳转到自带浏览器,感觉这种体验是不太好的,所以应当检查是否已安装Chrome,如果没有安装Chrome,就要自己使用WebView打开了。//检查是否安装Chrome
String packageName = "com.android.chrome";
Intent browserIntent = new Intent();
browserIntent.setPackage(packageName);
List<ResolveInfo> activitiesList = getPackageManager().queryIntentActivities(
browserIntent, -1);
if(activitiesList.size() > 0) {
// 使用Chrome Custom Tab打开
String url = "https://paul.kinlan.me/";
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
builder.setToolbarColor(Color.RED);
CustomTabsIntent customTabsIntent = builder.build();
customTabsIntent.launchUrl(this, Uri.parse(url));
} else {
//使用自定义的WebViewActivit打开
startActivity(new Intent(MainActivity.this,WebActivity.class));
}