我已经使用Chrome自定义标签构建了一个Android应用,但是当我点击按钮显示网址时,会出现一个对话框,说我需要选择“打开方式”并列出我可以选择的所有浏览器应用。我的问题是如何确定应用程序仅将Chrome设置为默认值,而不必再打开“打开方式”对话框。
fab.setOnClickListener {
val url = "http://myurl.com/"
val builder = CustomTabsIntent.Builder()
builder.setToolbarColor(ContextCompat.getColor(this@MainActivity,R.color.colorAccent))
builder.addDefaultShareMenuItem()
val anotherCustomTab = CustomTabsIntent.Builder().build()
val intent = anotherCustomTab.intent
intent.data = Uri.parse("http://myurl.com/")
builder.setShowTitle(true)
val customTabsIntent = builder.build()
customTabsIntent.launchUrl(this@MainActivity, Uri.parse(url))
}
以下代码来自here但请记住我们应该尊重用户偏好。根据用户偏好我的意思是,
其他用例也很少,但希望你能掌握这个问题
支持CCT的浏览器(Atleast with latest version)
没有CCT支持的浏览器:
public static String getPackageNameToUse(Context context) {
String packageNameToUse = null;
final PackageManager packageManager = context.getPackageManager();
final Intent activityIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
// Get all apps that can handle VIEW intents and have custom tab service
final List<ResolveInfo> resolvedActivityList = packageManager.queryIntentActivities(activityIntent, 0);
final List<String> packagesSupportingCustomTabs = new ArrayList<>();
for (final ResolveInfo info : resolvedActivityList)
{
final Intent serviceIntent = new Intent();
serviceIntent.setAction(ACTION_CUSTOM_TABS_CONNECTION);
serviceIntent.setPackage(info.activityInfo.packageName);
if (packageManager.resolveService(serviceIntent, 0) != null)
packagesSupportingCustomTabs.add(info.activityInfo.packageName);
}
// Now packagesSupportingCustomTabs contains all apps that can handle both VIEW intents
// and service calls.
if (packagesSupportingCustomTabs.size() == 1)
packageNameToUse = packagesSupportingCustomTabs.get(0);
else if (packagesSupportingCustomTabs.contains(STABLE_PACKAGE))
packageNameToUse = STABLE_PACKAGE;
return packageNameToUse;
}
我找到了如何验证它,参考this所以我得到了这个编码和工作,没有要求设置浏览器了。
fab.setOnClickListener {
val PACKAGE_NAME = "com.android.chrome"
val builder = CustomTabsIntent.Builder()
builder.setToolbarColor(ContextCompat.getColor(this@MainActivity,R.color.colorAccent))
builder.addDefaultShareMenuItem()
builder.setShowTitle(true)
val anotherCustomTab = builder.build()
val intent = anotherCustomTab.intent
intent.data = Uri.parse("http://www.myurl.com/")
val packageManager = packageManager
val resolveInfoList = packageManager.queryIntentActivities(anotherCustomTab.intent, PackageManager.MATCH_DEFAULT_ONLY)
for (resolveInfo in resolveInfoList) {
val packageName = resolveInfo.activityInfo.packageName
if (TextUtils.equals(packageName, PACKAGE_NAME))
anotherCustomTab.intent.setPackage(PACKAGE_NAME)
}
anotherCustomTab.launchUrl(this, anotherCustomTab.intent.data)
}