Search code examples
androidin-app-billing

Verifying in-app purchases after re-install or user prefs deletion


I've implemented in-app billing from this tutorial. The item to buy is the ability to set a custom background. It works great, but when I uninstall and re-install the app (or clear the user prefs), I'm having trouble figuring out how to verify that somebody has already purchased the in-app item.

    public void buySelected() {

    if (backgroundColorsPurchased == true) {
        this.colorChangeDialog(); //if user has already purchased, just call the dialog instead of re-buying.
        //if the person has cleared their prefs, they'll have to be online to re-verify that they did indeed buy the item.

    }else{
        if(BillingHelper.isBillingSupported()){
            BillingHelper.requestPurchase(mContext, "background.colors");
            BillingHelper.setCompletedHandler(mTransactionHandler);

        } else {
            Log.i(TAG,"Can't purchase on this device");

        }
    }
}

Then I have the handler:

    public Handler mTransactionHandler = new Handler(){
    public void handleMessage(android.os.Message msg) {
        Log.i(TAG, "Transaction complete");
        Log.i(TAG, "Transaction status: "+BillingHelper.latestPurchase.purchaseState);
        Log.i(TAG, "Item purchased is: "+BillingHelper.latestPurchase.productId);

        if(BillingHelper.latestPurchase.isPurchased()){
        //this is where we show the stuff that the person purchased. In this case, the dialog to change the background colour.
            backgroundColorsPurchased = true; //just setting this to true so that the next time somebody clicks the donate button it'll just open the dialog.

            //call the change background dialog
            colorChangeDialog();

        }else{
            //fail
            Toast.makeText(getApplicationContext(), "Fail", Toast.LENGTH_SHORT).show();

        }
    }

 };

How am I able to verify that the item has been purchased before? The market just keeps popping a dialog window that says, "You have already purchased this item, or the purchase is still pending." When I try using something like if(BillingHelper.latestPurchase.isPurchased()){ I get a force close if it's not within the handler.


Solution

  • You need to call restoreTransactions take a look at the default example that Android has provided for In App Billing for more reference.