com.android.billingclient.api.BillingClient.BillingResponse Java Examples

The following examples show how to use com.android.billingclient.api.BillingClient.BillingResponse. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GooglePlayBillingVendor.java    From Cashier with Apache License 2.0 6 votes vote down vote up
private Error getDetailsError(int responseCode) {
    final int code;
    switch (responseCode) {
        case BillingResponse.FEATURE_NOT_SUPPORTED:
        case BillingResponse.SERVICE_DISCONNECTED:
        case BillingResponse.SERVICE_UNAVAILABLE:
        case BillingResponse.BILLING_UNAVAILABLE:
        case BillingResponse.ITEM_UNAVAILABLE:
            code = PRODUCT_DETAILS_UNAVAILABLE;
            break;
        case BillingResponse.USER_CANCELED:
        case BillingResponse.ITEM_NOT_OWNED:
        case BillingResponse.DEVELOPER_ERROR:
        case BillingResponse.ERROR:
        default:
            code = PRODUCT_DETAILS_QUERY_FAILURE;
            break;
    }

    return new Error(code, responseCode);
}
 
Example #2
Source File: MainActivity.java    From scroball with MIT License 6 votes vote down vote up
@Override
protected void onResume() {
  super.onResume();
  billingClient = new BillingClient.Builder(this).setListener(this).build();
  billingClient.startConnection(
      new BillingClientStateListener() {
        @Override
        public void onBillingSetupFinished(@BillingResponse int billingResponseCode) {
          if (billingResponseCode == BillingResponse.OK) {
            Purchase.PurchasesResult purchasesResult =
                billingClient.queryPurchases(BillingClient.SkuType.INAPP);
            onPurchasesUpdated(
                purchasesResult.getResponseCode(), purchasesResult.getPurchasesList());
          }
        }

        @Override
        public void onBillingServiceDisconnected() {}
      });
}
 
Example #3
Source File: MainActivity.java    From scroball with MIT License 6 votes vote down vote up
@Override
public void onPurchasesUpdated(int responseCode, List<Purchase> purchases) {
  if (responseCode != BillingResponse.OK) {
    purchaseFailed();
  } else if (purchases != null) {
    for (Purchase purchase : purchases) {
      if (purchase.getSku().equals(REMOVE_ADS_SKU)) {
        RelativeLayout parent = (RelativeLayout) adView.getParent();
        if (parent != null) {
          parent.removeView(adView);
        }
        this.invalidateOptionsMenu();
        this.adsRemoved = true;
        SharedPreferences.Editor editor = application.getSharedPreferences().edit();
        editor.putBoolean(REMOVE_ADS_SKU, true);
        editor.apply();
      }
    }
  }
}
 
Example #4
Source File: AcquireFragment.java    From play-billing-codelab with Apache License 2.0 6 votes vote down vote up
/**
 * Executes query for SKU details at the background thread
 */
private void handleManagerAndUiReady() {
    // Start querying for SKUs
    List<String> inAppSkus = mBillingProvider.getBillingManager().getSkus(SkuType.INAPP);
    mBillingProvider.getBillingManager().querySkuDetailsAsync(SkuType.INAPP, inAppSkus,
            new SkuDetailsResponseListener() {
                @Override
                public void onSkuDetailsResponse(int responseCode, List<SkuDetails> skuDetailsList) {
                    if (responseCode == BillingResponse.OK
                            && skuDetailsList != null) {
                        for (SkuDetails details : skuDetailsList) {
                            Log.w(TAG, "Got a SKU: " + details);
                        }
                    }
                }
            });
    
    // Show the UI
    displayAnErrorIfNeeded();
}
 
Example #5
Source File: MainActivity.java    From FCM-for-Mojo with GNU General Public License v3.0 6 votes vote down vote up
private void showDonateGooglePlay() {
    mBillingClient = BillingClient.newBuilder(this).setListener(this).build();

    mBillingClient.startConnection(new BillingClientStateListener() {
        @Override
        public void onBillingSetupFinished(@BillingResponse int billingResponseCode) {
            if (billingResponseCode == BillingResponse.OK) {
                // The billing client is ready. You can query purchases here.
                BillingFlowParams flowParams = BillingFlowParams.newBuilder()
                        .setSku("donate_2")
                        .setType(SkuType.INAPP)
                        .build();
                mBillingClient.launchBillingFlow(MainActivity.this, flowParams);
            }
        }

        @Override
        public void onBillingServiceDisconnected() {
            // Try to restart the connection on the next request to
            // Google Play by calling the startConnection() method.
        }
    });
}
 
