升级Google Play Billing Library至v5后无法获取订阅价格求助
解决Google Play Billing Library v5无法获取订阅价格的问题
从v4升级到v5后,计费流程正常但无法获取订阅价格,结合你的代码,可从以下几个方向排查解决:
1. 增加空值校验,避免直接索引访问
你的代码直接通过get(0)获取列表元素,若返回的ProductDetails列表为空,或者对应的SubscriptionOfferDetails为空,会导致无输出(甚至静默异常)。先添加校验逻辑:
if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) { if (!list.isEmpty()) { ProductDetails productDetails = list.get(0); List<ProductDetails.SubscriptionOfferDetails> offerDetails = productDetails.getSubscriptionOfferDetails(); if (!offerDetails.isEmpty()) { // 获取默认优惠的首阶段价格 String formattedPrice = offerDetails.get(0) .getPricingPhases() .getPricingPhaseList() .get(0) .getFormattedPrice(); // 确保在主线程更新UI runOnUiThread(() -> monthlyPriceTV.setText(formattedPrice)); } else { Log.d("BillingDebug", "无可用的订阅优惠详情"); } } else { Log.d("BillingDebug", "未查询到对应订阅产品"); } }
2. 确认Google Play Console的产品配置
- 检查订阅产品在控制台是否已发布,且对应地区有定价设置
- 确认产品是否配置了有效的订阅优惠(包括基础订阅的默认优惠),若没有配置优惠,
SubscriptionOfferDetails会返回空列表
3. 优先获取默认订阅优惠
v5中订阅可能包含多个优惠(如基础订阅、促销优惠),建议通过getDefaultSubscriptionOfferId()匹配默认优惠,避免拿到非预期的优惠价格:
if (!offerDetails.isEmpty()) { String defaultOfferId = productDetails.getDefaultSubscriptionOfferId(); for (ProductDetails.SubscriptionOfferDetails offer : offerDetails) { if (offer.getOfferId().equals(defaultOfferId)) { String formattedPrice = offer.getPricingPhases() .getPricingPhaseList() .get(0) .getFormattedPrice(); runOnUiThread(() -> monthlyPriceTV.setText(formattedPrice)); break; } } }
4. 确保UI更新在主线程
queryProductDetailsAsync的回调线程不一定是主线程,直接更新TextView可能无反应且无报错。必须通过runOnUiThread(或其他主线程方式)更新UI,这是常见的静默失效原因。
5. 添加日志排查细节
在回调中添加日志,明确各个环节的状态,帮助定位问题:
Log.d("BillingDebug", "响应码: " + billingResult.getResponseCode()); Log.d("BillingDebug", "返回产品数量: " + list.size()); if (!list.isEmpty()) { Log.d("BillingDebug", "订阅优惠数量: " + list.get(0).getSubscriptionOfferDetails().size()); }
内容的提问来源于stack exchange,提问作者BhavitBJ
相关产品推荐
相关产品推荐

