com.android.vending.billing.IInAppBillingService Java Examples

The following examples show how to use com.android.vending.billing.IInAppBillingService. 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: GoogleBillingHelper.java    From OPFIab with Apache License 2.0 11 votes vote down vote up
/**
 * Wraps {@link IInAppBillingService#getBuyIntent(int, String, String, String, String)}
 *
 * @param sku      SKU of a product to purchase.
 * @param itemType Type of an item to purchase.
 *
 * @return Bundle containing purchase intent. Can be null.
 */
@Nullable
Bundle getBuyIntent(@NonNull final String sku, @NonNull final ItemType itemType) {
    OPFLog.logMethod(sku, itemType);
    final IInAppBillingService service = getService();
    if (service == null) {
        return null;
    }
    try {
        final String type = itemType.toString();
        final Bundle result = service.getBuyIntent(API, packageName, sku, type, "");
        final Response response = GoogleUtils.getResponse(result);
        OPFLog.d("Response: %s. Result: %s", response, OPFUtils.toString(result));
        return result;
    } catch (RemoteException exception) {
        OPFLog.d("getBuyIntent request failed.", exception);
    }
    return null;
}
 
Example #2
Source File: ServiceTest.java    From android-easy-checkout with Apache License 2.0 6 votes vote down vote up
@Test
public void onServiceConnected() throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    Intent intent = new Intent(Constants.ACTION_BILLING_SERVICE_BIND);
    intent.setPackage(Constants.VENDING_PACKAGE);
    final ServiceBinder conn = new ServiceBinder(
            mDataConverter.newBillingContext(RuntimeEnvironment.application), intent);

    conn.getServiceAsync(new ServiceBinder.Handler() {
        @Override
        public void onBind(IInAppBillingService service) {
            assertThat(service).isNotNull();
            latch.countDown();
        }

        @Override
        public void onError(BillingException e) {
            throw new IllegalStateException(e);
        }
    });
    conn.onServiceConnected(null, mServiceStub.create(new Bundle()).asBinder());

    latch.await(15, TimeUnit.SECONDS);
}
 
Example #3
Source File: DonationService.java    From ghwatch with Apache License 2.0 6 votes vote down vote up
public static void consumeAllPurchases(Activity activity, SupportAppDevelopmentDialogFragment dialog, IInAppBillingService mService) {
  try {
    Bundle ownedItems = mService.getPurchases(3, activity.getPackageName(), IabHelper.ITEM_TYPE_INAPP, null);
    int response = ownedItems.getInt("RESPONSE_CODE");
    if (response == 0) {
      ArrayList<String> purchaseDataList = ownedItems.getStringArrayList("INAPP_PURCHASE_DATA_LIST");
      for (String purchaseData : purchaseDataList) {
        JSONObject jo = new JSONObject(purchaseData);
        mService.consumePurchase(3, activity.getPackageName(), jo.getString("purchaseToken"));
      }
    }
  } catch (Exception e) {
    ActivityTracker.sendEvent(activity, ActivityTracker.CAT_BE, "message_err_billing_check_error", e.getMessage(), 0L);
    Log.e(TAG, "InApp billing - exception " + e.getMessage());
  }
}
 
Example #4
Source File: DonationService.java    From ghwatch with Apache License 2.0 6 votes vote down vote up
public static void consumeDisposablePurchases(Activity activity, IInAppBillingService mService) {
  try {
    Bundle ownedItems = mService.getPurchases(3, activity.getPackageName(), IabHelper.ITEM_TYPE_INAPP, null);
    int response = ownedItems.getInt("RESPONSE_CODE");
    if (response == 0) {
      ArrayList<String> purchaseDataList = ownedItems.getStringArrayList("INAPP_PURCHASE_DATA_LIST");
      for (String purchaseData : purchaseDataList) {
        JSONObject jo = new JSONObject(purchaseData);
        if (INAPP_CODE_DONATION_3.equals(jo.getString("productId")))
          mService.consumePurchase(3, activity.getPackageName(), jo.getString("purchaseToken"));
      }
    }
  } catch (Exception e) {
    ActivityTracker.sendEvent(activity, ActivityTracker.CAT_BE, "message_err_billing_check_error", e.getMessage(), 0L);
    Log.e(TAG, "InApp billing - exception " + e.getMessage());
  }
}
 
