Android的应用内计费教程 [英] Android In-App Billing Tutorial

查看:121
本文介绍了Android的应用内计费教程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看来,这是相当复杂的执行应用内结算的Andr​​oid应用程序。是否有任何好的教程吗?从SDK的示例应用程序只有一个活动,哪一种过度简化它像我这样有多个活动的应用程序。

It seems that it is quite complicated to implement In-App Billing in an Android app. Are there any good tutorials for this? The sample app from the SDK only has one Activity, which kind of over-simplifies it for an application like mine that has multiple Activities.

推荐答案

嗯,我会尽力解释我经历过。我不认为自己是这方面的专家,但我打破了我的头几天。

Well, I'll try to explain what I experienced. I don't consider myself an expert on this but I broke my head several days.

对于初学者来说,我有一个非常糟糕的时间去理解的例子,该应用程序的工作流程。我想这应该是最好先从一个简单的例子,但是它的很多很难分出code小块,不知道,如果你打破任何东西。我会告诉你我有什么,我从这个例子改变,使其工作。

For starters, I had a very bad time trying to understand the workflow of the example and the application. I thought it should be better to start with a simple example however its much difficult to separate the code in small pieces and not knowing if you are breaking anything. I'll tell you what I have and what I changed from the example to make it work.

我有一个单一的活动,所有我购买来的。这就是所谓的专业。

I have a single Activity where all my purchases come from. It's called Pro.

首先,你要更新变量base64En codedPublicKey用户的安全类的公开市场开发人员密钥,否则你会看到一个漂亮的异常。

First, you should update the variable base64EncodedPublicKey in your Security class with your public Market developer key or you will see a nice Exception.

嗯,我在我的活动绑定到我的BillingService有像这样:

Well, I bind my Activity to my BillingService like so:

      public class Pro extends TrackedActivity implements OnItemClickListener {

            private BillingService mBillingService;
            private BillingPurchaseObserver mBillingPurchaseObserver;
            private Handler mHandler;

            @Override
            protected void onCreate(Bundle savedInstanceState) {    
                super.onCreate(savedInstanceState);     
                setContentView(R.layout.pro);


                //Do my stuff

                mBillingService = new BillingService();
                mBillingService.setContext(getApplicationContext());

                mHandler = new Handler();
                mBillingPurchaseObserver = new BillingPurchaseObserver(mHandler);

            }

        }



    @Override
    protected void onStart() {
       //Register the observer to the service
        super.onStart();
        ResponseHandler.register(mBillingPurchaseObserver);   
    }


    @Override
    protected void onStop() {
        //Unregister the observer since you dont need anymore
        super.onStop();
        ResponseHandler.unregister(mBillingPurchaseObserver);
    }

    @Override
    protected void onDestroy() {
       //Unbind the service
        super.onDestroy();
        mBillingService.unbind();
    }

这样一来,所有的采购谈这个服务,那么将发送JSON请求到市场。你可能会认为采购是由在同一时刻,但没有。您发送请求和购买可能会晚一点几分钟或几小时。我认为这主要是服务器过载和信用卡审批。

That way, all the purchases talk to this service, that will then, send the JSON requests to the market. You might think that the purchases are made on the same instant but no. You send the request and the purchase might come minutes or hours later. I think this is mainly to server overload and approval of the credit cards.

然后,我有我的项目一个ListView,我打开一个AlertDialog上的每个人,邀请他们购买的物品。当他们点击一个项目,我这样做:

Then I have a ListView with my items, and I open a AlertDialog on each one, inviting them to buy the item. When they click on an item, I do this:

  private class BuyButton implements DialogInterface.OnClickListener {

       private BillingItem item = null;
       private String developerPayload;

       public BuyButton(BillingItem item, String developerPayload) {
        this.item = item;
        this.developerPayload = developerPayload;
        }

            @Override
            public void onClick(DialogInterface dialog, int which) {

                if (GeneralHelper.isOnline(getApplicationContext())){
                    //I track the buy here with GA SDK. 

        mBillingService.requestPurchase(this.item.getSku(), this.developerPayload);             
                } else {                
                    Toast.makeText(getApplicationContext(), R.string.msg_not_online, Toast.LENGTH_SHORT).show();
                }

            }

        }