Example #6
Source File: BillingPlugin.java    From flutter_billing with Apache License 2.0 6 votes vote down vote up
boolean handlePurchases(final List<Purchase> purchases) {
    Purchase purchase = findPurchase(purchases, identifier);
    if (purchase == null) return false;
    if (consume) {
        billingClient.consumeAsync(purchase.getPurchaseToken(), new ConsumeResponseListener() {
            @Override
            public void onConsumeResponse(int responseCode, String purchaseToken) {
                if (responseCode != BillingResponse.OK) {
                    Log.w(TAG, "Failed to consume product with code " + responseCode);
                }
                result.success(getIdentifiers(purchases));
            }
        });
    } else {
        result.success(getIdentifiers(purchases));
    }
    return true;
}
 
Example #7
Source File: GooglePlayBillingVendor.java    From Cashier with Apache License 2.0 6 votes vote down vote up
@Override
public void getProductDetails(@NonNull Context context, @NonNull final String sku, final boolean isSubscription,
                              @NonNull final ProductDetailsListener listener) {
    throwIfUninitialized();

    api.getSkuDetails(
            isSubscription ? SkuType.SUBS : SkuType.INAPP,
            Collections.singletonList(sku),
            new SkuDetailsResponseListener() {
                @Override
                public void onSkuDetailsResponse(int responseCode, List<SkuDetails> skuDetailsList) {
                    if (responseCode == BillingResponse.OK && skuDetailsList.size() == 1) {
                        logSafely("Successfully got sku details for " + sku + "!");
                        listener.success(
                                GooglePlayBillingProduct.create(skuDetailsList.get(0), isSubscription ? SkuType.SUBS : SkuType.INAPP)
                        );
                    } else {
                        logSafely("Error getting sku details for " + sku + " with code "+responseCode);
                        listener.failure(getDetailsError(responseCode));
                    }
                }
            }
    );
}
 
Example #8
Source File: GooglePlayBillingVendor.java    From Cashier with Apache License 2.0 6 votes vote down vote up
private Error getConsumeError(int responseCode) {
    final int code;
    switch (responseCode) {
        case BillingResponse.FEATURE_NOT_SUPPORTED:
        case BillingResponse.SERVICE_DISCONNECTED:
        case BillingResponse.BILLING_UNAVAILABLE:
        case BillingResponse.ITEM_UNAVAILABLE:
            code = CONSUME_UNAVAILABLE;
            break;
        case BillingResponse.USER_CANCELED:
            code = CONSUME_CANCELED;
            break;
        case BillingResponse.ITEM_NOT_OWNED:
            code = CONSUME_NOT_OWNED;
            break;
        case BillingResponse.DEVELOPER_ERROR:
        case BillingResponse.ERROR:
        default:
            code = CONSUME_FAILURE;
            break;
    }

    return new Error(code, responseCode);
}
 
Example #9
Source File: BillingPlugin.java    From flutter_billing with Apache License 2.0 6 votes vote down vote up
private void purchase(final String identifier, final Boolean consume, final Result result) {
    executeServiceRequest(new Request() {
        @Override
        public void execute() {
            int responseCode = billingClient.launchBillingFlow(
                    activity,
                    BillingFlowParams.newBuilder()
                                     .setSku(identifier)
                                     .setType(SkuType.INAPP)
                                     .build());

            if (responseCode == BillingResponse.OK) {
                PurchaseRequest request = new PurchaseRequest(identifier, consume, result);
                pendingPurchaseRequests.add(request);
            } else {
                result.error("ERROR", "Failed to launch billing flow to purchase an item with error " + responseCode, null);
            }
        }

        @Override
        public void failed() {
            result.error("UNAVAILABLE", "Billing service is unavailable!", null);
        }
    });
}
 
