使用Google Play结算库的IllegalStateException

时间:2018-10-20 13:32:53

标签: android kotlin play-billing-library

我正在使用Google Play结算库com.android.billingclient:billing:1.1出现IllegalStateException。

此异常有时在某些特殊情况下发生。像这样:每500次安装,我们都会出现4个错误。我们无法在本地重现此问题。

      override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        billingClient = BillingClient.newBuilder(this@MainActivity).setListener(this).build()
        billingClient.startConnection(object : BillingClientStateListener {
            override fun onBillingSetupFinished(@BillingClient.BillingResponse billingResponseCode: Int) {
                if (billingResponseCode == BillingClient.BillingResponse.OK) {
                    var purchasesResult = billingClient.queryPurchases(BillingClient.SkuType.INAPP)
                    var purchaseList = purchasesResult.purchasesList

                    purchaseList.forEach {  // LINE 89 -> MainActivity.kt
                        if(it.sku.equals(ExtraNames.REMOVE_ADS_SKU)){
                            Utils.setIntSharedPreferences(this@MainActivity, ExtraNames.REMOVE_ADS, ExtraNames.YES)
                        }
                    }

                }
            }
            override fun onBillingServiceDisconnected() {
                //Nothing to do now
            }
        })
        ...
     }

这是堆栈跟踪:

java.lang.IllegalStateException: 
  at com.myapp.br.MainActivity$onCreate$1.onBillingSetupFinished (MainActivity.kt:89)
  at com.android.billingclient.api.BillingClientImpl$BillingServiceConnection.onServiceConnected (BillingClientImpl.java:903)
  at android.app.LoadedApk$ServiceDispatcher.doConnected (LoadedApk.java:1818)
  at android.app.LoadedApk$ServiceDispatcher$RunConnection.run (LoadedApk.java:1847)
  at android.os.Handler.handleCallback (Handler.java:808)
  at android.os.Handler.dispatchMessage (Handler.java:101)
  at android.os.Looper.loop (Looper.java:166)
  at android.app.ActivityThread.main (ActivityThread.java:7425)
  at java.lang.reflect.Method.invoke (Native Method)
  at com.android.internal.os.Zygote$MethodAndArgsCaller.run (Zygote.java:245)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:921)

任何线索,是什么导致此异常?

1 个答案:

答案 0 :(得分:1)

一种可能性是您的活动在调用onBillingSetupFinished时不再处于活动状态。...确保在活动endConnection

中呼叫onDestroy()
override fun onDestroy() {
    billingClient.endConnection()
}