Example #5
Source File: GoogleBillingHelper.java    From OPFIab with Apache License 2.0 6 votes vote down vote up
/**
 * Tries to check if Google billing is available on current device.
 *
 * @return {@link Response#OK} if billing is supported, another corresponding {@link Response}
 * if it's not. Returns null if error has occurred.
 */
@Nullable
Response isBillingSupported() {
    OPFLog.logMethod();
    final IInAppBillingService service = getService();
    if (service == null) {
        // Can't connect to service.
        return null;
    }
    try {
        for (final ItemType itemType : ItemType.values()) {
            final int code = service.isBillingSupported(API, packageName, itemType.toString());
            final Response response = Response.fromCode(code);
            if (response != Response.OK) {
                // Report first encountered unsuccessful response.
                return response;
            }
        }
        return Response.OK;
    } catch (RemoteException exception) {
        OPFLog.d("Billing check failed.", exception);
    }
    return null;
}
 
Example #6
Source File: GoogleBillingHelper.java    From OPFIab with Apache License 2.0 6 votes vote down vote up
/**
 * Wraps {@link IInAppBillingService#consumePurchase(int, String, String)}
 *
 * @param token Token of a purchase to consume.
 *
 * @return Result of the operation. Can be null.
 */
@Nullable
Response consumePurchase(@NonNull final String token) {
    OPFLog.logMethod(token);
    final IInAppBillingService service = getService();
    if (service == null) {
        return null;
    }
    try {
        final int code = service.consumePurchase(API, packageName, token);
        final Response response = Response.fromCode(code);
        OPFLog.d("Response: %s", response);
        return response;
    } catch (RemoteException exception) {
        OPFLog.e("consumePurchase request failed.", exception);
    }
    return null;
}
 
Example #7
Source File: ServiceTest.java    From android-easy-checkout with Apache License 2.0 6 votes vote down vote up
@Test
public void bindService() throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    Intent intent = new Intent(Constants.ACTION_BILLING_SERVICE_BIND);
    intent.setPackage(Constants.VENDING_PACKAGE);
    final ServiceBinder conn = new ServiceBinder(
            mDataConverter.newBillingContext(RuntimeEnvironment.application), intent);

    ServiceBinder.Handler handler = new ServiceBinder.Handler() {
        @Override
        public void onBind(IInAppBillingService service) {
            assertThat(service).isNotNull();
            latch.countDown();
        }

        @Override
        public void onError(BillingException e) {
            throw new IllegalStateException(e);
        }
    };
    conn.getServiceAsync(handler);

    latch.await(15, TimeUnit.SECONDS);
}
 
Example #8
Source File: ServiceTest.java    From android-easy-checkout with Apache License 2.0 6 votes vote down vote up
@Test
public void callGetServiceAsyncTwice() throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    Intent intent = new Intent(Constants.ACTION_BILLING_SERVICE_BIND);
    intent.setPackage(Constants.VENDING_PACKAGE);
    final ServiceBinder conn = new ServiceBinder(
            mDataConverter.newBillingContext(RuntimeEnvironment.application), intent);

    ServiceBinder.Handler handler = new ServiceBinder.Handler() {
        @Override
        public void onBind(IInAppBillingService service) {
            conn.unbindService();
            latch.countDown();
        }

        @Override
        public void onError(BillingException e) {
            throw new IllegalStateException(e);
        }
    };
    conn.getServiceAsync(handler);
    conn.getServiceAsync(handler);
    conn.onServiceConnected(null, mServiceStub.create(new Bundle()).asBinder());

    latch.await(15, TimeUnit.SECONDS);
}
 
