- 在 AndroidManifest.xml 中添加以下权限:
- 在代码中创建一个广播接收器,用于接收来自 Google Play 的购买更新和到期通知:
public class BillingReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action != null) {
switch (action) {
case "com.android.vending.billing.PURCHASES_UPDATED":
// 订阅购买更新通知,这里可以添加购买成功后的处理逻辑
break;
case "com.android.vending.billing.RESPONSE_CODE":
// Google Play 返回的响应代码
int responseCode = intent.getIntExtra("RESPONSE_CODE", 0);
break;
case "com.android.vending.billing.IN_APP_NOTIFY":
// 再次收到到期通知
break;
}
}
}
}
- 在 Activity 或 Service 中注册该广播接收器:
IntentFilter filter = new IntentFilter("com.android.vending.billing.PURCHASES_UPDATED");
filter.addAction("com.android.vending.billing.RESPONSE_CODE");
filter.addAction("com.android.vending.billing.IN_APP_NOTIFY");
BillingReceiver receiver = new BillingReceiver();
registerReceiver(receiver, filter);
- 调用查询订阅信息的 API,检查订阅是否已过期:
BillingClient billingClient = BillingClient.newBuilder(this)
.setListener(new PurchasesUpdatedListener() {
@Override
public void onPurchasesUpdated(BillingResult billingResult, List list) {
// 处理购买更新通知
}
})
.build();
billingClient.startConnection(new BillingClientStateListener() {
@Override
public void onBillingSetupFinished(BillingResult billingResult) {
if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
// 查询订阅信息
List purchasesList = billingClient.queryPurchases(BillingClient.SkuType.SUBS)
.getPurchasesList();
if (purchasesList != null && !purchasesList.isEmpty()) {
for (Purchase purchase : purchasesList) {
if (purchase.getSku().equals("your_subscription_sku") &&
purchase.getPurchaseState() == Purchase.PurchaseState.PURCHASED) {
//