BillingClient 在iOS和Android应用程序中管理应用程序内购买。onQueryPurchasesResponse 方法用于从Google Play商店服务器获取用户已购买项目的列表,并返回与该用户帐户关联的购买信息。 当查询结果不为空时,BillingClient 会将结果离线存储一段时间以供使用。
默认情况下,BillingClient 在应用程序处于活动状态时会向 Google Play 服务器查询应用程序购买信息。如果用户没有联网,则 onQueryPurchasesResponse 方法将返回缓存的数据。离线存储的时间取决于 BillingClient 的 cacheTime 方法设置。
以下代码演示了如何使用 cacheTime 方法设置离线存储时间:
long cacheTime = 300000; // 设置为5分钟
BillingClient.newBuilder(context)
.enablePendingPurchases()
.setListener(this)
.setChildDirected(BillingClient.isChildDirected(context))
.setUnderAgeOfConsent(BillingClient.getUnderAgeOfConsent(context))
.setTestMode(isTestMode)
.setIdleTimeout(cacheTime, TimeUnit.MILLISECONDS) // 设置离线存储时间
.build();
在以上代码中,IdleTimeout 方法将 cacheTime 时间设置为 5 分钟(300000 毫秒),因此在此时间内,BillingClient 将在离线存储中缓存用户的购买结果。
需要注意的是,这是 BillingClient 的默认行为,可以根据应用程序的需要进行更改。如果您希望完全避免使用缓存,则可以使用 queryPurchaseHistoryAsync 方法在查询应用程序历史记录时禁用缓存:
billingClient.queryPurchaseHistoryAsync(BillingClient.SkuType.INAPP, (billingResult, purchaseHistoryRecordList) -> {
if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK && purchaseHistoryRecordList != null) {
//处理返回结果
}
}, purchasesResponseListener);