Example #9
Source File: ServiceTest.java    From android-easy-checkout with Apache License 2.0 6 votes vote down vote up
@Test
public void unbindService() throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    Intent intent = new Intent(Constants.ACTION_BILLING_SERVICE_BIND);
    intent.setPackage(Constants.VENDING_PACKAGE);
    final ServiceBinder conn = new ServiceBinder(
            mDataConverter.newBillingContext(RuntimeEnvironment.application), intent);

    conn.getServiceAsync(new ServiceBinder.Handler() {
        @Override
        public void onBind(IInAppBillingService service) {
            conn.unbindService();
            latch.countDown();
        }

        @Override
        public void onError(BillingException e) {
            throw new IllegalStateException(e);
        }
    });
    conn.onServiceConnected(null, mServiceStub.create(new Bundle()).asBinder());

    latch.await(15, TimeUnit.SECONDS);
}
 
Example #10
Source File: ServiceTest.java    From android-easy-checkout with Apache License 2.0 6 votes vote down vote up
@Test
public void onServiceDisconnected() throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    Intent intent = new Intent(Constants.ACTION_BILLING_SERVICE_BIND);
    intent.setPackage(Constants.VENDING_PACKAGE);
    final ServiceBinder conn = new ServiceBinder(
            mDataConverter.newBillingContext(RuntimeEnvironment.application), intent);

    conn.getServiceAsync(new ServiceBinder.Handler() {
        @Override
        public void onBind(IInAppBillingService service) {
            assertThat(service).isNotNull();
            conn.onServiceDisconnected(null);
            latch.countDown();
        }

        @Override
        public void onError(BillingException e) {
            throw new IllegalStateException(e);
        }
    });
    conn.onServiceConnected(null, mServiceStub.create(new Bundle()).asBinder());

    latch.await(15, TimeUnit.SECONDS);
}
 
Example #11
Source File: BillingProcessor.java    From android-easy-checkout with Apache License 2.0 6 votes vote down vote up
private void executeInService(final ServiceBinder.Handler serviceHandler, Handler handler) {
    handler.post(new Runnable() {
        @Override
        public void run() {
            final ServiceBinder conn = createServiceBinder();

            conn.getServiceAsync(new ServiceBinder.Handler() {
                @Override
                public void onBind(IInAppBillingService service) {
                    try {
                        serviceHandler.onBind(service);
                    } finally {
                        conn.unbindService();
                    }
                }

                @Override
                public void onError(BillingException e) {
                    serviceHandler.onError(e);
                }
            });
        }
    });
}
 
Example #12
Source File: BillingProcessor.java    From android-easy-checkout with Apache License 2.0 6 votes vote down vote up
/**
 * Check if the device supports InAppBilling
 *
 * @param service
 * @return true if it is supported
 */
protected boolean isSupported(PurchaseType purchaseType, IInAppBillingService service) throws RemoteException {
    String type;

    if (purchaseType == PurchaseType.SUBSCRIPTION) {
        type = Constants.TYPE_SUBSCRIPTION;
    } else {
        type = Constants.TYPE_IN_APP;
    }

    int response = service.isBillingSupported(
            mContext.getApiVersion(),
            mContext.getContext().getPackageName(),
            type);

    if (response == Constants.BILLING_RESPONSE_RESULT_OK) {
        mLogger.d(Logger.TAG, "Subscription is AVAILABLE.");
        return true;
    }
    mLogger.w(Logger.TAG,
            String.format(Locale.US, "Subscription is NOT AVAILABLE. Response: %d", response));
    return false;
}
 
