Simplest way to ‘Remove Ads’ via IAP

There are plenty of tutorials on the Internet bout how to Remove Ads in your App via IAP on Android,
but all are way harder & difficult for a beginner to understand…
Someone with a lil bit of Experience in Android will also find it a bit difficult…

In the beginning, even I faced problems with Android’s Own IAP library…

So here’s a Simplest tutorial for it…
This Tutorial doesn’t include parts like getting App’s API key & SKU (in app product name) from Play Developer Console…

We’ll use the Billing Library by ANJLab,
add the dependency as follows to grab the library –

compile 'com.anjlab.android.iab.v3:library:+'

We are done with adding the Library.

Next step,
create a private BillingProcessor variable in your Activity like below –

private BillingProcessor mBillingProcessor;

then,
Initialize the BillingProcessor variable in the onCreate() method of your Activity!

mBillingProcessor = new BillingProcessor(MainActivity.this, "Your App's API String Key here", new BillingProcessor.IBillingHandler(){
@Override
public void onProductPurchased(String productName, TransactionDetails transacDetails) {
//Remove Ads on Purchase, i.e.Removing AdView from Parent Layout, in this case RelativeLayout!
if(productName.equals("Product / SKU Name that you Created on Developer Console")) {
relativeLayout.removeView(mAdView);
}
}
}

@Override
public void onPurchaseHistoryRestored() {
// TODO: Implement this method
}

@Override
public void onBillingError(int errorCode, Throwable throwable) {
// TODO: Implement this method
}

@Override
public void onBillingInitialized() {
// TODO: Implement this method
}
});
mBillingProcessor.initialize();

What we did above was to Remove Ads ASAP when the Payment is successful…

Now, just below the line –
mBillingProcessor.initialize();
paste the following code –

 if(mBillingProcessor.isPurchased("Your SKU Name")){
relativelayout.removeView(mAdView);
}

The above Code checks on your App Start that whether Ad is Removed or not,
If it is Removed i.e. Purchased then Remove The AdView!
As an Addition you should override the onActivityResult() in your Activity as follows –

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

Simple, isn’t it!?

Okay, we have learnt how to handle AdView with purchase flow…
But how do we start or call the Purchase??
Simply use –

mBillingProcessor.purchase(MainActivity.this, "Your SKU Name");

& that’s it! ✌️

Posted in Android

Write a comment