📜 ⬆️ ⬇️

Android In-app purchasing: paid ad disconnection in your application

Many times already asked to write an article about how the application to implement a paid disable advertising. According to the In-app, there were already articles on the site. True, they considered the old version of the API. In principle, the new version is not particularly different from the old one. There was a similar article, but there it was told more about the display of advertising, and we never saw the second part of the article. As it turned out, this question is still interesting to many people, I decided to write how to implement it in my application.

In-App Purchase is a virtual goods purchase service within the application (for example, game currency, new levels, etc.). It is used mainly in games, in cases where the question arises about the need to earn money on his creation.

This article will look at how you can use in-app purchase to disable ads in your application .

Advertising in the application


In principle, you can take any site. Take for example AdMob. For convenience, I usually stuff such things into wrappers so that when changing the site, if necessary, almost nothing has to be changed. Wrappers for the advertising platform must implement the interface:
public interface AdsControllerBase { public void createView( RelativeLayout layout); public void show(boolean show); public void onStart(); public void onDestroy(); public void onResume(); public void onStop(); } 

')
Then the AdMob wrapper will look something like this:
AdMob Wrap
 public class AdMobController implements AdsControllerBase, AdListener { private static final String ADMOB_ID = "___AdMob"; private static final int REQUEST_TIMEOUT = 30000; private AdView adView; private Context c; private long last; public AdMobController(Context activity, RelativeLayout layout) { this.c = activity; createView(layout); last = System.currentTimeMillis() - REQUEST_TIMEOUT; } public void createView(RelativeLayout layout) { if(PreferencesHelper.isAdsDisabled()) return; adView = new AdView((Activity) c, AdSize.BANNER, ADMOB_ID); RelativeLayout.LayoutParams adParams = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); adParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); adParams.addRule(RelativeLayout.CENTER_HORIZONTAL); adView.setAdListener(this); layout.addView(adView, adParams); adView.loadAd(new AdRequest()); } //    ,    30  public void show(boolean show) { if(adView == null) return; adView.setVisibility((show) ? View.VISIBLE : View.GONE); if (show && (System.currentTimeMillis() - last > REQUEST_TIMEOUT)) { last = System.currentTimeMillis(); adView.loadAd(new AdRequest()); } } @Override public void onReceiveAd(Ad ad) {} @Override public void onFailedToReceiveAd(Ad ad, AdRequest.ErrorCode error) {} @Override public void onPresentScreen(Ad ad) {} @Override public void onDismissScreen(Ad ad) {} @Override public void onLeaveApplication(Ad ad) {} @Override public void onStart() {} @Override public void onDestroy() {} @Override public void onResume() {} @Override public void onStop() {} } 



Then the initialization of advertising will be:
 AdsControllerBase ads = new AdMobController(this, layout); 


With this implementation, in the event of a change of site, we simply create an instance of another class. To work, you need only application_id. which you get after creating in the application in the admin Admob.

In-app purchasing or internal payments in applications


In order to work with the purchase system, you need the IMarketBillingService.aidl file. It lies in the / user / android-sdk-linux / extras / google / play_billing directory with the SDK. Put the file in the com.android.vending.billing package of your application.

About the types of purchases can be read here. We are interested in recoverable purchases, that is, those that are tied to an account and reuse them no longer buy. If you delete the application and decide again, the purchase will be restored. In our case, after a purchase is disabled, advertising will no longer bother the user. This also applies to other devices: if a user logs in to another device under his account, the purchase will be restored to the application and advertising will be disabled.

To work, you need to add permission in AndroidManifest.xml:
<uses-permission android: name = "com.android.vending.BILLING" />

The official documentation and an example from the SDK helps a lot.

It is necessary to determine the key in the application - PublicKey, obtained when registering an account on the Android Market
We define IabHelper and initialize. If successful, then try to restore the purchase.

 // id      Google Play static final String SKU_ADS_DISABLE = "com.ads.disable"; IabHelper mHelper; private void billingInit() { mHelper = new IabHelper(this, BASE64_PUBLIC_KEY); //   (      false) mHelper.enableDebugLogging(true); // ;   //  ,    mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() { public void onIabSetupFinished(IabResult result) { if (!result.isSuccess()) { return; } //    mHelper. queryInventoryAsync(mGotInventoryListener); } }); } 


mGotInventoryListener - a purchase recovery listener.
 //    . IabHelper.QueryInventoryFinishedListener mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() { private static final String TAG = "QueryInventoryFinishedListener"; public void onQueryInventoryFinished(IabResult result, Inventory inventory) { LOG.d(TAG, "Query inventory finished."); if (result.isFailure()) { LOG.d(TAG, "Failed to query inventory: " + result); return; } LOG.d(TAG, "Query inventory was successful."); /* *  . *  ,     ,  ,   ! * . verifyDeveloperPayload(). */ Purchase purchase = inventory.getPurchase(SKU_ADS_DISABLE); PreferencesHelper.savePurchase( context, PreferencesHelper.Purchase.DISABLE_ADS, purchase != null && verifyDeveloperPayload(purchase)); ads.show(!PreferencesHelper.isAdsDisabled()); } }; 

Now we need to implement the purchase itself:

 private void buy(){ if(!PreferencesHelper.isAdsDisabled()){ /*    payload  .       . *          . */ String payload = ""; mHelper.launchPurchaseFlow(this, SKU_ADS_DISABLE, RC_REQUEST, mPurchaseFinishedListener, payload); } } 


SKU_ADS_DISABLE is the ID of the product that you created in Google Play admin. mPurchaseFinishedListener - listener:
 //    IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() { public void onIabPurchaseFinished(IabResult result, Purchase purchase) { if (result.isFailure()) { return; } if (!verifyDeveloperPayload(purchase)) { return; } if (purchase.getSku().equals(SKU_ADS_DISABLE)) { Toast.makeText(getApplicationContext(), "Purchase for disabling ads done.", Toast.LENGTH_SHORT); //   ,    PreferencesHelper.savePurchase( context, PreferencesHelper.Purchase.DISABLE_ADS, true); //   ads.show(!PreferencesHelper.isAdsDisabled()); } } }; 

It is worth talking separately about the verification method:
 boolean verifyDeveloperPayload(Purchase p) { String payload = p.getDeveloperPayload(); /* * TODO:      *        . */ return true; } 


There is no verification of purchases now, but in a real application you must verify the data obtained with the generated string that you sent in the purchase request. You need to check it on your third-party server. For usually applications or off-line games, this may not be critical, but for online games this is very important.

In principle, everything, now when you start the application, check the settings (where we saved that we turned off the advertisement):
 PreferencesHelper.loadSettings(this); 

After that, the ads will no longer appear.

Testing purchases


Now it's pretty convenient to test your application. You can upload .apk as alpha / beta version and publish. In this case, you can assign a group on Google+, which will be able to test. If you publish an alpha or beta version of the application, then it will not appear in the market, only this group will have access.


Testers will be able to make purchases. Money will be charged without commission and will be refunded after 15 minutes after purchase. So, do not worry. But you will not be able to test the application if your account on the device and the publisher account are the same = /

Fully working example can look at the githaba .

Source: https://habr.com/ru/post/203368/


All Articles