点击 EditText 时如何显示“Scan New Card”建议?
结论
应用无法强制让软键盘显示 “Scan New Card”。
这个建议通常来自当前启用的 Autofill Service、输入法或设备厂商组件。android:autofillHints="creditCardNumber" 只用于告诉系统该字段填写信用卡号,并不会生成扫描入口。如果用户关闭了 Autofill Service、当前服务不支持银行卡扫描,或者所用键盘没有相关功能,这项建议就不会出现。
正确配置字段
在 Android 8.0(API 26)及以上版本中,可以为卡号输入框声明 Autofill Hint:
<EditText
android:id="@+id/cardNumberEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:autofillHints="creditCardNumber"
android:importantForAutofill="yes"
android:inputType="number"
android:hint="Card number"
android:maxLength="19" />
也可以通过代码设置:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
cardNumberEditText.setAutofillHints(
View.AUTOFILL_HINT_CREDIT_CARD_NUMBER
)
cardNumberEditText.importantForAutofill = View.IMPORTANT_FOR_AUTOFILL_YES
}
如果页面中还有有效期和安全码字段,应分别声明相应的语义:
<EditText
android:id="@+id/expirationDateEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:autofillHints="creditCardExpirationDate"
android:importantForAutofill="yes"
android:inputType="number"
android:hint="MM/YY" />
<EditText
android:id="@+id/securityCodeEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:autofillHints="creditCardSecurityCode"
android:importantForAutofill="yes"
android:inputType="numberPassword"
android:hint="CVV" />
这些配置有助于 Autofill Service 识别字段,但无法保证 “Scan New Card” 一定出现。
Autofill 被禁用时怎么办
应用可以检查设备是否支持 Autofill,以及用户是否启用了 Autofill Service。不过,应用不能代替用户开启该服务,也不应在用户每次点击输入框时都强制跳转到设置页:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val autofillManager = getSystemService(AutofillManager::class.java)
if (autofillManager?.isAutofillSupported == true &&
autofillManager.hasEnabledAutofillServices()
) {
// Autofill 可用,但具体是否显示银行卡扫描仍由服务决定
} else {
// Autofill 不可用,可显示说明或提供应用自己的扫描按钮
}
}
如果确实需要引导用户配置 Autofill,可以在用户主动选择后打开系统设置:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val intent = Intent(Settings.ACTION_REQUEST_SET_AUTOFILL_SERVICE).apply {
data = Uri.parse("package:$packageName")
}
runCatching {
startActivity(intent)
}
}
设置页面及可配置的行为可能因 Android 版本、设备厂商和 Autofill Service 而异,因此还要处理该页面无法打开的情况。
需要稳定扫描入口时
如果扫描支付卡是核心功能,不要依赖键盘建议。更稳妥的做法是在卡号输入框旁提供应用自己的 “扫描卡片” 按钮:
<Button
android:id="@+id/scanCardButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="扫描卡片" />
用户点击按钮后,可以调用所选支付 SDK 的卡片扫描功能,也可以使用相机和 OCR 识别。识别出的卡号和有效期仍需由用户确认。
不要依赖某个特定键盘的 UI、文本或私有 Intent 来实现卡片扫描。这类方案没有稳定的公共 API,用户更换输入法、Autofill Service 或设备后,很可能无法继续使用。
注意事项
autofillHints是字段语义提示,不是控制 “Scan New Card” 是否显示的开关。- 这项建议是否出现,取决于 Autofill Service、输入法、系统版本、地区、设备能力和服务自身策略。
- 不要读取、记录或上传 CVV。卡号等支付数据也不应写入日志、分析事件、崩溃报告或普通本地存储。
- 如果应用自行处理支付卡数据,需要评估支付服务商的要求以及适用的 PCI DSS 合规范围。
- 如果应用只是用于收款,优先使用支付服务商提供的托管输入组件或支付 SDK,以减少应用直接接触敏感卡片数据的范围。
备注:内容仅供参考。