Example #10
Source File: GooglePlayBillingVendor.java    From Cashier with Apache License 2.0 5 votes vote down vote up
private Error getPurchaseError(int responseCode) {
    final int code;
    switch (responseCode) {
        case BillingResponse.FEATURE_NOT_SUPPORTED:
        case BillingResponse.SERVICE_DISCONNECTED:
        case BillingResponse.SERVICE_UNAVAILABLE:
        case BillingResponse.BILLING_UNAVAILABLE:
        case BillingResponse.ITEM_UNAVAILABLE:
            code = PURCHASE_UNAVAILABLE;
            break;
        case BillingResponse.USER_CANCELED:
            code = PURCHASE_CANCELED;
            break;
        case BillingResponse.ITEM_ALREADY_OWNED:
            code = PURCHASE_ALREADY_OWNED;
            break;
        case BillingResponse.ITEM_NOT_OWNED:
            code = PURCHASE_NOT_OWNED;
            break;
        case BillingResponse.DEVELOPER_ERROR:
        case BillingResponse.ERROR:
        default:
            code = PURCHASE_FAILURE;
            break;
    }

    return new Error(code, responseCode);
}
 
Example #11
Source File: GooglePlayBillingVendor.java    From Cashier with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized void consume(@NonNull final Context context, @NonNull final Purchase purchase, @NonNull final ConsumeListener listener) {
    Preconditions.checkNotNull(context, "Purchase is null");
    Preconditions.checkNotNull(listener, "Consume listener is null");
    throwIfUninitialized();

    final Product product = purchase.product();
    if (product.isSubscription()) {
        throw new IllegalStateException("Cannot consume a subscription");
    }

    if (tokensToBeConsumed.contains(purchase.token())) {
        // Purchase currently being consumed or already successfully consumed.
        logSafely("Token was already scheduled to be consumed - skipping...");
        listener.failure(purchase, new Error(VendorConstants.CONSUME_UNAVAILABLE, -1));
        return;
    }

    logSafely("Consuming " + product.sku());
    tokensToBeConsumed.add(purchase.token());

    api.consumePurchase(purchase.token(), new ConsumeResponseListener() {
        @Override
        public void onConsumeResponse(int responseCode, String purchaseToken) {
            if (responseCode == BillingResponse.OK) {
                logSafely("Successfully consumed " + purchase.product().sku() + "!");
                listener.success(purchase);
            } else {
                // Failure in consuming token, remove from the list so retry is possible
                logSafely("Error consuming " + purchase.product().sku() + " with code "+responseCode);
                tokensToBeConsumed.remove(purchaseToken);
                listener.failure(purchase, getConsumeError(responseCode));
            }
        }
    });
}
 
Example #12
Source File: GooglePlayBillingVendor.java    From Cashier with Apache License 2.0 5 votes vote down vote up
@Override
public void onPurchasesUpdated(@BillingResponse int responseCode,
                               @Nullable List<com.android.billingclient.api.Purchase> purchases) {
    if (purchaseListener == null) {
        pendingProduct = null;
        logSafely("#onPurchasesUpdated called but no purchase listener attached.");
        return;
    }

    switch (responseCode) {
        case BillingResponse.OK:
            if (purchases == null || purchases.isEmpty()) {
                purchaseListener.failure(pendingProduct, new Error(PURCHASE_FAILURE, responseCode));
                clearPendingPurchase();
                return;
            }

            for (com.android.billingclient.api.Purchase purchase : purchases) {
                handlePurchase(purchase, responseCode);
            }
            return;
        case BillingResponse.USER_CANCELED:
            logSafely("User canceled the purchase code: " + responseCode);
            purchaseListener.failure(pendingProduct, getPurchaseError(responseCode));
            clearPendingPurchase();
            return;
        default:
            logSafely("Error purchasing item with code: " + responseCode);
            purchaseListener.failure(pendingProduct, getPurchaseError(responseCode));
            clearPendingPurchase();
    }
}
 
Example #13
Source File: GooglePlayBillingVendor.java    From Cashier with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized void initialized(boolean success) {
    logSafely("Initialized: success = " + success);
    if (!success) {
        logAndDisable("Could not create Google Play Billing instance");
        return;
    }

    try {
        canPurchaseItems =
                api.isBillingSupported(SkuType.INAPP) == BillingResponse.OK;

        canSubscribe =
                api.isBillingSupported(SkuType.SUBS) == BillingResponse.OK;

        available = canPurchaseItems || canSubscribe;
        logSafely("Connected to service and it is " + (available ? "available" : "not available"));
        initializing = false;

        for (InitializationListener listener : initializationListeners) {
            listener.initialized();
        }
        initializationListeners.clear();
    } catch (Exception error) {
        logAndDisable(Log.getStackTraceString(error));
    }
}
 
