2

I am trying to implement in-app billing for my app. And I am following the Android In-app billing tutorial from Google.

In the tutorial, IabHelper is an instance variable of an Activity. To instantiate an IabHelper, we need to pass a Context, in this case the Activity itself.

I have several Activtys that need to communicate with the Google Play Store. Is it bad to create multiple IabHelpers for different Activitys?

If it is bad, how do I make one IabHelper available for different Activitys? How how do I tell the IabHelper that the Context has changed as I switch between Activitys?

Thank you.

Jonas
  • 534
  • 8
  • 16

1 Answers1

0

I've found next solution: I do initialization inside Application > onCreate method:

@Override
    public void onCreate() {
        final IabHelper iabHelper = IabHelper.createInstance(getApplicationContext(), AppHelper.getPublicKey());
}

Then when you need to launch a purchase you should do:

public static void launchPurchase():void {
    final AppCompatActivity foregAct = sFacade.getForegroundActivity();
    final String payload = AppHelper.generateDeveloperPayload();
    final IabHelper iabHelper = IabHelper.getInstance();
    if (iabHelper != null) {
        iabHelper.launchPurchaseFlow(foregAct, AppHelper.SKU_PRO, AppHelper.RC_REQUEST, mPurchaseFinishedListener, payload);
    }
}

Where getForegroundActivity can be implemented in different way for example:

public AppCompatActivity getForegroundActivity() {
    if (MainActivity.isForeground) {
        return (AppCompatActivity) retrieveEntity(MainActivity.NAME);
    } else if (MiscActivity.isForeground) {
        return (AppCompatActivity) retrieveEntity(MiscActivity.NAME);
    } if (GameActivity.isForeground) {
        return (AppCompatActivity) retrieveEntity(GameActivity.NAME);
    }  else {
        return (AppCompatActivity) retrieveEntity(HelpActivity.NAME);
    }
}

Or you can choose another methods for tracking foreground activity:

How to check if activity is in foreground or in visible background?

Android: How can I get the current foreground activity (from a service)?

At last, don't dispose IabHelper in any activity. And you should include handling code into each activity from which you can launch a purchase:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        final IabHelper iabHelper = IabHelper.getInstance();
        if (iabHelper != null) {
            iabHelper.handleActivityResult(requestCode, resultCode, data);
        }
}
Community
  • 1
  • 1
Oleksandr Albul
  • 1,611
  • 1
  • 23
  • 31