Skip to content

Instantly share code, notes, and snippets.

@kcochibili
Last active November 16, 2022 03:50
Show Gist options
  • Save kcochibili/de641c434ec6fe7236004009d9b09727 to your computer and use it in GitHub Desktop.
Save kcochibili/de641c434ec6fe7236004009d9b09727 to your computer and use it in GitHub Desktop.
Singleton class that fixes the issue with the android-inapp-billing-v3 library. This fix allows you to flawlessly use the BillingProcessor in multiple activities, without encountering this issue: https://github.com/anjlab/android-inapp-billing-v3/issues/503
package com.your.package.name;
import android.app.Activity;
import com.anjlab.android.iab.v3.BillingProcessor;
// This singleton class is designed to fix this issue: https://github.com/anjlab/android-inapp-billing-v3/issues/503
// the solution is based on this suggestion: https://github.com/anjlab/android-inapp-billing-v3/issues/501#issuecomment-962612355
public class BillingHolder {
private static BillingHolder single_instance = null;
private BillingProcessor bp;
public String lastBillingActivity = "";
private BillingHolder()
{
}
public static BillingHolder getInstance()
{
if (single_instance == null)
single_instance = new BillingHolder();
return single_instance;
}
public void killLast(){
if (bp != null) {
bp.release();
bp = null;
}
}
public BillingProcessor getBp(Activity activity){
String currentActivityName = activity.getClass().getSimpleName();
if(!currentActivityName.equals(lastBillingActivity)){
killLast(); //to fix https://github.com/anjlab/android-inapp-billing-v3/issues/503
return getNew(activity);
}else{
if(bp != null){
return bp;
}else{
return getNew(activity);
}
}
}
private BillingProcessor getNew(Activity activity){
bp = BillingProcessor.newBillingProcessor(activity, null, (BillingProcessor.IBillingHandler) activity); // doesn't bind
bp.initialize(); // binds
lastBillingActivity = activity.getClass().getSimpleName();
return bp;
}
}
@kcochibili
Copy link
Author

kcochibili commented Jan 1, 2022

Example 1:
put this in the onResume method of every activity that uses billing:

	@Override
	protected void onResume() {
		super.onResume();

		BillingHolder.getInstance().getBp(this); // must be in every activity that uses billing

	}

to use this class, simply use it directly like below.
BillingHolder.getInstance().getBp(this).purchase(this, "food");

Example 2:
put this on the onResume method of every activity that uses billing:

        public BillingProcessor bp;

	@Override
	protected void onResume() {
		super.onResume();

		bp = BillingHolder.getInstance().getBp(this); // must be in every activity that uses billing

	}

usage:
bp.purchase(this, "food");

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment