dependencies {
…
implementation ‘com.android.billingclient:billing:4.0.0’
}
2、初始化 BillingClient
添加对 Google Play 结算库的依赖关系后,您需要初始化 BillingClient 实例。BillingClient 是 Google Play 结算库与应用的其余部分之间进行通信的主接口。BillingClient 为许多常见的结算操作提供了方便的方法,既有同步方法,又有异步方法。我们强烈建议您一次打开一个活跃的 BillingClient 连接,以避免对某一个事件进行多次 PurchasesUpdatedListener 回调。
如需创建 BillingClient,请使用 newBuilder()。为了接收有关购买交易的更新,您还必须调用 setListener(),并传递对 PurchasesUpdatedListener 的引用。此监听器可接收应用中所有购买交易的更新。
private PurchasesUpdatedListener purchasesUpdatedListener = new PurchasesUpdatedListener() {
@Override
public void onPurchasesUpdated(BillingResult billingResult, List purchases) {
// To be implemented in a later section.
}
};
private BillingClient billingClient = BillingClient.newBuilder(activity)
.setListener(purchasesUpdatedListener)
.enablePendingPurchases()
.build();
3、连接到Google Play
在发出Google Play结算请求之前,您必须先通过以下步骤建立与Google Play的连接:
调用newBuilder() 以创建的实例。 BillingClient 您还必须调用 setListener(),将传递给引用, PurchasesUpdatedListener 以接收有关您的应用发起的购买以及Google Play商店发起的购买的更新。
建立与Google Play的连接。设置过程是异步的,BillingClientStateListener 一旦客户端的设置完成并且可以发出进一步的请求,您就必须实现A 来接收回调。
覆盖 onBillingServiceDisconnected() 回调方法,并实施您自己的重试策略,以在客户端断开连接的情况下处理与Google Play的连接丢失。例如,BillingClient如果Google Play商店服务在后台更新,则可能会失去其连接。 在发出进一步的请求之前,BillingClient必须调用 startConnection()方法重新启动连接。
billingClient.startConnection(new BillingClientStateListener() {
@Override
public void onBillingSetupFinished(BillingResult billingResult) {
if (billingResult.getResponseCode() == BillingResponseCode.OK) {
// The BillingClient is ready. You can query purchases here.
}
}
@Override
public void onBillingServiceDisconnected() {
// Try to restart the connection on the next request to
// Google Play by calling the startC