在Application类中使用应用内结算

时间:2014-03-21 12:00:10

标签: java android google-play-services in-app-billing

在我的应用程序中,我有一个可以购买的应用内商品。这是应用程序的高级服务解锁程序。在扩展onCreate的类中检查Application方法中的购买状态是不是很糟糕?

这样做的优点是它可以在后台完成,而不是与活动相关联。目前,我有一个启动画面,之后我的第二个活动开始检查购买状态。它以AsyncTask运行,可能需要一段时间。因此,用户可能会看到高级版购买按钮闪烁。

我可以在启动画面Activity中执行此操作,但之后我无法访问该连接,并且无法将购买操作绑定到主Activity中的按钮。

这样我也可以在Application类中存储购买状态的布尔值。我需要从多个地方访问它。目前,我将Intent额外的值传递给需要它的活动。

唯一的缺点是连接会持续很长时间。在我的主Activity中,我在onCreate方法中绑定连接,并在onDestroy中取消绑定。它是否保持活动连接打开或是否可以在Application类中打开连接?

此外,如果在扩展Application的类中打开连接,则无法访问任何on destroy方法来关闭连接。根据{{​​3}},onTerminate类中的Application永远不会被调用,以便执行用户代码。

  

永远不会在生产Android设备上调用它   只需杀死它们即可删除进程;没有用户代码(包括   这样做时会执行此回调。

在我的主要活动中,我目前有这个

IInAppBillingService mService;
ServiceConnection mServiceConnection = new ServiceConnection() {
    @Override
    public void onServiceDisconnected(ComponentName name) {
        mService = null;
    }

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        mService = IInAppBillingService.Stub.asInterface(service);
    }
};

onCreate

@Override
public void onCreate() {
    super.onCreate();

    bindService(new Intent("com.android.vending.billing.InAppBillingService.BIND"), mServiceConnection, Context.BIND_AUTO_CREATE);

onDestroy

@Override
public void onDestroy() {
    super.onDestroy();

    if(mService != null) {
        unbindService(mServiceConnection);
    }
}

并在购买按钮的onClickListener

Bundle buyIntentBundle = mService.getBuyIntent(3, getPackageName(), "proversion", "inapp", "...");

PendingIntent pendingIntent = buyIntentBundle.getParcelable("BUY_INTENT");
if(pendingIntent != null) {
    startIntentSenderForResult(pendingIntent.getIntentSender(), PURCHASE_RESULT_CODE, new Intent(), 0, 0, 0);
}

0 个答案:

没有答案