-
Notifications
You must be signed in to change notification settings - Fork 169
/
Billing.java
1341 lines (1190 loc) · 49 KB
/
Billing.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2014 serso aka se.solovyev
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Contact details
*
* Email: [email protected]
* Site: http://se.solovyev.org
*/
package org.solovyev.android.checkout;
import com.android.vending.billing.InAppBillingServiceImpl;
import com.android.vending.billing.InAppBillingService;
import com.google.android.gms.internal.play_billing.InAppBillingServiceFactory;
import android.app.Application;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumMap;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
import static java.lang.System.currentTimeMillis;
import static org.solovyev.android.checkout.ResponseCodes.ITEM_ALREADY_OWNED;
import static org.solovyev.android.checkout.ResponseCodes.ITEM_NOT_OWNED;
/**
* A core class of the Checkout's implementation of Android's Billing API.
* This class is responsible for:
* <ol>
* <li>Connecting and disconnecting to the billing service</li>
* <li>Performing billing requests</li>
* <li>Caching the requests results</li>
* <li>Creating {@link Checkout} objects</li>
* <li>Logging</li>
* </ol>
* Though, this class can be used on its own to obtain the billing information from Android it's
* recommended to use higher abstractions, such as {@link Checkout} and {@link Inventory}, for such
* purposes.
*/
@SuppressWarnings("WeakerAccess")
public final class Billing {
static final int V3 = 3;
static final int V5 = 5;
static final int V6 = 6;
static final int V7 = 7;
static final long SECOND = 1000L;
static final long MINUTE = SECOND * 60L;
static final long HOUR = MINUTE * 60L;
static final long DAY = HOUR * 24L;
@Nonnull
private static final String TAG = "Checkout";
@Nonnull
private static final EmptyRequestListener sEmptyListener = new EmptyRequestListener();
// a list of states from which transition to this state is allowed
@Nonnull
private static final EnumMap<State, List<State>> sPreviousStates = new EnumMap<>(State.class);
@Nonnull
private static Logger sLogger = newLogger();
static {
sPreviousStates.put(State.INITIAL, Collections.<State>emptyList());
sPreviousStates.put(State.CONNECTING, Arrays.asList(State.INITIAL, State.FAILED, State.DISCONNECTED, State.DISCONNECTING));
sPreviousStates.put(State.CONNECTED, Collections.singletonList(State.CONNECTING));
sPreviousStates.put(State.DISCONNECTING, Collections.singletonList(State.CONNECTED));
sPreviousStates.put(State.DISCONNECTED, Arrays.asList(State.DISCONNECTING, State.CONNECTING));
sPreviousStates.put(State.FAILED, Collections.singletonList(State.CONNECTING));
}
@Nonnull
private final Context mContext;
@Nonnull
private final Object mLock = new Object();
@Nonnull
private final StaticConfiguration mConfiguration;
@Nonnull
private final ConcurrentCache mCache;
@Nonnull
private final PendingRequests mPendingRequests = new PendingRequests();
@Nonnull
private final BillingRequests mRequests = newRequestsBuilder().withTag(null).onBackgroundThread().create();
@GuardedBy("mLock")
@Nonnull
private final PlayStoreBroadcastReceiver mPlayStoreBroadcastReceiver;
@Nonnull
private final PlayStoreListener mPlayStoreListener = new PlayStoreListener() {
@Override
public void onPurchasesChanged() {
mCache.removeAll(RequestType.GET_PURCHASES.getCacheKeyType());
}
};
@GuardedBy("mLock")
@Nullable
private InAppBillingService mService;
@GuardedBy("mLock")
@Nonnull
private State mState = State.INITIAL;
@Nonnull
private CancellableExecutor mMainThread;
@Nonnull
private Executor mBackground = Executors.newSingleThreadExecutor(new ThreadFactory() {
@Override
public Thread newThread(@Nonnull Runnable r) {
return new Thread(r, "RequestThread");
}
});
@Nonnull
private ServiceConnector mConnector = new DefaultServiceConnector();
@GuardedBy("mLock")
private int mCheckoutCount;
public Billing(@Nonnull Context context, @Nonnull Configuration configuration) {
this(context, new Handler(), configuration);
Check.isMainThread();
}
/**
* @param context application or activity context. Needed to bind to the in-app billing
* service.
* @param configuration billing configuration
*/
public Billing(@Nonnull Context context, @Nonnull Handler handler, @Nonnull Configuration configuration) {
if (context instanceof Application) {
// mContext.getApplicationContext() might return null for applications as we allow create Billing before
// Application#onCreate is called
mContext = context;
} else {
mContext = context.getApplicationContext();
}
mMainThread = new MainThread(handler);
mConfiguration = new StaticConfiguration(configuration);
Check.isNotEmpty(mConfiguration.getPublicKey());
final Cache cache = configuration.getCache();
mCache = new ConcurrentCache(cache == null ? null : new SafeCache(cache));
mPlayStoreBroadcastReceiver = new PlayStoreBroadcastReceiver(mContext, mLock);
}
/**
* Sometimes Google Play is not that fast in updating information on device. Let's wait it a
* little bit as if we don't wait we might cache expired information (though, it will be
* updated soon as RequestType#GET_PURCHASES cache entry expires quite often)
*/
static void waitGooglePlay() {
try {
Thread.sleep(100L);
} catch (InterruptedException e) {
error(e);
}
}
@SuppressWarnings("unchecked")
@Nonnull
private static <R> RequestListener<R> emptyListener() {
return sEmptyListener;
}
static void error(@Nonnull String message) {
sLogger.e(TAG, message);
}
static void error(@Nonnull Exception e) {
final String msg = e.getMessage();
error(msg == null ? "" : msg, e);
}
static void error(@Nonnull String message, @Nonnull Exception e) {
if (e instanceof BillingException) {
final BillingException be = (BillingException) e;
switch (be.getResponse()) {
case ResponseCodes.OK:
case ResponseCodes.USER_CANCELED:
case ResponseCodes.ACCOUNT_ERROR:
sLogger.e(TAG, message, e);
break;
default:
sLogger.e(TAG, message, e);
}
} else {
sLogger.e(TAG, message, e);
}
}
static void debug(@Nonnull String subTag, @Nonnull String message) {
sLogger.d(TAG + "/" + subTag, message);
}
static void debug(@Nonnull String message) {
sLogger.d(TAG, message);
}
static void warning(@Nonnull String message) {
sLogger.w(TAG, message);
}
public static void setLogger(@Nullable Logger logger) {
Billing.sLogger = logger == null ? new EmptyLogger() : logger;
}
/**
* @return default cache implementation
*/
@Nonnull
public static Cache newCache() {
return new MapCache();
}
/**
* @return default purchase verifier
*/
@Nonnull
public static PurchaseVerifier newPurchaseVerifier(@Nonnull String publicKey) {
return new DefaultPurchaseVerifier(publicKey);
}
/**
* @return default logger
*/
@Nonnull
public static Logger newLogger() {
return new DefaultLogger(true);
}
/**
* @return logger whose methods are called only on the main thread
*/
@Nonnull
public static Logger newMainThreadLogger(@Nonnull Logger logger) {
return new MainThreadLogger(logger);
}
/**
* Cancels listener recursively
*
* @param listener listener to be cancelled
*/
static void cancel(@Nonnull RequestListener<?> listener) {
if (listener instanceof CancellableRequestListener) {
((CancellableRequestListener) listener).cancel();
}
}
@Nonnull
public Context getContext() {
return mContext;
}
@Nonnull
Configuration getConfiguration() {
return mConfiguration;
}
@Nonnull
ServiceConnector getConnector() {
return mConnector;
}
void setConnector(@Nonnull ServiceConnector connector) {
mConnector = connector;
}
void setService(@Nullable InAppBillingService service, boolean connecting) {
synchronized (mLock) {
final State newState;
if (connecting) {
if (mState != State.CONNECTING) {
// don't leak the service and disconnect directly without going through Billing#setState
if (service != null) {
mConnector.disconnect();
}
return;
}
newState = service == null ? State.FAILED : State.CONNECTED;
} else {
if (mState == State.INITIAL || mState == State.DISCONNECTED || mState == State.FAILED) {
// preserve the state
Check.isNull(mService);
return;
}
// service might be disconnected abruptly but we must go through CONNECTED->DISCONNECTING->DISCONNECTED
// routine to free the acquired resources. If, however, the current state was not
// CONNECTED (only one option left is CONNECTING) then we should directly jump to
// FAILED state as something strange has happened on the billing service side
if (mState == State.CONNECTED) {
setState(State.DISCONNECTING);
}
if (mState == State.DISCONNECTING) {
newState = State.DISCONNECTED;
} else {
Check.isTrue(mState == State.CONNECTING, "Unexpected state: " + mState);
// DISCONNECTED state can occur only after the established connection. If the
// connection was never established it's a
newState = State.FAILED;
}
}
mService = service;
setState(newState);
}
}
void setBackground(@Nonnull Executor background) {
mBackground = background;
}
void setMainThread(@Nonnull CancellableExecutor mainThread) {
mMainThread = mainThread;
}
void setPurchaseVerifier(@Nonnull PurchaseVerifier purchaseVerifier) {
mConfiguration.setPurchaseVerifier(purchaseVerifier);
}
private void executePendingRequests() {
mBackground.execute(mPendingRequests);
}
@Nonnull
State getState() {
synchronized (mLock) {
return mState;
}
}
void setState(@Nonnull State newState) {
synchronized (mLock) {
if (mState == newState) {
return;
}
Check.isTrue(sPreviousStates.get(newState).contains(mState), "State " + newState + " can't come right after " + mState + " state");
mState = newState;
switch (mState) {
case DISCONNECTING:
// as we can jump directly from DISCONNECTING to CONNECTED state let's remove
// the listener here instead of in DISCONNECTED state. That also will protect
// us from getting in the following trap: CONNECTED->DISCONNECTING->CONNECTING->FAILED
mPlayStoreBroadcastReceiver.removeListener(mPlayStoreListener);
break;
case CONNECTED:
// CONNECTED is the only state when we know for sure that Play Store is available.
// Registering the listener here also means that it should be never registered
// in the FAILED state
mPlayStoreBroadcastReceiver.addListener(mPlayStoreListener);
executePendingRequests();
break;
case FAILED:
// the play store listener should not be registered in the receiver in case of
// failure as FAILED state can't occur after CONNECTED
Check.isTrue(!mPlayStoreBroadcastReceiver.contains(mPlayStoreListener), "Leaking the listener");
mMainThread.execute(new Runnable() {
@Override
public void run() {
mPendingRequests.onConnectionFailed();
}
});
break;
}
}
}
/**
* Connects to the Billing service. Called automatically when first request is done,
* Use {@link #disconnect()} to disconnect.
* It's allowed to call this method several times, if service is already connected nothing will
* happen.
*/
public void connect() {
synchronized (mLock) {
if (mState == State.CONNECTED) {
executePendingRequests();
return;
}
if (mState == State.CONNECTING) {
return;
}
if (mConfiguration.isAutoConnect() && mCheckoutCount <= 0) {
warning("Auto connection feature is turned on. There is no need in calling Billing.connect() manually. See Billing.Configuration.isAutoConnect");
}
setState(State.CONNECTING);
mMainThread.execute(new Runnable() {
@Override
public void run() {
connectOnMainThread();
}
});
}
}
private void connectOnMainThread() {
Check.isMainThread();
final boolean connecting = mConnector.connect();
if (!connecting) {
setState(State.FAILED);
}
}
/**
* Adds {@link PlayStoreListener} possibly registering a {@link android.content.BroadcastReceiver}
* responsible for getting "com.android.vending.billing.PURCHASES_UPDATED" intent from the Play
* Store.
*
* @param listener listener to be added
*/
public void addPlayStoreListener(@Nonnull PlayStoreListener listener) {
synchronized (mLock) {
mPlayStoreBroadcastReceiver.addListener(listener);
}
}
/**
* Removes previously added {@link PlayStoreListener}. This method might also unregister the
* {@link android.content.BroadcastReceiver}.
*
* @param listener listener to be removed
*/
public void removePlayStoreListener(@Nonnull PlayStoreListener listener) {
synchronized (mLock) {
mPlayStoreBroadcastReceiver.removeListener(listener);
}
}
/**
* Disconnects from the Billing service cancelling all pending requests if any. Any subsequent
* request will automatically reconnect the Billing service. Thus, no more requests should be
* scheduled after this method has been called (otherwise the service will be connected again).
* It's allowed to call this method several times, if the service is already disconnected
* nothing happens.
*/
public void disconnect() {
synchronized (mLock) {
if (mState == State.DISCONNECTED || mState == State.DISCONNECTING || mState == State.INITIAL) {
return;
}
if (mState == State.FAILED) {
// it would be strange to change the state from FAILED to DISCONNECTING/DISCONNECTED,
// thus, just cancelling all pending the requested here and returning without updating
// the state
mPendingRequests.cancelAll();
return;
}
if (mState == State.CONNECTED) {
setState(State.DISCONNECTING);
mMainThread.execute(new Runnable() {
@Override
public void run() {
disconnectOnMainThread();
}
});
} else {
// if we're still CONNECTING - skip DISCONNECTING state
setState(State.DISCONNECTED);
}
// requests should be cancelled only when Billing#disconnect() is called explicitly as
// it's only then we know for sure that no more work should be done
mPendingRequests.cancelAll();
}
}
private void disconnectOnMainThread() {
Check.isMainThread();
mConnector.disconnect();
}
private int runWhenConnected(@Nonnull Request request, @Nullable Object tag) {
return runWhenConnected(request, null, tag);
}
<R> int runWhenConnected(@Nonnull Request<R> request, @Nullable RequestListener<R> listener, @Nullable Object tag) {
if (listener != null) {
if (mCache.hasCache()) {
listener = new CachingRequestListener<>(request, listener);
}
request.setListener(listener);
}
if (tag != null) {
request.setTag(tag);
}
mPendingRequests.add(onConnectedService(request));
connect();
return request.getId();
}
/**
* Cancels a pending request with the given <var>requestId</var>.
*
* @param requestId id of request
*/
public void cancel(int requestId) {
mPendingRequests.cancel(requestId);
}
/**
* Cancels all pending requests.
*/
public void cancelAll() {
mPendingRequests.cancelAll();
}
@Nonnull
private RequestRunnable onConnectedService(@Nonnull final Request request) {
return new OnConnectedServiceRunnable(request);
}
/**
* A factory method of {@link RequestsBuilder}.
*
* @return new instance of {@link RequestsBuilder}
*/
@Nonnull
public RequestsBuilder newRequestsBuilder() {
return new RequestsBuilder();
}
/**
* @return default requests object associated with this {@link Billing} class. All methods of
* {@link RequestListener} used in it are called on the main application thread.
*/
@Nonnull
public BillingRequests getRequests() {
return mRequests;
}
/**
* A factory method of {@link BillingRequests}. The constructed object is marked with the given
* <var>tag</var>. All methods of {@link RequestListener} used in this {@link BillingRequests}
* are called on the main application thread.
*
* @param tag requests marker
* @return requests for the given <var>tag</var>
*/
@Nonnull
public Requests getRequests(@Nullable Object tag) {
if (tag == null) {
return (Requests) getRequests();
}
return (Requests) new RequestsBuilder().withTag(tag).onMainThread().create();
}
@Nonnull
PurchaseFlow createPurchaseFlow(@Nonnull IntentStarter intentStarter, int requestCode, @Nonnull RequestListener<Purchase> listener) {
if (mCache.hasCache()) {
listener = new RequestListenerWrapper<Purchase>(listener) {
@Override
public void onSuccess(@Nonnull Purchase result) {
mCache.removeAll(RequestType.GET_PURCHASES.getCacheKeyType());
super.onSuccess(result);
}
};
}
return new PurchaseFlow(intentStarter, requestCode, listener, mConfiguration.getPurchaseVerifier());
}
@Nonnull
private <R> RequestListener<R> onMainThread(@Nonnull final RequestListener<R> listener) {
return new MainThreadRequestListener<>(mMainThread, listener);
}
public void onCheckoutStarted() {
Check.isMainThread();
synchronized (mLock) {
mCheckoutCount++;
if (mCheckoutCount > 0 && mConfiguration.isAutoConnect()) {
connect();
}
}
}
void onCheckoutStopped() {
Check.isMainThread();
synchronized (mLock) {
mCheckoutCount--;
if (mCheckoutCount < 0) {
mCheckoutCount = 0;
warning("Billing#onCheckoutStopped is called more than Billing#onCheckoutStarted");
}
if (mCheckoutCount == 0 && mConfiguration.isAutoConnect()) {
disconnect();
}
}
}
/**
* Service connection state
*/
enum State {
/**
* Service is not connected, no requests can be done, initial state
*/
INITIAL,
/**
* Service is connecting
*/
CONNECTING,
/**
* Service is connected, requests can be executed
*/
CONNECTED,
/**
* Service is disconnecting
*/
DISCONNECTING,
/**
* Service is disconnected
*/
DISCONNECTED,
/**
* Service failed to connect
*/
FAILED
}
interface ServiceConnector {
boolean connect();
void disconnect();
}
/**
* An interface that represents {@link Billing}'s configuration. Each {@link Billing} object
* gets an instance of this class when it is constructed. Once {@link Billing} is created the
* configuration can't be changed.
* A {@link DefaultConfiguration} can be used as a base class for common configurations.
*/
public interface Configuration {
/**
* This is used for verification of purchase signatures. You can find app's base64-encoded
* public key in application's page on Google Play Developer Console. Note that this
* is *not* "developer public key".
*
* @return application's public key, encoded in base64.
*/
@Nonnull
String getPublicKey();
/**
* Though, Android's Billing API claims to support client caching Checkout library uses its
* own cache. The main reason is to avoid too frequent inter-process communication (IPC)
* between the app and the billing service. This feature can be disabled if a null
* reference is returned by this method.
*
* @return cache instance to be used for caching, null for no caching
* @see Billing#newCache()
*/
@Nullable
Cache getCache();
/**
* A hook to perform a custom signature verification via {@link PurchaseVerifier}
* interface.
* One and only one instance of {@link PurchaseVerifier} is used in {@link Billing}: this
* method is called from the {@link Billing}'s constructor and the returned value is cached
* and later reused.
*
* @return {@link PurchaseVerifier} to be used to validate purchases
* @see PurchaseVerifier
*/
@Nonnull
PurchaseVerifier getPurchaseVerifier();
/**
* A fallback inventory is used to recover purchases that were done in the earlier Billing
* API versions and that can't be restored automatically in Billing API v.3
*
* @param checkout checkout
* @param onLoadExecutor executor to be used to call {@link Inventory.Callback} methods
* @return inventory to be used if Billing v.3 is not supported
*/
@Nullable
Inventory getFallbackInventory(@Nonnull Checkout checkout, @Nonnull Executor onLoadExecutor);
/**
* Internally, Checkout library connects to the Billing service and uses it to perform
* the API requests. As often only some application activities require Billing information
* there is no need in keeping the connection all the time. Starting and stopping
* {@link Billing} manually in the activities that need it is one way to solve the problem.
* Another way is to allow {@link Billing} to manage the connection itself. If
* <code>true</code> is returned from this method {@link Billing} will count all the
* {@link Checkout} objects created in it and will close the connection as soon as the last
* {@link Checkout} is destroyed.
*
* @return true if {@link Billing} should connect to/disconnect from Billing API service
* automatically
*/
boolean isAutoConnect();
}
/**
* Class that partially implements {@link Configuration} interface. {@link Billing} instance
* configured with this class will get a cache from {@link #newCache()}, a purchase verifier
* from {@link #newPurchaseVerifier(String)}, no fallback inventory and will auto-connect to
* the billing service when needed.
*/
public abstract static class DefaultConfiguration implements Configuration {
@Nullable
@Override
public Cache getCache() {
return newCache();
}
@Nonnull
@Override
public PurchaseVerifier getPurchaseVerifier() {
Billing.warning("Default purchase verification procedure is used, please read https://github.com/serso/android-checkout#purchase-verification");
return newPurchaseVerifier(getPublicKey());
}
@Nullable
@Override
public Inventory getFallbackInventory(@Nonnull Checkout checkout, @Nonnull Executor onLoadExecutor) {
return null;
}
@Override
public boolean isAutoConnect() {
return true;
}
}
/**
* {@link Configuration} that caches and re-uses some fields of the original
* {@link Configuration} passed to its constructor.
*/
private static final class StaticConfiguration implements Configuration {
@Nonnull
private final Configuration mOriginal;
@Nonnull
private final String mPublicKey;
@Nonnull
private PurchaseVerifier mPurchaseVerifier;
private StaticConfiguration(@Nonnull Configuration original) {
mOriginal = original;
mPublicKey = original.getPublicKey();
mPurchaseVerifier = original.getPurchaseVerifier();
}
@Nonnull
@Override
public String getPublicKey() {
return mPublicKey;
}
@Nullable
@Override
public Cache getCache() {
return mOriginal.getCache();
}
@Nonnull
@Override
public PurchaseVerifier getPurchaseVerifier() {
return mPurchaseVerifier;
}
void setPurchaseVerifier(@Nonnull PurchaseVerifier purchaseVerifier) {
mPurchaseVerifier = purchaseVerifier;
}
@Nullable
@Override
public Inventory getFallbackInventory(@Nonnull Checkout checkout, @Nonnull Executor onLoadExecutor) {
return mOriginal.getFallbackInventory(checkout, onLoadExecutor);
}
@Override
public boolean isAutoConnect() {
return mOriginal.isAutoConnect();
}
}
private final class OnConnectedServiceRunnable implements RequestRunnable {
@GuardedBy("this")
@Nullable
private Request mRequest;
public OnConnectedServiceRunnable(@Nonnull Request request) {
mRequest = request;
}
@Override
public boolean run() {
final Request localRequest = getRequest();
if (localRequest == null) {
// request was cancelled => finish here
return true;
}
if (checkCache(localRequest)) return true;
// request is alive, let's check the service state
final State localState;
final InAppBillingService localService;
synchronized (mLock) {
localState = mState;
localService = mService;
}
if (localState == State.CONNECTED) {
Check.isNotNull(localService);
// service is connected, let's start request
try {
localRequest.start(localService, mContext.getPackageName());
} catch (RemoteException | RuntimeException | RequestException e) {
localRequest.onError(e);
}
} else {
// service is not connected, let's check why
if (localState != State.FAILED) {
// service was disconnected
connect();
return false;
} else {
// service was not connected in the first place => can't do anything, aborting the request
localRequest.onError(ResponseCodes.SERVICE_NOT_CONNECTED);
}
}
return true;
}
private boolean checkCache(@Nonnull Request request) {
if (!mCache.hasCache()) {
return false;
}
final String key = request.getCacheKey();
if (key == null) {
return false;
}
final Cache.Entry entry = mCache.get(request.getType().getCacheKey(key));
if (entry == null) {
return false;
}
request.onSuccess(entry.data);
return true;
}
@Override
@Nullable
public Request getRequest() {
synchronized (this) {
return mRequest;
}
}
public void cancel() {
synchronized (this) {
if (mRequest != null) {
Billing.debug("Cancelling request: " + mRequest);
mRequest.cancel();
}
mRequest = null;
}
}
@Override
public int getId() {
synchronized (this) {
return mRequest != null ? mRequest.getId() : -1;
}
}
@Nullable
@Override
public Object getTag() {
synchronized (this) {
return mRequest != null ? mRequest.getTag() : null;
}
}
@Override
public String toString() {
return String.valueOf(mRequest);
}
}
/**
* A {@link BillingRequests} builder. Allows to specify request tags and result delivery
* methods
*/
public final class RequestsBuilder {
@Nullable
private Object mTag;
@Nullable
private Boolean mOnMainThread;
private RequestsBuilder() {
}
/**
* @param tag tab to be used for all requests initiated by the constructed {@link
* BillingRequests}
* @return this builder
*/
@Nonnull
public RequestsBuilder withTag(@Nullable Object tag) {
Check.isNull(mTag);
mTag = tag;
return this;
}
/**
* Makes {@link RequestListener} methods to be called on a background thread.
*
* @return this builder
*/
@Nonnull
public RequestsBuilder onBackgroundThread() {
Check.isNull(mOnMainThread);
mOnMainThread = false;
return this;
}
/**
* Makes {@link RequestListener} methods to be called on the main application thread.
* Default choice if neither this nor {@link #onBackgroundThread()} was called.
*
* @return this builder
*/
@Nonnull
public RequestsBuilder onMainThread() {
Check.isNull(mOnMainThread);
mOnMainThread = true;
return this;
}
@Nonnull
public BillingRequests create() {
return new Requests(mTag, mOnMainThread == null ? true : mOnMainThread);
}
}
final class Requests implements BillingRequests {
@Nullable
private final Object mTag;
private final boolean mOnMainThread;
private Requests(@Nullable Object tag, boolean onMainThread) {
mTag = tag;
mOnMainThread = onMainThread;
}
@Override
public int isBillingSupported(@Nonnull String product) {
return isBillingSupported(product, emptyListener());
}
@Override
public int isBillingSupported(@Nonnull String product, int apiVersion) {
return isBillingSupported(product, apiVersion, emptyListener());
}
@Override
public int isBillingSupported(@Nonnull String product, int apiVersion,
@Nonnull RequestListener<Object> listener) {
Check.isNotEmpty(product);
return runWhenConnected(new BillingSupportedRequest(product, apiVersion, null), wrapListener(listener), mTag);
}
@Override
public int isBillingSupported(@Nonnull String product, int apiVersion, @Nonnull Bundle extraParams, @Nonnull RequestListener<Object> listener) {
Check.isNotEmpty(product);
return runWhenConnected(new BillingSupportedRequest(product, apiVersion, extraParams), wrapListener(listener), mTag);
}
@Override
public int isBillingSupported(@Nonnull final String product, @Nonnull RequestListener<Object> listener) {
return isBillingSupported(product, V3, listener);