Example #14
Source File: GooglePlayBillingApi.java    From Cashier with Apache License 2.0 5 votes vote down vote up
@Override
public void onBillingSetupFinished(@BillingResponse int billingResponseCode) {
    logSafely("Service setup finished and connected. Response: " + billingResponseCode);

    if (billingResponseCode == BillingResponse.OK) {
        isServiceConnected = true;

        if (listener != null) {
            listener.initialized(available());
        }
    }
}
 
Example #15
Source File: GooglePlayBillingApi.java    From Cashier with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public List<Purchase> getPurchases(String itemType) {
    throwIfUnavailable();

    Purchase.PurchasesResult purchasesResult = billing.queryPurchases(itemType);
    if (purchasesResult.getResponseCode() == BillingResponse.OK) {
        List<Purchase> purchases = purchasesResult.getPurchasesList();
        logSafely(itemType + " purchases: " + TextUtils.join(", ", purchases));
        return purchases;
    }

    return null;
}
 
Example #16
Source File: GooglePlayBillingApi.java    From Cashier with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public List<Purchase> getPurchases() {
    throwIfUnavailable();

    List<Purchase> allPurchases = new ArrayList<>();

    logSafely("Querying in-app purchases...");
    Purchase.PurchasesResult inAppPurchasesResult = billing.queryPurchases(SkuType.INAPP);

    if (inAppPurchasesResult.getResponseCode() == BillingResponse.OK) {
        List<Purchase> inAppPurchases = inAppPurchasesResult.getPurchasesList();
        logSafely("In-app purchases: " + TextUtils.join(", ", inAppPurchases));
        allPurchases.addAll(inAppPurchases);
        // Check if we support subscriptions and query those purchases as well
        boolean isSubscriptionSupported =
                billing.isFeatureSupported(FeatureType.SUBSCRIPTIONS) == BillingResponse.OK;
        if (isSubscriptionSupported) {
            logSafely("Querying subscription purchases...");
            Purchase.PurchasesResult subscriptionPurchasesResult = billing.queryPurchases(SkuType.SUBS);

            if (subscriptionPurchasesResult.getResponseCode() == BillingResponse.OK) {
                List<Purchase> subscriptionPurchases = subscriptionPurchasesResult.getPurchasesList();
                logSafely("Subscription purchases: " + TextUtils.join(", ", subscriptionPurchases));
                allPurchases.addAll(subscriptionPurchases);
                return allPurchases;
            } else {
                logSafely("Error in querying subscription purchases with code: "
                        + subscriptionPurchasesResult.getResponseCode());
                return allPurchases;
            }
        } else {
            logSafely("Subscriptions are not supported...");
            return allPurchases;
        }
    } else {
        return null;
    }
}
 
Example #17
Source File: GooglePlayBillingApi.java    From Cashier with Apache License 2.0 5 votes vote down vote up
@Override
public void launchBillingFlow(@NonNull final Activity activity, @NonNull String sku, @SkuType String itemType) {
    throwIfUnavailable();
    logSafely("Launching billing flow for " + sku + " with type " + itemType);

    getSkuDetails(
            itemType,
            Collections.singletonList(sku),
            new SkuDetailsResponseListener() {
                @Override
                public void onSkuDetailsResponse(int responseCode, List<SkuDetails> skuDetailsList) {
                    try {
                        if (responseCode == BillingResponse.OK && skuDetailsList.size() > 0) {
                            BillingFlowParams billingFlowParams = BillingFlowParams.newBuilder()
                                    .setSkuDetails(skuDetailsList.get(0))
                                    .build();

                            // This will call the {@link PurchasesUpdatedListener} specified in {@link #initialize}
                            billing.launchBillingFlow(activity, billingFlowParams);
                        } else {
                            vendor.onPurchasesUpdated(BillingResponse.ERROR, null);
                        }
                    } catch (Exception e) {
                        vendor.onPurchasesUpdated(BillingResponse.ERROR, null);
                    }
                }
            }
    );
}
 
Example #18
Source File: GooglePlayBillingApi.java    From Cashier with Apache License 2.0 5 votes vote down vote up
@Override
public int isBillingSupported(@SkuType String itemType) {
    throwIfUnavailable();

    if (SkuType.INAPP.equalsIgnoreCase(itemType) && billing.isReady()) {
        return BillingResponse.OK;
    } else if (SkuType.SUBS.equalsIgnoreCase(itemType)) {
        return billing.isFeatureSupported(FeatureType.SUBSCRIPTIONS);
    }

    return BillingResponse.FEATURE_NOT_SUPPORTED;
}
 
