メインコンテンツまでスキップ

登录 Aptoide 服务(Android SDK)

登录 Aptoide 服务会将用户的购买记录与其 Aptoide 账户关联。登录之后, 即使宿主应用的存储被清除或用户更换了设备,其待处理购买和非消耗型购买仍可通过 queryPurchasesAsync 取回——您无需自建后端。

📘
功能可用性

账户登录由远程开关控制,默认处于关闭状态。在向用户开放该功能之前,请先使用 billingClient.isFeatureSupported(FeatureType.ACCOUNT_SIGN_IN) 确认其可用性(响应码为 OK 表示已启用;SERVICE_UNAVAILABLE 表示配置仍在加载中,请稍后重试)。

登录​

使用 signInToAptoideServices 启动 Aptoide 账户登录流程。该方法为异步方法:结果会以 BillingResult 的形式 传递给 AptoideSignInResponseListener。 请在 SDK 连接建立之后调用(例如从「登录」按钮触发)。

fun signIn(activity: Activity) {
billingClient.signInToAptoideServices(activity) { billingResult ->
runOnUiThread {
when (billingResult.responseCode) {
BillingResponseCode.OK -> restoreOwnedPurchases() // signed in (or already signed in)
BillingResponseCode.USER_CANCELED -> Log.i(TAG, "Sign-in dismissed by the user")
BillingResponseCode.FEATURE_NOT_SUPPORTED -> Log.i(TAG, "Sign-in is disabled")
BillingResponseCode.SERVICE_UNAVAILABLE -> Log.i(TAG, "Not ready yet - retry shortly")
else -> Log.e(TAG, "Sign-in error: ${billingResult.debugMessage}")
}
}
}
}

返回给监听器的响应码如下:

响应码含义
OK用户已完成登录,或原本已处于登录状态。可继续查询已拥有的购买。
USER_CANCELED用户关闭了登录界面,或选择了「不再显示」。
FEATURE_NOT_SUPPORTED账户登录已被停用(功能开关关闭)。
SERVICE_UNAVAILABLE配置仍在加载中(或加载失败),可重试。
ERROR发生了未预期的错误。

返回 OK 时,请查询已拥有的购买以恢复用户权益(结果中包含已确认的非消耗型商品—— 参见确认非消耗型购买):

private fun restoreOwnedPurchases() {
billingClient.queryPurchasesAsync(
QueryPurchasesParams.newBuilder()
.setProductType(ProductType.INAPP)
.build()
) { billingResult, purchases ->
if (billingResult.responseCode == BillingResponseCode.OK) {
purchases.forEach { grantEntitlement(it) }
}
}
}
📘
说明

SDK 会谨慎地展示登录界面(有频率限制,并向用户提供「不再显示」的选项), 因此调用 signInToAptoideServices 是安全的——在不适合展示时,它只会直接返回而不显示界面。

查询当前登录状态​

使用 isSignedInToAptoideServices 可同步读取 当前状态——例如,在打开某个界面时判断应显示「登录」还是「登出」按钮。

val signedIn = billingClient.isSignedInToAptoideServices()

监听登录状态变化​

登录和登出也可能在支付 WebView 内发生。请在构建器上注册 AptoideAccountStateListener,以便在状态发生任何变化时收到通知, 从而无需用户重启应用即可刷新界面并重新查询购买记录。 状态取值为 AccountState 之一:SIGNED_IN 或 SIGNED_OUT。 仅在状态实际发生变化时才会触发。

billingClient = AptoideBillingClient.newBuilder(context)
.setListener(purchasesUpdatedListener)
.setAccountStateListener { state ->
runOnUiThread {
when (state) {
AccountState.SIGNED_IN -> restoreOwnedPurchases()
AccountState.SIGNED_OUT -> revokeAccountEntitlements()
}
}
}
.setPublicKey(publicKey)
.build()

登出​

使用 signOutFromAptoideServices 让用户登出。 该方法会清除已保存的会话,并使后续所有操作恢复为匿名访客流程。 已注册的 AptoideAccountStateListener 会收到 AccountState.SIGNED_OUT 通知。

billingClient.signOutFromAptoideServices()