Example #13
Source File: BaseObservable.java    From Reactive-Billing with MIT License 6 votes vote down vote up
/**
 * For some reason, that method is always called on the main thread
 * Regardless of the originating thread executing bindService()
 */
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
    ReactiveBilling.log(null, "Service connected (thread %s)", Thread.currentThread().getName());

    IInAppBillingService inAppBillingService = IInAppBillingService.Stub.asInterface(service);
    billingService = new BillingService(context, inAppBillingService);

    if (useSemaphore) {
        // once the service is available, release the semaphore
        // that is blocking the originating thread
        ReactiveBilling.log(null, "Release semaphore (thread %s)", Thread.currentThread().getName());
        semaphore.release();
    } else {
        deliverBillingService(observer);
    }
}
 
Example #14
Source File: PurchaseFlowLauncher.java    From android-easy-checkout with Apache License 2.0 6 votes vote down vote up
private Bundle getBuyIntent(IInAppBillingService service, List<String> oldItemIds,
                            String itemId, String developerPayload) throws BillingException {
    try {
        // Purchase an item
        if (oldItemIds == null || oldItemIds.isEmpty()) {
            return service.getBuyIntent(
                    mApiVersion, mPackageName, itemId, mItemType, developerPayload);
        }
        // Upgrade/downgrade of subscriptions must be done on api version 5
        // See https://developer.android.com/google/play/billing/billing_reference.html#upgrade-getBuyIntentToReplaceSkus
        return service.getBuyIntentToReplaceSkus(
                BillingApi.VERSION_5.getValue(),
                mPackageName,
                oldItemIds,
                itemId,
                mItemType,
                developerPayload);

    } catch (RemoteException e) {
        throw new BillingException(Constants.ERROR_REMOTE_EXCEPTION, e.getMessage());
    }
}
 
Example #15
Source File: ServiceBinder.java    From android-easy-checkout with Apache License 2.0 6 votes vote down vote up
private void setBinder(android.os.IBinder binder) {
    IInAppBillingService service = IInAppBillingService.Stub.asInterface(binder);
    Handler handler = mHandler;
    mHandler = null;

    if (handler == null) {
        return;
    }
    if (service == null) {
        BillingException e = new BillingException(
                Constants.ERROR_BIND_SERVICE_FAILED_EXCEPTION,
                Constants.ERROR_MSG_BIND_SERVICE_FAILED_SERVICE_NULL);

        postBinderError(e, handler);
    } else {
        postBinder(service, handler);
    }
}
 
Example #16
Source File: BillingProcessor.java    From android-easy-checkout with Apache License 2.0 5 votes vote down vote up
/**
 * Get the purchase token to be used in {@link BillingProcessor#consumePurchase(String, ConsumeItemHandler)}
 */
private String getToken(IInAppBillingService service, String itemId) throws BillingException {
    PurchaseGetter getter = new PurchaseGetter(mContext);
    Purchases purchases = getter.get(service, Constants.ITEM_TYPE_INAPP);
    Purchase purchase = purchases.getByPurchaseId(itemId);

    if (purchase == null || TextUtils.isEmpty(purchase.getToken())) {
        throw new BillingException(Constants.ERROR_PURCHASE_DATA,
                Constants.ERROR_MSG_PURCHASE_OR_TOKEN_NULL);
    }
    return purchase.getToken();
}
 
Example #17
Source File: Accountant.java    From Noyze with Apache License 2.0 5 votes vote down vote up
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
    LogUtils.LOGI("Accountant", "onServiceConnected(" + name.toString() + ')');
    mService = IInAppBillingService.Stub.asInterface(service);
    String packageName = context.getPackageName();
    try {
        // check for in-app billing v3 support
        int response = mService.isBillingSupported(3, packageName, ITEM_TYPE_INAPP);
        if (response != BILLING_RESPONSE_RESULT_OK) {
            // LISTENER: No in-app billing
            // if in-app purchases aren't supported, neither are subscriptions.
            mSubscriptionsSupported = false;
            return;
        }

        // check for v3 subscriptions support
        response = mService.isBillingSupported(3, packageName, ITEM_TYPE_SUBS);
        if (response == BILLING_RESPONSE_RESULT_OK) {
            mSubscriptionsSupported = true;
        } else {
            // LISTENER: Doesn't support version 3.
        }

        mSetupDone = true;
    } catch (RemoteException e) {
        // LISTENER: RemoteException
        e.printStackTrace();
    }

    // LISTENER: SUCCESS!
}
 