Example #19
Source File: BillingManager.java    From play-billing-codelab with Apache License 2.0 5 votes vote down vote up
public BillingManager(Activity activity) {
    mActivity = activity;
    mBillingClient = BillingClient.newBuilder(mActivity).setListener(this).build();
    mBillingClient.startConnection(new BillingClientStateListener() {
        @Override
        public void onBillingSetupFinished(@BillingResponse int billingResponse) {
            Log.i(TAG, "onBillingSetupFinished() response: " + billingResponse);
        }
        @Override
        public void onBillingServiceDisconnected() {
            Log.w(TAG, "onBillingServiceDisconnected()");
        }
    });
}
 
Example #20
Source File: MainActivity.java    From scroball with MIT License 5 votes vote down vote up
@Override
public boolean onOptionsItemSelected(MenuItem item) {
  switch (item.getItemId()) {
    case R.id.settings_item:
      Intent intent = new Intent(getBaseContext(), SettingsActivity.class);
      startActivityForResult(intent, 1);
      return true;
    case R.id.remove_ads_item:
      BillingFlowParams.Builder builder =
          new BillingFlowParams.Builder()
              .setSku(REMOVE_ADS_SKU)
              .setType(BillingClient.SkuType.INAPP);
      int responseCode = billingClient.launchBillingFlow(this, builder.build());
      if (responseCode != BillingResponse.OK) {
        purchaseFailed();
      }
      return true;
    case R.id.privacy_policy_item:
      Intent browserIntent =
          new Intent(
              Intent.ACTION_VIEW,
              Uri.parse("https://scroball.peterjosling.com/privacy_policy.html"));
      startActivity(browserIntent);
      return true;
    case R.id.logout_item:
      logout();
      return true;
    default:
      return super.onOptionsItemSelected(item);
  }
}
 
Example #21
Source File: BillingPlugin.java    From flutter_billing with Apache License 2.0 5 votes vote down vote up
private void fetchProducts(final List<String> identifiers, final Result result) {
    executeServiceRequest(new Request() {
        @Override
        public void execute() {
            billingClient.querySkuDetailsAsync(
                    SkuDetailsParams.newBuilder()
                                    .setSkusList(identifiers)
                                    .setType(SkuType.INAPP)
                                    .build(),
                    new SkuDetailsResponseListener() {
                        @Override
                        public void onSkuDetailsResponse(int responseCode, List<SkuDetails> skuDetailsList) {
                            if (responseCode == BillingResponse.OK) {
                                List<Map<String, Object>> products = getProductsFromSkuDetails(skuDetailsList);
                                result.success(products);
                            } else {
                                result.error("ERROR", "Failed to fetch products!", null);
                            }
                        }
                    });
        }

        @Override
        public void failed() {
            result.error("UNAVAILABLE", "Billing service is unavailable!", null);
        }
    });
}
 
Example #22
Source File: AcquireFragment.java    From play-billing-codelab with Apache License 2.0 5 votes vote down vote up
/**
 * Executes query for SKU details at the background thread
 */
private void handleManagerAndUiReady() {
    final List<SkuRowData> inList = new ArrayList<>();
    SkuDetailsResponseListener responseListener = new SkuDetailsResponseListener() {
        @Override
        public void onSkuDetailsResponse(int responseCode,
                                         List<SkuDetails> skuDetailsList) {
            if (responseCode == BillingResponse.OK && skuDetailsList != null) {
                // Repacking the result for an adapter
                for (SkuDetails details : skuDetailsList) {
                    Log.i(TAG, "Found sku: " + details);
                    inList.add(new SkuRowData(details.getSku(), details.getTitle(),
                            details.getPrice(), details.getDescription(),
                            details.getType()));
                }
                if (inList.size() == 0) {
                    displayAnErrorIfNeeded();
                } else {
                    mAdapter.updateData(inList);
                    setWaitScreen(false);
                }
            }
        }
    };

    // Start querying for in-app SKUs
    List<String> skus = mBillingProvider.getBillingManager().getSkus(SkuType.INAPP);
    mBillingProvider.getBillingManager().querySkuDetailsAsync(SkuType.INAPP, skus, responseListener);
    // Start querying for subscriptions SKUs
    skus = mBillingProvider.getBillingManager().getSkus(SkuType.SUBS);
    mBillingProvider.getBillingManager().querySkuDetailsAsync(SkuType.SUBS, skus, responseListener);
}
 
