当用户不想购买应用内商品并取消Google商店弹出式对话框时,应用会崩溃。为什么?

时间:2017-07-06 16:37:07

标签: android in-app-purchase

我的应用内购买效果非常好,但是,当我的用户不想购买它,取消或退出“Google Store弹出式对话框”时,我的应用程序崩溃(退出)。我有以下代码:

@Override
protected void onActivityResult(int requestCode, int resultCode,
                                Intent data) {
    if (!mHelper.handleActivityResult(requestCode,
            resultCode, data)) {
        super.onActivityResult(requestCode, resultCode, data);
    }
}

IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
    public void onIabPurchaseFinished(IabResult result, Purchase purchase) {

        if (purchase.getSku().equals(ITEM_SKU)) {
            Log.d(TAG, "Purchase is fast mode");
            try {
                mHelper.consumeAsync(purchase, mConsumeFinishedListener);
            } catch (Exception e) {
                Log.d(TAG, "error");
            }
        }

    }
};


IabHelper.OnConsumeFinishedListener mConsumeFinishedListener = new IabHelper.OnConsumeFinishedListener() {
    public void onConsumeFinished(Purchase purchase, IabResult result) {

        Log.d(TAG, "Consumption finished. JSON: " + purchase.getOriginalJson() + ", signature: " + purchase.getSignature());

        if (mHelper == null) return;

        if (result.isSuccess()) {
            Log.i(TAG, "BOUGHT THE ITEM :-)");
            clickButton.setEnabled(true);
            buyButton.setEnabled(false);
        } else {
            Log.e(TAG, "Error while consuming: " + result);
        }
        Log.d(TAG, "End consumption flow.");
    }
};

1 个答案:

答案 0 :(得分:1)

问题在于OnIabPurchaseFinishedListener接口,因为这是在购买对话框打开时调用的内容,并且您必须确保在取消该过程时立即退出该方法,因为那里没有SKU检查最有可能导致NullPointerException的购买。也就是说,我在界面中添加验证方法(就像你在消费完成的监听器中所做的那样),如下所示:

IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
    public void onIabPurchaseFinished(IabResult result, Purchase purchase) {

        // If we were disposed of in the meantime, exits out of the method.
        if (mHelper == null) return;

        // If purchase was cancelled, exits out of the method.
        if (result.isFailure()) {
            Log.d(TAG, "Error purchasing: " + result);
            return;
        }

        // If user authentication is invalid, exits out of the method.
        if (!verifyDeveloperPayload(purchase)) {
            Log.d(TAG, "Error purchasing. Authenticity verification failed.");
            return;
        }

        // Only then if all of the validation conditions are met will the following be executed.
        if (purchase.getSku().equals(ITEM_SKU)) {
            Log.d(TAG, "Purchase is fast mode");
            try {
                mHelper.consumeAsync(purchase, mConsumeFinishedListener);
            } catch (Exception e) {
                Log.d(TAG, "error");
            }
        }

    }
};