好吧,你应该看到,市场打开,用户无论是完成或取消购买。

Alright, you should see that the Market opens and the user either finishes or cancels the buy.

请告诉我那么重要的是我PurChaseObserver,它能够处理所有的市场发送的事件。这是它的一个精简版本,但你应该明白了吧(见我的意见throught的code):

Whats then important is my PurChaseObserver, which handles all the events that market sends. This is a stripped version of it but you should get the point (See my comments throught the code):

private class BillingPurchaseObserver extends PurchaseObserver {
        public BillingPurchaseObserver(Handler handler) {
            super(Pro.this, handler);
        }

        @Override
        public void onBillingSupported(boolean supported) {

            if (supported) {
                //Enable buy functions. Not required, but you can do stuff here. The market first checks if billing is supported. Maybe your country is not supported, for example. 
            } else {
                Toast.makeText(getApplicationContext(), R.string.billing_not_supported, Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public void onPurchaseStateChange(PurchaseState purchaseState, String itemId,
                int quantity, long purchaseTime, String developerPayload) {

//This is the method that is called when the buy is completed or refunded I believe. 
// Here you can do something with the developerPayload. Its basically a Tag you can use to follow your transactions. i dont use it. 

        BillingItem item = BillingItem.getBySku(getApplicationContext(), itemId);

        if (purchaseState == PurchaseState.PURCHASED) {
            if (item != null){
//This is my own implementation that sets the item purchased in my database. BillingHelper is a class with methods I use to check if the user bought an option and update the UI. You should also check for refunded. You can see the Consts class to find what you need to check for. 

                    boolean resu = item.makePurchased(getApplicationContext());
                    if (resu){                      
                        Toast.makeText(getApplicationContext(), R.string.billing_item_purchased, Toast.LENGTH_LONG).show();
                    }
                }
            }
        }

        private void trackPurchase(BillingItem item, long purchaseTime) {           
            //My code to track the purchase in GA
        }

        @Override
        public void onRequestPurchaseResponse(RequestPurchase request,
                ResponseCode responseCode) {

               //This is the callback that happens when you sent the request. It doesnt mean you bought something. Just that the Market received it. 

            if (responseCode == ResponseCode.RESULT_OK) {               

                Toast.makeText(getApplicationContext(), R.string.billing_item_request_sent, Toast.LENGTH_SHORT).show();

            } else if (responseCode == ResponseCode.RESULT_USER_CANCELED) {
                //The user canceled the item. 
            } else {
            //If it got here, the Market had an unexpected problem. 
            }
        }

        @Override
        public void onRestoreTransactionsResponse(RestoreTransactions request,
                ResponseCode responseCode) {
            if (responseCode == ResponseCode.RESULT_OK) {
//Restore transactions should only be run once in the lifecycle of your application unless you reinstalled the app or wipe the data. 

                SharedPreferences.Editor edit = PreferencesHelper.getInstance().getDefaultSettings(getApplicationContext()).edit();
                edit.putBoolean(Consts.DB_INITIALIZED, true);
                edit.commit();

            } else {
    //Something went wrong
            }
        }
    }

和我相信你应该不需要修改任何东西。的code剩下的作品。 您可以尝试在自己的项目android.test.purchased使用样本SKU在第一。到目前为止,我已经测试了这一点,它的工作原理,但是我仍然需要面面俱到,如退还状态。在这种情况下,我让用户保留的功能,但我想,以确保它的工作原理完美modyfing之前。

And I believe you shouldn't need to edit anything else. The rest of the code "works". You can try using the sample SKU at first in your own items "android.test.purchased". So far I have tested this and it works however I still need to cover everything like the refunded state. In this case, I am letting the user keep the features but I want to make sure it works perfect before modyfing it.

我希望它可以帮助你和其他人。

I hope it helps you and others.

这篇关于Android的应用内计费教程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