Example #23
Source File: BillingManager.java    From play-billing-codelab with Apache License 2.0 5 votes vote down vote up
/**
 * Trying to restart service connection.
 * <p>Note: It's just a primitive example - it's up to you to develop a real retry-policy.</p>
 * @param executeOnSuccess This runnable will be executed once the connection to the Billing
 *                         service is restored.
 */
private void startServiceConnection(final Runnable executeOnSuccess) {
    mBillingClient.startConnection(new BillingClientStateListener() {
        @Override
        public void onBillingSetupFinished(@BillingResponse int billingResponse) {
            Log.i(TAG, "onBillingSetupFinished() response: " + billingResponse);
        }
        @Override
        public void onBillingServiceDisconnected() {
            Log.w(TAG, "onBillingServiceDisconnected()");
        }
    });
}
 
Example #24
Source File: BillingManager.java    From play-billing-codelab with Apache License 2.0 5 votes vote down vote up
public BillingManager(Activity activity) {
    mActivity = activity;
    mBillingClient = BillingClient.newBuilder(mActivity).setListener(this).build();
    mBillingClient.startConnection(new BillingClientStateListener() {
        @Override
        public void onBillingSetupFinished(@BillingResponse int billingResponse) {
            Log.i(TAG, "onBillingSetupFinished() response: " + billingResponse);
        }
        @Override
        public void onBillingServiceDisconnected() {
            Log.w(TAG, "onBillingServiceDisconnected()");
        }
    });
}
 
Example #25
Source File: AcquireFragment.java    From play-billing-codelab with Apache License 2.0 5 votes vote down vote up
/**
 * Executes query for SKU details at the background thread
 */
private void handleManagerAndUiReady() {
    final List<SkuRowData> inList = new ArrayList<>();
    SkuDetailsResponseListener responseListener = new SkuDetailsResponseListener() {
        @Override
        public void onSkuDetailsResponse(int responseCode,
                                         List<SkuDetails> skuDetailsList) {
            if (responseCode == BillingResponse.OK && skuDetailsList != null) {
                // Repacking the result for an adapter
                for (SkuDetails details : skuDetailsList) {
                    Log.i(TAG, "Found sku: " + details);
                    inList.add(new SkuRowData(details.getSku(), details.getTitle(),
                            details.getPrice(), details.getDescription(),
                            details.getType()));
                }
                if (inList.size() == 0) {
                    displayAnErrorIfNeeded();
                } else {
                    mAdapter.updateData(inList);
                    setWaitScreen(false);
                }
            }
        }
    };

    // Start querying for in-app SKUs
    List<String> skus = mBillingProvider.getBillingManager().getSkus(SkuType.INAPP);
    mBillingProvider.getBillingManager().querySkuDetailsAsync(SkuType.INAPP, skus, responseListener);
    // Start querying for subscriptions SKUs
    skus = mBillingProvider.getBillingManager().getSkus(SkuType.SUBS);
    mBillingProvider.getBillingManager().querySkuDetailsAsync(SkuType.SUBS, skus, responseListener);
}
 
Example #26
Source File: BillingManager.java    From play-billing-codelab with Apache License 2.0 5 votes vote down vote up
/**
 * Trying to restart service connection if it's needed or just execute a request.
 * <p>Note: It's just a primitive example - it's up to you to implement a real retry-policy.</p>
 * @param executeOnSuccess This runnable will be executed once the connection to the Billing
 *                         service is restored.
 */
private void startServiceConnectionIfNeeded(final Runnable executeOnSuccess) {
    if (mBillingClient.isReady()) {
        if (executeOnSuccess != null) {
            executeOnSuccess.run();
        }
    } else {
        mBillingClient.startConnection(new BillingClientStateListener() {
            @Override
            public void onBillingSetupFinished(@BillingResponse int billingResponse) {
                if (billingResponse == BillingResponse.OK) {
                    Log.i(TAG, "onBillingSetupFinished() response: " + billingResponse);
                    if (executeOnSuccess != null) {
                        executeOnSuccess.run();
                    }
                } else {
                    Log.w(TAG, "onBillingSetupFinished() error code: " + billingResponse);
                }
            }

            @Override
            public void onBillingServiceDisconnected() {
                Log.w(TAG, "onBillingServiceDisconnected()");
            }
        });
    }
}
 