Example #18
Source File: IabHelperTest.java    From pay-me with Apache License 2.0 5 votes vote down vote up
@Before
public void before() {
    MockitoAnnotations.initMocks(this);
    when(signatureValidator.validate(anyString(), anyString())).thenReturn(true);

    helper = new IabHelper(Robolectric.application, signatureValidator) {
        @Override
        protected IInAppBillingService getInAppBillingService(IBinder binder) {
            return service;
        }
    };
    helper.enableDebugLogging(true, getClass().getSimpleName());
    ShadowLog.stream = System.out;
}
 
Example #19
Source File: OpenFitActivity.java    From OpenFit with MIT License 5 votes vote down vote up
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
    Log.d(LOG_TAG, "Billing service connected");
    billingService = IInAppBillingService.Stub.asInterface(service);
    billing.setService(billingService);
    billing.getSkuDetails();
    billing.verifyPremium();
}
 
Example #20
Source File: OpenFitService.java    From OpenFit with MIT License 5 votes vote down vote up
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
    Log.d(LOG_TAG, "Billing service connected");
    billingService = IInAppBillingService.Stub.asInterface(service);
    billing.setService(billingService);
    billing.getSkuDetails();
    billing.verifyPremium();
}
 
Example #21
Source File: BillingProcessor.java    From RxIAPv3 with Apache License 2.0 5 votes vote down vote up
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
	billingService = IInAppBillingService.Stub.asInterface(service);
	if (!isPurchaseHistoryRestored() && loadOwnedPurchasesFromGoogle()) {
		setPurchaseHistoryRestored();
		if (billingProcessorListener != null)
                  billingProcessorListener.onPurchaseHistoryRestored();
	}
}
 
Example #22
Source File: PurchaseFlowLauncher.java    From android-easy-checkout with Apache License 2.0 5 votes vote down vote up
public void launch(IInAppBillingService service,
                   Activity activity,
                   int requestCode,
                   List<String> oldItemIds,
                   String itemId,
                   String developerPayload) throws BillingException {

    mRequestCode = requestCode;
    Bundle bundle = getBuyIntent(service, oldItemIds, itemId, developerPayload);
    PendingIntent intent = getPendingIntent(activity, bundle);

    startBuyIntent(activity, intent, requestCode);
}
 
Example #23
Source File: Accountant.java    From Noyze with Apache License 2.0 5 votes vote down vote up
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
    LogUtils.LOGI("Accountant", "onServiceConnected(" + name.toString() + ')');
    mService = IInAppBillingService.Stub.asInterface(service);
    String packageName = context.getPackageName();
    try {
        // check for in-app billing v3 support
        int response = mService.isBillingSupported(3, packageName, ITEM_TYPE_INAPP);
        if (response != BILLING_RESPONSE_RESULT_OK) {
            // LISTENER: No in-app billing
            // if in-app purchases aren't supported, neither are subscriptions.
            mSubscriptionsSupported = false;
            return;
        }

        // check for v3 subscriptions support
        response = mService.isBillingSupported(3, packageName, ITEM_TYPE_SUBS);
        if (response == BILLING_RESPONSE_RESULT_OK) {
            mSubscriptionsSupported = true;
        } else {
            // LISTENER: Doesn't support version 3.
        }

        mSetupDone = true;
    } catch (RemoteException e) {
        // LISTENER: RemoteException
        e.printStackTrace();
    }

    // LISTENER: SUCCESS!
}
 
