Purchase an Item
1、
To start a purchase request from your app, call
launchPurchaseFlow(Activity, String, int, OnIabPurchaseFinishedListener, String)
on your
IabHelper
instance. You must make this call from the main thread of your
Activity
.
2、If Successful.
If the purchase order is successful, the response data from Google Play is stored in an
Purchase
object that is passed back to the listener.IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() { public void onIabPurchaseFinished(IabResult result, Purchase purchase) { if (result.isFailure()) { Log.d(TAG, "Error purchasing: " + result); return; } else if (purchase.getSku().equals(SKU_GAS)) { // consume the gas and update the UI } else if (purchase.getSku().equals(SKU_PREMIUM)) { // give user access to premium content and update the UI } } };
Query Purchased Items
1、To retrieve the user’s purchases from your app, callqueryInventoryAsync(QueryInventoryFinishedListener)
on your
IabHelper
instance.
IabHelper.QueryInventoryFinishedListener mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() { public void onQueryInventoryFinished(IabResult result, Inventory inventory) { if (result.isFailure()) { // handle error here } else { // does the user have the premium upgrade? mIsPremium = inventory.hasPurchase(SKU_PREMIUM); // update UI accordingly } } };
Consume a Purchase
To record a purchase consumption, call
consumeAsync(Purchase, OnConsumeFinishedListener)
on yourIabHelper
instance. The first argument that the method takes is thePurchase
object representing the item to consume. The second argument is aOnConsumeFinishedListener
that is notified when the consumption operation has completed and handles the consumption response from Google Play. It is safe to make this call fom your main thread.In this example, you want to consume the gas item that the user has previously purchased in your app.
mHelper.consumeAsync(inventory.getPurchase(SKU_GAS), mConsumeFinishedListener);The following example shows how to implement the
OnConsumeFinishedListener
.IabHelper.OnConsumeFinishedListener mConsumeFinishedListener = new IabHelper.OnConsumeFinishedListener() { public void onConsumeFinished(Purchase purchase, IabResult result) { if (result.isSuccess()) { // provision the in-app purchase to the user // (for example, credit 50 gold coins to player's character) } else { // handle error } } };