Example #27
Source File: AcquireFragment.java    From play-billing-codelab with Apache License 2.0 5 votes vote down vote up
/**
 * Executes query for SKU details at the background thread
 */
private void handleManagerAndUiReady() {
    final List<SkuRowData> inList = new ArrayList<>();
    SkuDetailsResponseListener responseListener = new SkuDetailsResponseListener() {
        @Override
        public void onSkuDetailsResponse(int responseCode,
                List<SkuDetails> skuDetailsList) {
            // If we successfully got SKUs, add a header in front of it
            if (responseCode == BillingResponse.OK && skuDetailsList != null) {
                // Repacking the result for an adapter
                for (SkuDetails details : skuDetailsList) {
                    Log.i(TAG, "Found sku: " + details);
                    inList.add(new SkuRowData(details.getSku(), details.getTitle(),
                            details.getPrice(), details.getDescription(),
                            details.getType()));
                }
                if (inList.size() == 0) {
                    displayAnErrorIfNeeded();
                } else {
                    mAdapter.updateData(inList);
                    setWaitScreen(false);
                }
            }
        }
    };

    // Start querying for in-app SKUs
    List<String> skus = mBillingProvider.getBillingManager().getSkus(SkuType.INAPP);
    mBillingProvider.getBillingManager().querySkuDetailsAsync(SkuType.INAPP, skus, responseListener);
    // Start querying for subscriptions SKUs
    skus = mBillingProvider.getBillingManager().getSkus(SkuType.SUBS);
    mBillingProvider.getBillingManager().querySkuDetailsAsync(SkuType.SUBS, skus, responseListener);
}
 
Example #28
Source File: MainActivity.java    From FCM-for-Mojo with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onPurchasesUpdated(int responseCode, @Nullable List<Purchase> purchases) {
    if (responseCode == BillingResponse.OK
            && purchases != null) {
        for (Purchase purchase : purchases) {
            mBillingClient.consumeAsync(purchase.getPurchaseToken(), (responseCode1, purchaseToken) -> {
            });
        }
    }
}
 
Example #29
Source File: BillingPlugin.java    From flutter_billing with Apache License 2.0 5 votes vote down vote up
private void startServiceConnection() {
    if (billingServiceStatus != BillingServiceStatus.IDLE) return;
    billingServiceStatus = BillingServiceStatus.STARTING;
    billingClient.startConnection(new BillingClientStateListener() {
        @Override
        public void onBillingSetupFinished(@BillingResponse int billingResponseCode) {
            Log.d(TAG, "Billing service was setup with code " + billingResponseCode);

            billingServiceStatus = billingResponseCode == BillingResponse.OK ? BillingServiceStatus.READY : BillingServiceStatus.IDLE;
            Request request;

            while ((request = pendingRequests.poll()) != null) {
                if (billingServiceStatus == BillingServiceStatus.READY) {
                    request.execute();
                } else {
                    request.failed();
                }
            }
        }

        @Override
        public void onBillingServiceDisconnected() {
            Log.d(TAG, "Billing service was disconnected!");
            billingServiceStatus = BillingServiceStatus.IDLE;
        }
    });
}
 
Example #30
Source File: BillingPlugin.java    From flutter_billing with Apache License 2.0 5 votes vote down vote up
private void fetchPurchases(final Result result) {
    executeServiceRequest(new Request() {
        @Override
        public void execute() {
            List<String> identifiers = new ArrayList<>();

            Purchase.PurchasesResult purchasesResult = billingClient.queryPurchases(SkuType.INAPP);
            if (purchasesResult.getResponseCode() == BillingResponse.OK) {
                identifiers.addAll(getIdentifiers(purchasesResult.getPurchasesList()));
            } else {
                Log.w(TAG, "Failed to query purchases for in app products " +
                        "with error " + purchasesResult.getResponseCode());
            }

            purchasesResult = billingClient.queryPurchases(SkuType.SUBS);
            if (purchasesResult.getResponseCode() == BillingResponse.OK) {
                identifiers.addAll(getIdentifiers(purchasesResult.getPurchasesList()));
            } else {
                Log.w(TAG, "Failed to query purchases for in app subscriptions " +
                        "with error " + purchasesResult.getResponseCode());
            }

            result.success(identifiers);
        }

        @Override
        public void failed() {
            result.error("UNAVAILABLE", "Billing service is unavailable!", null);
        }
    });
}