2

这是我的帐单经理

public class BillingManager implements PurchasesUpdatedListener {
    private BillingClient mBillingClient;
    private Activity mActivity;

    public BillingManager(Activity activity) {
        mActivity = activity;
        mBillingClient = BillingClient.newBuilder(mActivity).setListener(this).build();
        startServiceConnectionIfNeeded(null);
    }

    private void startServiceConnectionIfNeeded(final Runnable executeOnSuccess) {
        if (mBillingClient.isReady()) {
            if (executeOnSuccess != null) {
                executeOnSuccess.run();
            }
        } else {
            mBillingClient.startConnection(new BillingClientStateListener() {
                @Override
                public void onBillingSetupFinished(@BillingClient.BillingResponse int billingResponse) {
                    if (billingResponse == BillingClient.BillingResponse.OK) {
                        Log.i(TAG, "onBillingSetupFinished() response: " + billingResponse);
                        if (executeOnSuccess != null) {
                            executeOnSuccess.run();
                        }
                    } else {
                        Log.w(TAG, "onBillingSetupFinished() error code: " + billingResponse);
                    }
                }

                @Override
                public void onBillingServiceDisconnected() {
                    Log.w(TAG, "onBillingServiceDisconnected()");
                }
            });
        }
    }

下面的监听器只有在完成谷歌播放库后才会执行

@Override
    public void onPurchasesUpdated(int responseCode, @Nullable List<Purchase> purchases) {
        Log.d(TAG, "onPurchasesUpdated: ResponseCode = "+ responseCode);
        Log.d(TAG, "onPurchasesUpdated: Purchase = "+purchases);
        if (responseCode == BillingClient.BillingResponse.OK && purchases != null) {
                //if user purchased something
        } else if (responseCode == BillingClient.BillingResponse.USER_CANCELED) {
            // Handle an error caused by a user cancelling the purchase flow.
        } else {
            // Handle any other error codes.
        }
    }
4

1 回答 1

3

除了成功的 onBillingSetupFinished 回调之外,就在您的活动的 onCreate 甚至更好的 onResume 内(这将防止在应用程序之间切换时丢失购买的潜在问题)。

对于所有类似的问题,请查看最新的TrivialDrive_v2

例如 queryPurchase在此处此处触发。

于 2017-09-28T18:48:27.083 回答