我有一个应用程序用于购买应用程序以删除广告。如果用户已经购买了该应用程序的高级版本,则希望隐藏“删除广告”按钮。当我们收到用户是否为高级用户时,应隐藏或显示按钮。
运行billingClient查询时,我正在UI线程上运行,并且想知道是否需要在后台线程上实现它。
public class SettingsActivity extends AppCompatActivity implements
Preference.OnPreferenceChangeListener, PurchasesUpdatedListener,
View.OnClickListener {
private static final String LOG_TAG = "LOGGER: " + SettingsActivity.class.getSimpleName();
private BillingClient billingClient;
private Button bt_remove_ads;
private BillingFlowParams flowParams;
private ProgressBar adProgressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
adProgressBar = findViewById(R.id.pb_ad);
bt_remove_ads = findViewById(R.id.button_remove_ads);
bt_remove_ads.setOnClickListener(this);
setupBillingClient();
}
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
return false;
}
@Override
public void onPurchasesUpdated(BillingResult billingResult, @Nullable List<Purchase> purchases) {
//When user taps on BUY
}
@Override
public void onClick(View view) {
if (view.getId() == R.id.button_remove_ads) {
if (billingClient.isReady()) {
BillingResult billingResponseCode = billingClient
.launchBillingFlow(SettingsActivity.this, flowParams);
} else {
displayPopup(DIALOG_BILLING_NOT_READY);
}
}
}
private void setupBillingClient() {
billingClient = BillingClient
.newBuilder(this)
.enablePendingPurchases()
.setListener(this)
.build();
billingClient.startConnection(new BillingClientStateListener() {
@Override
public void onBillingServiceDisconnected() {
}
@Override
public void onBillingSetupFinished(BillingResult billingResult) {
adProgressBar.setVisibility(View.GONE);
Log.v(LOG_TAG, "onBillingSetupFinished code: " + billingResult.getResponseCode());
if (billingResult.getResponseCode() == BillingResponseCode.OK) {
final Purchase.PurchasesResult result = billingClient.queryPurchases(BillingClient.SkuType.INAPP);
if (result.getPurchasesList().isEmpty()) {
startBillingConnection();
bt_remove_ads.setVisibility(View.VISIBLE);
}
else bt_remove_ads.setVisibility(View.GONE);
}
}
});
}
private void startBillingConnection() {
List<String> skuList = new ArrayList<>();
skuList.add(IN_APP_PURCHASE_PREMIUM);
SkuDetailsParams skuDetailsParams = SkuDetailsParams.newBuilder()
.setSkusList(skuList).setType(BillingClient.SkuType.INAPP).build();
Log.v(LOG_TAG, "querySkuDetailsAsync");
billingClient.querySkuDetailsAsync(skuDetailsParams,
(responseCode, skuDetailsList) -> {
flowParams = BillingFlowParams.newBuilder()
.setSkuDetails(skuDetailsList.get(0))
.build();
});
}
}