Example #24
Source File: GoogleBillingHelper.java    From OPFIab with Apache License 2.0 5 votes vote down vote up
/**
 * Wraps {@link IInAppBillingService#getSkuDetails(int, String, String, Bundle)}.
 *
 * @param skus SKUs to load details for.
 *
 * @return Bundle containing requested SKUs details. Can be null.
 */
@Nullable
Bundle getSkuDetails(@NonNull final Collection<String> skus) {
    OPFLog.logMethod(Arrays.toString(skus.toArray()));
    final IInAppBillingService service = getService();
    if (service == null) {
        return null;
    }
    final List<String> skuList = new ArrayList<>(skus);
    final Bundle result = new Bundle();
    try {
        final int size = skuList.size();
        final int batchCount = size / BATCH_SIZE;
        for (int i = 0; i <= batchCount; i++) {
            final int first = i * BATCH_SIZE;
            final int last = Math.min((i + 1) * BATCH_SIZE, size);
            final ArrayList<String> batch = new ArrayList<>(skuList.subList(first, last));
            final Bundle bundle = GoogleUtils.putSkuList(new Bundle(), batch);
            for (final ItemType itemType : ItemType.values()) {
                final String type = itemType.toString();
                final Bundle details = service.getSkuDetails(API, packageName, type, bundle);
                final Response response = GoogleUtils.getResponse(details);
                OPFLog.d("From %d to %d. Type: %s. Response: %s. Details: %s.",
                        first, last, itemType, response, OPFUtils.toString(details));
                if (response != Response.OK) {
                    // Return received bundle if error is encountered
                    return details;
                } else {
                    // Aggregate all loaded details in a single bundle
                    final ArrayList<String> skuDetails = GoogleUtils.getSkuDetails(details);
                    GoogleUtils.addSkuDetails(result, skuDetails);
                }
            }
        }
    } catch (RemoteException exception) {
        OPFLog.e("getSkuDetails request failed.", exception);
        return null;
    }
    return GoogleUtils.putResponse(result, Response.OK);
}
 
Example #25
Source File: InAppBillingV3API.java    From Cashier with Apache License 2.0 5 votes vote down vote up
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
  logger.i("InAppBillingV3API", "onServiceConnected");
  billing = IInAppBillingService.Stub.asInterface(service);
  if (listener != null) {
    listener.initialized(available());
  }
}
 
Example #26
Source File: ServiceBinder.java    From android-easy-checkout with Apache License 2.0 5 votes vote down vote up
private void postBinder(final IInAppBillingService service, final Handler handler) {
    postEventHandler(new Runnable() {
        @Override
        public void run() {
            handler.onBind(service);
        }
    });
}
 
Example #27
Source File: ServiceTest.java    From android-easy-checkout with Apache License 2.0 5 votes vote down vote up
@Test
public void onServiceConnectedServiceNull() throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    Intent intent = new Intent(Constants.ACTION_BILLING_SERVICE_BIND);
    intent.setPackage(Constants.VENDING_PACKAGE);
    BillingContext context = mDataConverter.newBillingContext(mock(Context.class));
    ServiceBinder conn = new ServiceBinder(context, intent);

    when(context.getContext().bindService(
            any(Intent.class),
            any(ServiceConnection.class),
            eq(Context.BIND_AUTO_CREATE))
    ).thenReturn(true);

    conn.getServiceAsync(new ServiceBinder.Handler() {
        @Override
        public void onBind(IInAppBillingService service) {
            throw new IllegalStateException();
        }

        @Override
        public void onError(BillingException e) {
            assertThat(e.getErrorCode()).isEqualTo(Constants.ERROR_BIND_SERVICE_FAILED_EXCEPTION);
            assertThat(e.getMessage()).isEqualTo(Constants.ERROR_MSG_BIND_SERVICE_FAILED_SERVICE_NULL);
            latch.countDown();
        }
    });
    conn.onServiceConnected(null, null);

    latch.await(15, TimeUnit.SECONDS);
}
 
