I'm initializing a member variable to null.
Later in the process, this member variable is assigned a value, before starting the payment flow, ie before invoking billingClient.launchBillingFlow(context, billingFlowParams)
When arriving in the PurchasesUpdatedListener
callback, the member variable is null again.
我首先认为这是一个作用域问题,所以我设置了一个inner class MyPurchasesUpdatedListener : PurchasesUpdatedListener
,以确保在包含类中可以访问包含类成员变量,但这没有什么不同.
所以我认为这是完全不同的东西,比如生命周期,不同的线程/活动隐含在我自己的流中间的计费流中…
我试图将我的代码剥离到最小的有用部分:
class GooglePlayPay(val context:NativeAppActivity) {
...
var purchaseCallback: ((Boolean)->Unit)?=null
...
private val purchasesUpdatedListener = MyPurchasesUpdatedListener()
inner class MyPurchasesUpdatedListener : PurchasesUpdatedListener {
override fun onPurchasesUpdated(billingResult:BillingResult, purchases:List<Purchase>?){
Log.d("fp_purchUpdatedListener","PurchaseCallback: ${purchaseCallback.toString()}")
// ===> in catlog: PurchaseCallback: null
if (billingResult.responseCode == BillingClient.BillingResponseCode.OK && purchases != null) {
for (purchase in purchases) {
handlePurchase(purchase)
}
} else if (billingResult.responseCode == BillingClient.BillingResponseCode.USER_CANCELED) {
// Handle an error caused by a user cancelling the purchase flow.
} else {
// Handle any other error codes.
}
}
}
fun handlePurchase(purchase: Purchase){
...
Log.d("fp_handlePurchase","PurchaseCallback: ${purchaseCallback.toString()}")
// ===> in catlog: PurchaseCallback: null
...
}
fun purchaseProduct(productDetails: ProductDetails, cb:(Boolean)->Unit) {
purchaseCallback = cb
Log.d("fp_purchaseProduct","2.PurchaseCallback: ${purchaseCallback.toString()}")
// ===> in catlog: PurchaseCallback: Function1<java.lang.Boolean, kotlin.Unit>
// Launch the billing flow
billingClient.launchBillingFlow(context, billingFlowParams)
}
我不知道它是否重要:这purchaseProduct()
是从@JavascriptInterface
函数中调用的.
[编辑]此处添加了调用类的摘录:
class GooglePlayPayJSInterface(val context: WebAppActivity) {
@JavascriptInterface fun getProduct(str:String) {
GooglePlayPay(context).getProduct(str, ::getProductCallback)
}
fun getProductCallback(details: ProductDetails){
context.postToJs("""{"data":{"productId":"${details.getProductId()}", "name": "${details.getName()}", "price":"${details.getOneTimePurchaseOfferDetails()?.getFormattedPrice()?:"n/a"}"}}""")
}
@JavascriptInterface fun purchase(str:String) {
GooglePlayPay(context).purchase(str, ::purchaseCallback} )
}
fun purchaseCallback(success:Boolean){
if(success){ context.postToJs("""{"data":{"result":"success"}}""") }
else { context.postToJs("""{"errcode":"Purchase failed"}""") }
}
...
}
But I don't think there's a problem here: getProduct()
and its getProductCallback()
work like a charm.
The only difference I see between getProduct
+callback and purchase
+callback is that:
-
purchase
被Android的计费流程中断, - 其中
getProduct
只是调用API函数(billingClient.startConnection()
、billingClient.queryProductDetailsAsync()
),然后调用先前存储为成员变量的回调.