Carlos Eduardo Ki Lee
Carlos Eduardo Ki Lee

Reputation: 245

IllegalStateException using Google Play Billing Library

I'm having IllegalStateException using Google Play Billing Library: com.android.billingclient:billing:1.1.

This exception happens just sometimes in some particular case. Something like: for each 500 installations we got 4 errors. We couldn't reproduce this issue locally.

      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
            }
        })
        ...
     }

And this is the stacktrace:

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)

Any clues, what Is causing this exception?

Upvotes: 0

Views: 1014

Answers (1)

John O'Reilly
John O'Reilly

Reputation: 10330

One possibility is that your activity is no longer active by time onBillingSetupFinished is invoked....make sure you're calling endConnection in your activity onDestroy()

override fun onDestroy() {
    billingClient.endConnection()
}

Upvotes: 3

Related Questions