소스 검색

[new]优化谷歌连接逻辑

zk 1 년 전
부모
커밋
0c63b0f5b0

+ 6 - 1
app/src/main/java/com/atmob/voiceai/module/integral/IntegralPurchaseViewModel.java

@@ -220,7 +220,7 @@ public class IntegralPurchaseViewModel extends BaseViewModel {
                     @Override
                     public void onSuccess(@NonNull BillingResult billingResult) {
                         AtmobLog.d(TAG, "requestPayment onSuccess: " + billingResult);
-                        gpBillingClient.registerFlowListener(this, orderNo, purchase -> queryOrderStatus(orderNo, purchase.getPurchaseToken()));
+                        gpBillingClient.registerFlowListener(TAG, orderNo, purchase -> queryOrderStatus(orderNo, purchase.getPurchaseToken()));
                     }
 
                     @Override
@@ -287,4 +287,9 @@ public class IntegralPurchaseViewModel extends BaseViewModel {
                 });
     }
 
+    @Override
+    protected void onCleared() {
+        super.onCleared();
+        gpBillingClient.unregisterAllFlowListener(TAG);
+    }
 }

+ 2 - 4
app/src/main/java/com/atmob/voiceai/module/newsplash/NewSplashViewModel.java

@@ -69,7 +69,6 @@ public class NewSplashViewModel extends BaseViewModel {
         this.memberRepository = memberRepository;
         this.gpBillingClient = gpBillingClient;
         refreshUserInfo();
-        gpBillingClient.startUrgentConnection();
         EventHandler.report(EventId.opensubscribe_001);
         if (gpBillingClient.isSupportProductDetails()) {
             EventHandler.report(EventId.opensubhigh_001);
@@ -234,7 +233,7 @@ public class NewSplashViewModel extends BaseViewModel {
                     @Override
                     public void onSuccess(@NonNull BillingResult billingResult) {
                         AtmobLog.d(TAG, "requestPayment onSuccess: " + billingResult);
-                        gpBillingClient.registerFlowListener(this, orderNo, purchase -> queryOrderStatus(orderNo, purchase.getPurchaseToken()));
+                        gpBillingClient.registerFlowListener(TAG, orderNo, purchase -> queryOrderStatus(orderNo, purchase.getPurchaseToken()));
                     }
 
                     @Override
@@ -312,7 +311,6 @@ public class NewSplashViewModel extends BaseViewModel {
     @Override
     protected void onCleared() {
         super.onCleared();
-        gpBillingClient.endUrgentConnection();
-        gpBillingClient.unregisterAllFlowListener(this);
+        gpBillingClient.unregisterAllFlowListener(TAG);
     }
 }

+ 2 - 4
app/src/main/java/com/atmob/voiceai/module/subscription/SubscriptionPageViewModel.java

@@ -73,7 +73,6 @@ public class SubscriptionPageViewModel extends BaseViewModel {
         this.gpBillingClient = gpBillingClient;
         init();
         refreshSubscriptionDetail();
-        gpBillingClient.startUrgentConnection();
         if (gpBillingClient.isSupportProductDetails()) {
             EventHandler.report(EventId.playsethigh_001);
         } else {
@@ -267,7 +266,7 @@ public class SubscriptionPageViewModel extends BaseViewModel {
                     @Override
                     public void onSuccess(@NonNull BillingResult billingResult) {
                         AtmobLog.d(TAG, "requestPayment onSuccess: " + billingResult);
-                        gpBillingClient.registerFlowListener(this, orderNo, purchase -> queryOrderStatus(orderNo, purchase.getPurchaseToken()));
+                        gpBillingClient.registerFlowListener(TAG, orderNo, purchase -> queryOrderStatus(orderNo, purchase.getPurchaseToken()));
                     }
 
                     @Override
@@ -314,7 +313,6 @@ public class SubscriptionPageViewModel extends BaseViewModel {
     @Override
     protected void onCleared() {
         super.onCleared();
-        gpBillingClient.endUrgentConnection();
-        gpBillingClient.unregisterAllFlowListener(this);
+        gpBillingClient.unregisterAllFlowListener(TAG);
     }
 }

+ 21 - 103
app/src/main/java/com/atmob/voiceai/sdk/billing/GPBillingClient.java

@@ -19,6 +19,7 @@ import com.android.billingclient.api.Purchase;
 import com.android.billingclient.api.PurchasesUpdatedListener;
 import com.atmob.common.logging.AtmobLog;
 import com.atmob.common.runtime.ProcessUtil;
+import com.atmob.voiceai.handlers.EventHandler;
 import com.atmob.voiceai.sdk.billing.bean.GPProductInfo;
 
 import java.util.HashMap;
@@ -43,6 +44,7 @@ import atmob.reactivex.rxjava3.core.Single;
 import atmob.reactivex.rxjava3.core.SingleSource;
 import atmob.reactivex.rxjava3.disposables.Disposable;
 import atmob.reactivex.rxjava3.functions.Function;
+import atmob.reactivex.rxjava3.internal.schedulers.ExecutorScheduler;
 import atmob.reactivex.rxjava3.schedulers.Schedulers;
 
 @Singleton
@@ -51,22 +53,15 @@ public class GPBillingClient implements PurchasesUpdatedListener {
     private static final String TAG = GPBillingClient.class.getSimpleName();
 
     private final int BILLING_CLIENT_CONNECTED_TIMEOUT = 5000;
-    private final int TRY_CON_MAX_POW_TIMES = 3;
-
-    private final int TRY_URGENT_CON_TIMES = 300;
-
-    private final int TRY_URGENT_DELAY_TIME_MILLISECONDS = 200;
+    private final int TRY_CON_MAX_POW_TIMES = 8;
 
     private final BillingClient billingClient;
 
     private Disposable powConnectionDisposable;
-    private Disposable urgentConnectionDisposable;
-
-    private final ThreadPoolExecutor threadPoolExecutor;
 
     private final ReentrantLock lock = new ReentrantLock();
 
-    private Runnable urgentConnectionRunnable;
+    private final ThreadPoolExecutor threadPoolExecutor;
 
     private final BillingStrategy billingStrategy;
 
@@ -79,102 +74,11 @@ public class GPBillingClient implements PurchasesUpdatedListener {
                 .enablePendingPurchases(PendingPurchasesParams.newBuilder().enablePrepaidPlans().enableOneTimeProducts().build())
                 .build();
         billingStrategy = new BillingStrategy(billingClient);
-        threadPoolExecutor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>());
+        threadPoolExecutor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(), r -> new Thread(r, "GPBillingClientThread"));
         addApplicationLifecycleListener();
     }
 
 
-    /**
-     * 开启间隔时间较短的连接操作
-     */
-    public void startUrgentConnection() {
-        urgentConnectionRunnable = () -> {
-            if (billingClient.isReady()) {
-                return;
-            }
-            doUrgentConnection();
-        };
-        threadPoolExecutor.execute(urgentConnectionRunnable);
-    }
-
-    /**
-     * 关闭连接操作
-     */
-    public void endUrgentConnection() {
-        AtmobLog.d(TAG, "End connection.——Urgent");
-        if (urgentConnectionDisposable != null && !urgentConnectionDisposable.isDisposed()) {
-            urgentConnectionDisposable.dispose();
-        }
-        while (lock.getHoldCount() > 0) {
-            lock.unlock();
-        }
-        threadPoolExecutor.remove(urgentConnectionRunnable);
-    }
-
-
-    private void doUrgentConnection() {
-        Observable.create(emitter -> {
-                    billingClient.startConnection(new BillingClientStateListener() {
-                        @Override
-                        public void onBillingServiceDisconnected() {
-                            AtmobLog.e(TAG, "onBillingServiceDisconnected() called.——Urgent");
-                            emitter.onError(new RuntimeException("Billing service disconnected.——Urgent"));
-                        }
-
-                        @Override
-                        public void onBillingSetupFinished(@NonNull BillingResult billingResult) {
-                            AtmobLog.d(TAG, "onBillingSetupFinished() called with: billingResult = [" + billingResult + "]——Urgent");
-                            if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
-                                emitter.onNext(billingResult);
-                                emitter.onComplete();
-                            } else {
-                                emitter.onError(new RuntimeException("Billing setup failed.——Urgent"));
-                            }
-                        }
-                    });
-                })
-                .retryWhen(new Function<Observable<Throwable>, ObservableSource<?>>() {
-
-                    private final AtomicInteger count = new AtomicInteger(0);
-
-                    @Override
-                    public ObservableSource<?> apply(Observable<Throwable> throwableObservable) {
-                        return throwableObservable.takeWhile(throwable -> {
-                                    if (count.getAndIncrement() < TRY_URGENT_CON_TIMES) {
-                                        return true;
-                                    }
-                                    throw throwable;
-                                })
-                                .flatMap((Function<Throwable, ObservableSource<?>>) throwable -> Observable.timer(TRY_URGENT_DELAY_TIME_MILLISECONDS, TimeUnit.MILLISECONDS));
-                    }
-                })
-
-                .subscribe(new Observer<Object>() {
-                    @Override
-                    public void onSubscribe(@NonNull Disposable d) {
-                        urgentConnectionDisposable = d;
-                        lock.lock();
-                    }
-
-                    @Override
-                    public void onNext(@NonNull Object o) {
-
-                    }
-
-                    @Override
-                    public void onError(@NonNull Throwable e) {
-                        AtmobLog.d(TAG, "Billing connection retry times exceed max retry times, stop retry.——Urgent");
-                    }
-
-                    @Override
-                    public void onComplete() {
-                        AtmobLog.d(TAG, "Billing connection success.——Urgent");
-                        lock.unlock();
-                    }
-                });
-    }
-
-
     public boolean isSupportProductDetails() {
         return billingStrategy.isSupportProductDetails();
     }
@@ -200,6 +104,7 @@ public class GPBillingClient implements PurchasesUpdatedListener {
         });
     }
 
+
     private void endPowConnection() {
         AtmobLog.d(TAG, "End connection.");
         if (billingClient.isReady()) {
@@ -216,12 +121,14 @@ public class GPBillingClient implements PurchasesUpdatedListener {
                     billingClient.startConnection(new BillingClientStateListener() {
                         @Override
                         public void onBillingServiceDisconnected() {
+                            AtmobLog.d(TAG, "Billing connection onBillingServiceDisconnected.--" + Thread.currentThread());
                             AtmobLog.d(TAG, "Billing service disconnected.");
                             emitter.onError(new RuntimeException("Billing service disconnected."));
                         }
 
                         @Override
                         public void onBillingSetupFinished(@NonNull BillingResult billingResult) {
+                            AtmobLog.d(TAG, "Billing connection onBillingSetupFinished.--" + Thread.currentThread());
                             AtmobLog.d(TAG, "Billing setup finished with result: " + billingResult.getResponseCode() + " " + billingResult.getDebugMessage());
                             if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
                                 emitter.onNext(billingResult);
@@ -239,6 +146,7 @@ public class GPBillingClient implements PurchasesUpdatedListener {
                     @Override
                     public ObservableSource<?> apply(Observable<Throwable> throwableObservable) {
                         return throwableObservable.takeWhile(throwable -> {
+                                    AtmobLog.d(TAG, "Billing connection retryWhen.--" + Thread.currentThread());
                                     if (count.getAndIncrement() < TRY_CON_MAX_POW_TIMES) {
                                         return true;
                                     }
@@ -252,10 +160,15 @@ public class GPBillingClient implements PurchasesUpdatedListener {
                     }
                 })
                 .subscribeOn(Schedulers.io())
-                .observeOn(AndroidSchedulers.mainThread())
+                .observeOn(Schedulers.io())
                 .subscribe(new Observer<Object>() {
                     @Override
                     public void onSubscribe(@NonNull Disposable d) {
+                        threadPoolExecutor.execute(() -> {
+                            lock.lock();
+                            AtmobLog.d(TAG, "lock--" + Thread.currentThread());
+                        });
+                        AtmobLog.d(TAG, "Billing connection onSubscribe.--" + Thread.currentThread());
                         powConnectionDisposable = d;
                     }
 
@@ -271,7 +184,11 @@ public class GPBillingClient implements PurchasesUpdatedListener {
 
                     @Override
                     public void onComplete() {
-                        AtmobLog.d(TAG, "Billing connection success.");
+                        AtmobLog.d(TAG, "Billing connection success.--" + Thread.currentThread());
+                        threadPoolExecutor.execute(() -> {
+                            lock.unlock();
+                            AtmobLog.d(TAG, "unlock--" + Thread.currentThread());
+                        });
                     }
                 });
     }
@@ -280,6 +197,7 @@ public class GPBillingClient implements PurchasesUpdatedListener {
     @Override
     public void onPurchasesUpdated(@NonNull BillingResult billingResult, @Nullable List<Purchase> list) {
         AtmobLog.d(TAG, "onPurchasesUpdated() called with: billingResult = [" + billingResult + "], list = [" + list + "]");
+        EventHandler.report("orderstatus_" + billingResult.getResponseCode());
         if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK && list != null) {
             for (Purchase purchase : list) {
                 AccountIdentifiers accountIdentifiers;

+ 32 - 29
app/src/main/res/layout/activity_new_splash.xml

@@ -46,50 +46,39 @@
                 app:layout_constraintDimensionRatio="1080:936"
                 app:layout_constraintTop_toTopOf="parent" />
 
+            <Space
+                android:id="@+id/space_status_bar"
+                android:layout_width="match_parent"
+                android:layout_height="@{SizeUtil.getStatusBarHeight(), default=@dimen/app_status_bar_height}"
+                app:layout_constraintTop_toTopOf="parent" />
+
+            <Space
+                android:id="@+id/space1"
+                android:layout_width="match_parent"
+                android:layout_height="0dp"
+                app:layout_constraintDimensionRatio="360:16"
+                app:layout_constraintTop_toBottomOf="@+id/space_status_bar" />
+
+
             <androidx.core.widget.NestedScrollView
+                app:layout_constraintTop_toBottomOf="@+id/space_status_bar"
                 android:layout_width="match_parent"
                 android:layout_height="match_parent"
                 app:layout_constrainedHeight="true"
-                app:layout_constraintBottom_toTopOf="@+id/tv_auto_renewable"
-                app:layout_constraintTop_toTopOf="parent">
+                app:layout_constraintBottom_toTopOf="@+id/tv_auto_renewable">
 
 
                 <androidx.constraintlayout.widget.ConstraintLayout
                     android:layout_width="match_parent"
                     android:layout_height="match_parent">
 
-                    <Space
-                        android:id="@+id/space_status_bar"
-                        android:layout_width="match_parent"
-                        android:layout_height="@{SizeUtil.getStatusBarHeight(), default=@dimen/app_status_bar_height}"
-                        app:layout_constraintTop_toTopOf="parent" />
-
-                    <Space
-                        android:id="@+id/space1"
-                        android:layout_width="match_parent"
-                        android:layout_height="0dp"
-                        app:layout_constraintDimensionRatio="360:16"
-                        app:layout_constraintTop_toBottomOf="@+id/space_status_bar" />
-
-                    <ImageView
-                        android:id="@+id/iv_close"
-                        isInvisible="@{!newSplashViewModel.isShowCloseBtn}"
-                        android:layout_width="0dp"
-                        android:layout_height="0dp"
-                        android:layout_marginStart="14dp"
-                        android:onClick="@{()-> newSplashViewModel.onBackClick()}"
-                        android:src="@drawable/icon_new_splash_close"
-                        app:layout_constraintDimensionRatio="1:1"
-                        app:layout_constraintStart_toStartOf="parent"
-                        app:layout_constraintTop_toBottomOf="@+id/space1"
-                        app:layout_constraintWidth_percent="0.1" />
 
                     <Space
+                        app:layout_constraintTop_toTopOf="parent"
                         android:id="@+id/space2"
                         android:layout_width="match_parent"
                         android:layout_height="0dp"
-                        app:layout_constraintDimensionRatio="360:33"
-                        app:layout_constraintTop_toBottomOf="@+id/iv_close" />
+                        app:layout_constraintDimensionRatio="360:85" />
 
                     <ImageView
                         android:id="@+id/iv_logo"
@@ -196,6 +185,20 @@
 
             </androidx.core.widget.NestedScrollView>
 
+
+            <ImageView
+                android:id="@+id/iv_close"
+                isInvisible="@{!newSplashViewModel.isShowCloseBtn}"
+                android:layout_width="0dp"
+                android:layout_height="0dp"
+                android:layout_marginStart="14dp"
+                android:onClick="@{()-> newSplashViewModel.onBackClick()}"
+                android:src="@drawable/icon_new_splash_close"
+                app:layout_constraintDimensionRatio="1:1"
+                app:layout_constraintStart_toStartOf="parent"
+                app:layout_constraintTop_toBottomOf="@+id/space1"
+                app:layout_constraintWidth_percent="0.1" />
+
             <Space
                 android:id="@+id/space_bottom"
                 android:layout_width="match_parent"