Example #28
Source File: ServiceTest.java    From android-easy-checkout with Apache License 2.0 5 votes vote down vote up
@Test
public void failedToBindIllegalArgument() throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    Intent intent = new Intent(Constants.ACTION_BILLING_SERVICE_BIND);
    intent.setPackage(Constants.VENDING_PACKAGE);
    BillingContext context = mDataConverter.newBillingContext(mock(Context.class));
    ServiceBinder conn = new ServiceBinder(context, intent);

    when(context.getContext().bindService(
            any(Intent.class),
            any(ServiceConnection.class),
            eq(Context.BIND_AUTO_CREATE))
    ).thenThrow(IllegalArgumentException.class);

    conn.getServiceAsync(new ServiceBinder.Handler() {
        @Override
        public void onBind(IInAppBillingService service) {
            throw new IllegalStateException();
        }

        @Override
        public void onError(BillingException e) {
            assertThat(e.getErrorCode()).isEqualTo(Constants.ERROR_BIND_SERVICE_FAILED_EXCEPTION);
            assertThat(e.getMessage()).isEqualTo(Constants.ERROR_MSG_BIND_SERVICE_FAILED_ILLEGAL_ARGUMENT);
            latch.countDown();
        }
    });
    latch.await(15, TimeUnit.SECONDS);
}
 
Example #29
Source File: ServiceTest.java    From android-easy-checkout with Apache License 2.0 5 votes vote down vote up
@Test
public void failedToBindNullPointer() throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    Intent intent = new Intent(Constants.ACTION_BILLING_SERVICE_BIND);
    intent.setPackage(Constants.VENDING_PACKAGE);
    BillingContext context = mDataConverter.newBillingContext(mock(Context.class));
    ServiceBinder conn = new ServiceBinder(context, intent);

    when(context.getContext().bindService(
            any(Intent.class),
            any(ServiceConnection.class),
            eq(Context.BIND_AUTO_CREATE))
    ).thenThrow(NullPointerException.class);

    conn.getServiceAsync(new ServiceBinder.Handler() {
        @Override
        public void onBind(IInAppBillingService service) {
            throw new IllegalStateException();
        }

        @Override
        public void onError(BillingException e) {
            assertThat(e.getErrorCode()).isEqualTo(Constants.ERROR_BIND_SERVICE_FAILED_EXCEPTION);
            assertThat(e.getMessage()).isEqualTo(Constants.ERROR_MSG_BIND_SERVICE_FAILED_NPE);
            latch.countDown();
        }
    });
    latch.await(15, TimeUnit.SECONDS);
}
 
Example #30
Source File: ServiceTest.java    From android-easy-checkout with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void failedToBind() throws InterruptedException, RemoteException {
    final CountDownLatch latch = new CountDownLatch(1);
    Intent intent = new Intent(Constants.ACTION_BILLING_SERVICE_BIND);
    intent.setPackage(Constants.VENDING_PACKAGE);
    BillingContext context = mDataConverter.newBillingContext(mock(Context.class));
    ServiceBinder conn = new ServiceBinder(context, intent);

    when(context.getContext().bindService(
            any(Intent.class),
            any(ServiceConnection.class),
            eq(Context.BIND_AUTO_CREATE))
    ).thenReturn(false);

    conn.getServiceAsync(new ServiceBinder.Handler() {
        @Override
        public void onBind(IInAppBillingService service) {
            throw new IllegalStateException();
        }

        @Override
        public void onError(BillingException e) {
            assertThat(e.getErrorCode()).isEqualTo(Constants.ERROR_BIND_SERVICE_FAILED_EXCEPTION);
            assertThat(e.getMessage()).isEqualTo(Constants.ERROR_MSG_BIND_SERVICE_FAILED);
            latch.countDown();
        }
    });
    latch.await(15, TimeUnit.SECONDS);
}