You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android BillingClient价格无法正常显示,仅重启页面/点击购买才加载

问题

使用Google BillingClient实现内购价格展示功能时遇到异常:首次进入Activity时价格无法显示,需多次重启Activity或点击购买按钮(触发launchBillingFlow)后,价格才会加载显示。

相关实现代码如下:

初始化BillingClient代码

billingClient = BillingClient.newBuilder(this)
            .setListener(purchasesUpdatedListener)
            .enablePendingPurchases()
            .build()

billingClient.startConnection(object : BillingClientStateListener {
    override fun onBillingSetupFinished(billingResult: BillingResult) {
        if (billingResult.responseCode ==  BillingClient.BillingResponseCode.OK) {
            getPrice(PRODUCT_ID_1)
            getPrice(PRODUCT_ID_2)
            getPrice(PRODUCT_ID_3)
            getPrice(PRODUCT_ID_4)
        }
    }
})

getPrice方法实现

private fun getPrice(productId: String) {
    // Define the product details to query
    val productList =
        listOf(
            QueryProductDetailsParams.Product.newBuilder()
                .setProductId(productId)
                .setProductType(BillingClient.ProductType.INAPP)
                .build(),
        )

    // Create query parameters
    val params = QueryProductDetailsParams.newBuilder().setProductList(productList).build()

    // Query product details
    billingClient.queryProductDetailsAsync(params) { billingResult, productDetailsList ->
        if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) {
            if (productDetailsList.size > 0) {
                // Extract the product details
                val productDetails = productDetailsList[0]

                // Get the price of the product
                val price = productDetails.oneTimePurchaseOfferDetails?.formattedPrice

                // Update the corresponding TextView with the price
                when (productId) {
                    PRODUCT_ID_1 -> findViewById<TextView>(R.id.price1).text = price
                    PRODUCT_ID_2 -> findViewById<TextView>(R.id.price2).text = price
                    PRODUCT_ID_3 -> findViewById<TextView>(R.id.price3).text = price
                    PRODUCT_ID_4 -> findViewById<TextView>(R.id.price4).text = price
                }
            }
        }
    }
}
异常原因分析
  • 非主线程更新UI:queryProductDetailsAsync的回调运行在后台线程,直接在回调里修改TextView的文本属于违规操作,系统不会立即执行UI更新,只有后续主线程触发UI刷新时才可能显示价格,这是首次进入不显示的核心原因。
  • 无查询失败重试机制:首次查询可能因网络波动、Google Play服务响应延迟等原因失败,但当前代码没有重试逻辑,只有重启Activity或触发购买时才会重新发起查询,导致价格偶然显示。
  • 并发查询触发限流:连续发起4个独立的queryProductDetailsAsync请求,BillingClient可能对并发请求有限流策略,部分请求被丢弃或延迟响应,导致首次进入时无法获取完整价格数据。

内容的提问来源于stack exchange,提问作者RGS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 11:52:34